Java Programming

Java ProgrammingIn this Java programming Tutorial I’ll teach you all of the core knowledge needed to write Java code in 30 minutes. This is the most popular request from everyone.

I specifically cover the following topics: primitive data types, comments, class, import, Scanner, final, Strings, static, private, protected, public, constructors, math, hasNextLine, nextLine, getters, setters, method overloading, Random, casting, toString, conversion from Strings to primitives, converting from primitives to Strings, if, else, else if, print, println, printf, logical operators, comparison operators, ternary operator, switch, for, while, break, continue, do while, polymorphism, arrays, for each, multidimensional arrays and more.

If you like videos like this it helps my Google search rank when you share on Google Plus with a click here

If you prefer a slower Java tutorial I have one here. Here I show you how to install Eclipse and Java.

Java Programming Code

// A Single line comment

/* A 
 * Multiple line
 * comment

// You can import libraries with helpful methods using import

import java.util.Scanner;
import java.util.*;

// A class defines the attributes (fields) and capabilities (methods) of a real world object

public class Animal {
	// static means this number is shared by all objects of type Animal
	// final means that this value can't be changed
	public static final double FAVNUMBER = 1.6180;
	// Variables (Fields) start with a letter, underscore or $
	// Private fields can only be accessed by other methods in the class
	// Strings are objects that hold a series of characters
	private String name;
	// An integer can hold values from -2 ^ 31 to (2 ^ 31) -1
	private int weight;
	// Booleans have a value of true or false
	private boolean hasOwner = false;
	// Bytes can hold the values between -128 to 127
	private byte age;
	// Longs can hold the values between -2 ^ 63 to (2 ^ 63) - 1
	private long uniqueID;
	// Chars are unsigned ints that represent UTF-16 codes from 0 to 65,535
	private char favoriteChar;
	// Doubles are 64 bit IEEE 754 floating points with decimal values
	private double speed;
	// Floats are 32 bit IEEE 754 floating points with decimal values
	private float height;
	// Static variables have the same value for every object 
	// Any variable or function that doesn't make sense for an object to have should be made static
	// protected means that this value can only be accessed by other code in the same package
	// or by subclasses in other packages
	protected static int numberOfAnimals = 0;
	// A Scanner object allows you to except user input from the keyboard
	static Scanner userInput = new Scanner(;
	// Any time an Animal object is created this function called the constructor is called
	// to initialize the object
	public Animal(){
		// Shorthand for numberOfAnimals = numberOfAnimals + 1;
		int sumOfNumbers = 5 + 1;
		System.out.println("5 + 1 = " + sumOfNumbers);
		int diffOfNumbers = 5 - 1;
		System.out.println("5 - 1 = " + diffOfNumbers);
		int multOfNumbers = 5 * 1;
		System.out.println("5 * 1 = " + multOfNumbers);
		int divOfNumbers = 5 / 1;
		System.out.println("5 / 1 = " + divOfNumbers);
		int modOfNumbers = 5 % 3;
		System.out.println("5 % 3 = " + modOfNumbers);
		// print is used to print to the screen, but it doesn't end with a newline \n
		System.out.print("Enter the name: \n");
		// The if statement performs the actions between the { } if the condition is true
		// userInput.hasNextLine() returns true if a String was entered in the keyboard
			// this provides you with a way to refer to the object itself
			// userInput.nextLine() returns the value that was entered at the keyboard
			// hasNextInt, hasNextFloat, hasNextDouble, hasNextBoolean, hasNextByte,
			// hasNextLong, nextInt, nextDouble, nextFloat, nextBoolean, etc.
	// It is good to use getter and setter methods so that you can protect your data
	// In Eclipse Right Click -> Source -> Generate Getter and Setters
	public String getName() {
		return name;

	public void setName(String name) { = name;

	public int getWeight() {
		return weight;

	public void setWeight(int weight) {
		this.weight = weight;

	public boolean isHasOwner() {
		return hasOwner;

	public void setHasOwner(boolean hasOwner) {
		this.hasOwner = hasOwner;

	public byte getAge() {
		return age;

	public void setAge(byte age) {
		this.age = age;

	public long getUniqueID() {
		return uniqueID;

	// Method overloading allows you to accept different input with the same method name
	public void setUniqueID(long uniqueID) {
		this.uniqueID = uniqueID;
		System.out.println("Unique ID set to: " + this.uniqueID);
	public void setUniqueID() {
		long minNumber = 1;
		long maxNumber = 1000000;
		// Generates a random number between 1 and 1000000
		this.uniqueID = minNumber + (long)(Math.random() * ((maxNumber - minNumber) + 1));
		// You can cast from one primitive value into another by putting what you want between ( )
		// (byte) (short) (long) (double)
		// (float), (boolean) & (char) don't work.
		// (char) stays as a number instead of a character
		// You convert from a primitive to a string like this
		String stringNumber = Long.toString(maxNumber);
		// Byte.toString(bigByte); Short.toString(bigShort); Integer.toString(bigInt);
		// Float.toString(bigFloat); Double.toString(bigDouble); Boolean.toString(trueOrFalse);
		// You convert from a String to a primitive like this
		int numberString = Integer.parseInt(stringNumber);
		// parseShort, parseLong, parseByte, parseFloat, parseDouble, parseBoolean
		System.out.println("Unique ID set to: " + this.uniqueID);

	public char getFavoriteChar() {
		return favoriteChar;

	public void setFavoriteChar(char favoriteChar) {
		this.favoriteChar = favoriteChar;
	public void setFavoriteChar() {
		int randomNumber = (int) (Math.random() * 126) + 1;
		this.favoriteChar = (char) randomNumber;
		// if then else statement
		// > < == != >= <=
		if(randomNumber == 32){
			System.out.println("Favorite character set to: Space");
		} else if(randomNumber == 10){
			System.out.println("Favorite character set to: New Line");
		} else {
			System.out.println("Favorite character set to: " + this.favoriteChar);
		// Logical operators
		// ! : Converts the boolean value to its right to its opposite form ie. true to false
		// & : Returns true if boolean value on the right and left are both true (Always evaluates both boolean values)
		// && : Returns true if boolean value on the right and left are both true (Stops evaluating after first false)
		// | : Returns true if either boolean value on the right or left are true (Always evaluates both boolean values)
		// || : Returns true if either boolean value on the right or left are true (Stops evaluating after first true)
		// ^ : Returns true if there is 1 true and 1 false boolean value on the right or left
		if((randomNumber > 97) && (randomNumber < 122)){
			System.out.println("Favorite character is a lowercase letter");
		if(((randomNumber > 97) && (randomNumber < 122)) || ((randomNumber > 64) && (randomNumber < 91))){
			System.out.println("Favorite character is a letter");
			System.out.println("I turned false to " + !false);
		// The ternary operator assigns one or another value based on a condition
		int whichIsBigger = (50 > randomNumber) ? 50 : randomNumber;
		System.out.println("The biggest number is " + whichIsBigger);
		// The switch statement is great for when you have a limited number of values
		// and the values are int, byte, or char unless you have Java 7 which allows Strings
		case 8 :
			System.out.println("Favorite character set to: Backspace");
		case 9 :
			System.out.println("Favorite character set to: Horizontal Tab");
		case 10 :
		case 11 :
		case 12 :
			System.out.println("Favorite character set to: Something else weird");
		default :
			System.out.println("Favorite character set to: " + this.favoriteChar);

	public double getSpeed() {
		return speed;

	public void setSpeed(double speed) {
		this.speed = speed;

	public float getHeight() {
		return height;

	public void setHeight(float height) {
		this.height = height;

	protected static int getNumberOfAnimals() {
		return numberOfAnimals;

	// Since numberOfAnimals is Static you must set the value using the class name
	public void setNumberOfAnimals(int numberOfAnimals) {
		Animal.numberOfAnimals = numberOfAnimals;
	protected static void countTo(int startingNumber){
		for(int i = startingNumber; i <= 100; i++){
			// continue is used to skip 1 iteration of the loop
			if(i == 90) continue;
	protected static String printNumbers(int maxNumbers){
		int i = 1;
		while(i < (maxNumbers / 2)){
			// This isn't needed, but if you want to jump out of a loop use break
			if(i == (maxNumbers/2)) break;
		// You can return a value like this
		return "End of printNumbers()";
	protected static void guessMyNumber(){
		int number;
		// Do while loops are used when you want to execute the code in the braces at least once
		do {
			System.out.println("Guess my number up to 100");
			// If what they entered isn't a number send a warning
				String numberEntered =;
				System.out.printf("%s is not a number\n", numberEntered);
			number = userInput.nextInt();
		}while(number != 50);
		System.out.println("Yes the number was 50");
	// This will be used to demonstrate polymorphism
	public String makeSound(){
		return "Grrrr";
	// With polymorphism we can refer to any Animal and yet use overridden methods 
	// in the specific animal type
	public static void speakAnimal(Animal randAnimal){
		System.out.println("Animal says " + randAnimal.makeSound());

	// public allows other classes to use this method
	// static means that only a class can call for this to execute 
	// void means it doesn't return a value when it finishes executing
	// This method can except Strings that can be stored in the String array args when it is executed
	public static void main(String[] args){
		Animal theDog = new Animal();
		System.out.println("The animal is named " + theDog.getName());
		// An array is a fixed series of boxes that contain multiple values of the same data type
		// How you create arrays
		// int[] favoriteNumbers;
		// favoriteNumbers = new int[20];
		int[] favoriteNumbers = new int[20];
		favoriteNumbers[0] = 100;
		String[] stringArray = {"Random", "Words", "Here"};
		// for(dataType[] varForRow : arrayName)
		for(String word : stringArray)
		// This is a multidimensional array
		String[][][] arrayName = { { { "000" }, { "100" }, { "200" }, { "300" } },
			     { { "010" }, { "110" }, { "210" }, { "310" } }, 
				 { { "020" }, { "120" }, { "220" }, { "320" } }};
		for(int i = 0; i < arrayName.length; i++)
			for(int j = 0; j < arrayName[i].length; j++)
				for(int k = 0; k < arrayName[i][j].length; k++)
					System.out.print("| " + arrayName[i][j][k] + " ");
		// You can copy an array (stringToCopy, indexes to copy)
		String[] cloneOfArray = Arrays.copyOf(stringArray, 3);
		// You can print out the whole array
		// Returns the index or a negative number
		System.out.println(Arrays.binarySearch(cloneOfArray, "Random"));

// Since Cat extends Animal it gets all of Animals fields and methods
// This is called inheritance
public class Cat extends Animal{

	public Cat() {
	// Overriding the Animal method
	public String makeSound(){
		return "Meow";
	public static void main(String[] args) {
		Animal fido = new Dog();
		Animal fluffy = new Cat();
		// We can have an array of Animals that contain more specific subclasses
		// Any overridden methods are used instead because of polymorphism
		Animal[] theAnimals = new Animal[10];
		theAnimals[0] = fido;
		theAnimals[1] = fluffy;
		System.out.println("Fido says " + theAnimals[0].makeSound());
		System.out.println("Fluffy says " + theAnimals[1].makeSound());
		// We can also pass subclasses of Animal and they just work


// Since Dog extends Animal it gets all of Animals fields and methods
// This is called inheritance
public class Dog extends Animal{

	public Dog() {
	// You can override Animal methods
	public String makeSound(){
		return "Woof";
	public static void main(String[] args) {
		Dog fido = new Dog();


36 Responses to “Java Programming”

  1. Alexander says:

    Hey, I really enjoy your videos and I have much respect for you.

    How can I go further into learning the java language?
    For example how can I train and test what I have in my knowledge?

  2. Swati says:

    Hi Derek,

    I really like the way you explain. I would like to know and learn the difference between Java 6 and Java 7 and also about new features of Java 8.
    Have already given tutorial on this ? If not, please point out the differences / additions / enhancements of Java 6, Java 7, Java 8 if possible. That would be of great help. This is actually a basic interview question for which there is no proper answer on internet.

    I hope to see the tutorial soon 🙂

    Thank you for wonderful tutorials. Keep up the good work !


  3. ILoveJava says:

    Hi Derek – Thanks very much! This is a lot of stuff put togther in best possible way.

    Appreciate your Tutorial. 🙂

  4. ThankYouDereke says:

    Hi Derek. You are doing an awsome work for mankind. ThankYou.

    I really want to be a Software Developer in Java and would like to have some advices from you.

    Thank you a lot.

  5. Mike says:

    hi im a complete newbie where do i start from? Your tutorial was great but alot of it went over my head as expected

  6. bs says:

    nice job derek on both java and php. was wondering if you could do video – address and compare lambda vs closure vs java vs lambda in php?? obviously i havent messed with them much but to understand the difference wud totally help. thanks kindly.

  7. Saul says:

    very nice video, a little bit too fast but I think it will help me with my project. I am going to start watching your videos, I am trying to learn java for my class and the other videos that I’ve seen don’t have that much of explanation. I hope your videos make me understand what I could not understand 2 computer science classes before

    • Derek Banas says:

      Thank you 🙂 I have another Java tutorial that covers everything in more depth. I have hundreds of Java tutorials. Take a look at them by putting your mouse over videos in the top menu.

      • Saul says:

        is there any video that you would recommend for me to create a book contact project? I would like to create all these in my project public interface ProjTwo {
        public void readInitialFromFile();
        public void writeFinalToFile();
        public void addContact(Contact c);
        public void deleteContact(String nm);
        public void showByName(String nm);
        public void showByPhoneNumber(long pN);
        public void showByComment(String c);

        and Driver2

  8. Alexandru says:

    Hello Derek. I have started learning Java from the book Head First Java – 2nd Edition, you recommended on your youtube channel. Can you please tell me the next book / books you recommend to expand my knowledge? I want to learn the language properly before starting with your great playlist of tutorials. Thanks in advance, have a great day.

  9. joseph says:

    very comprehensive video tutorials. thanks !

  10. Michael says:

    Hi Derek! Awesome job you have done! It’s the best tutorial video of core Java that I have ever gone through! I just finish my study of core Java, and the video content, though only 30 minutes, has covered what I have learned in the past two months , and even more!

    It is really impressive video and I appreciate your share and your effort. You do have my respect!

    And I have a question here, since I have just finished my study of core Java, what do you think is the next move on the way to become a real java programmer ? I mean, what to learn after core java? Where can I find some project to practice my coding?

    Another question Is web development or mobile development a better market to enter in the coming few years?

    Thank you!

    • Derek Banas says:

      Thank you for the compliment 🙂 I’d say the next thing you need to work on is problem solving. i cover that in my UML, object oriented design, design patterns and refactoring tutorials. There is a ton of web development work out there. PHP is still the dominate language there though. I have also found a ton of mobile work by focusing on creating private apps for small business owners. It doesn’t seem like I have any competition locally for that. Best of luck.

  11. Ronald Kaylor says:

    I found your video on YouTube as I am in a Java class and this has really helped me get a better handle on what I am doing. THANK YOU for the video and this page.

  12. No words to appreciate you you are awesome.This saved me a lot of time.Expect more great tutorials from you like this one.

  13. Andrea lee says:

    Hi Derek,
    Thanks for all of the wonderful java video I enjoy so much. May I know if you are still going to teach hibernate, spring & other related video.

  14. Andrei says:

    Hello, Derek,

    Thanks a lot for your awesome work!
    I am quite new to this so I will really appreciate some advice. The copy/pasted code does not compile on Eclipse, I get the message “Build path specifies execution environment OSGi/Minimum-1.2. There are no JREs installed in the workspace that are strictly compatible with this environment.” To solve this, I have tried new projects and tried different options in the field “use an execution environment JRE”. It didn’t work. Probably the problem comes from other versions of java I previously had on my computer.
    If I run java -version on Command Prompt I get 1.8.0_31 version even if I deleted the 8th version and reconnected Eclipse to the 7th version (in Preferences Installed JREs).
    I also have from previous trials a program called DrJava and there the code is compiling, but I want to run it in Eclipse so I can follow you better and I also want to understand what I did wrong.

    Thanks a lot!

Leave a Reply

Your email address will not be published.