menu

Intro to Java

A concurrent, class-based, and object-oriented programming language

Java SE • Eclipse • IntelliJ
Primitive Data TypeBit SizeRangeDefault Value
byte8-128 to 1270
short16-32,768 to 32,7670
int32-231 to 231 - 10
long64-263 to 263 - 10L
float32???0.0f
double64???0.0d
booleanvariestrue/falsefalse
char160 to 65,535\u0000 (0)
The Basics
Here is a sample that shows the structure of a class and how static methods work.
public class Basics { //this is a class; the name should match the name of your file (Basics.java in this case)

    /*
     * As the name implies, this is your main method.
     * It will always start with 'public static void main(String[] args)'
     *     (Though you can change the args to any variable name).
     * Though it is not required in every file, it must exist for you to run that class.
     */
    public static void main(String[] args) {
        String text = "hi"; //creating a variable is done by [type] [variable name] = [value]; <-- don't forget the semicolon
        print(text); //pass the variable text into the print method, which will print "hi"
        print("I am Bob"); //pass the String "I am Bob" to the print method, which will print "I am Bob"
        print(join("How", "are you")); //this first calls join, which combines the two Strings, then prints it with the print method
        //note that you can call methods within other methods; the innermost method runs first
        casting(); //see casting method
    }

    /*
     * This is a separate method in this class; the method name is "print" and it returns void (nothing)
     * It will not be called unless it is executed in main or by another method called by main.
     * In this particular case, the parameter is a String named s; the naming is only important within this method
     * and is independent of whatever naming you have in other methods or in the variable you pass to this method.
     * The order in which you write methods also doesn't matter; you always start your program with main and go line by line,
     * jumping to whatever method you call in the process
     */
    public static void print(String s) {
        /*
         * Now that the method is called, you may go through the contents line by line
         * In this case, we are calling a predefined method to print the value of s, followed by a new line
         * System.out.print(s) is another method that would print s without a new line
         */
        System.out.println(s);
    }

    /*
     * This method is called "join" and will combine two Strings
     * Note that it returns String, and has two String parameters
     */
    public static String join(String s1, String s2) {
        String s3 = s1 + " " + s2; //combine both Strings with a space in between
        return s3; //as the method is defined to return a String, you must do so after the method is finished
    }

    //This method is called "casting" and takes no arguments
    public static void casting() {
        //You can call other methods within methods, as shown here:
        double percent = getPercentage("65");
        percent += 0.1; //a += b is shorthand for a = a + b; -=, *=, /= and %= also exist
        print(Double.toString(percent)); //print takes in a String, so we must convert the value into a String
        //prints 0.75
    }

    public static double getPercentage(String text) {
        //Casting is when you take something of one type and "turn it into" another type
        //There are some input methods that do so for you such as:
        try {
            int percent = Integer.parseInt(text); //attempts to parse the text into an integer
            //note that this is surrounded by a try catch block, because not every String can be converted into an int
            //more on this later
            return ((double) percent)/100; //another form of casting (which you'll see very often)
            //the desired type is put in front of the variable in parentheses
            //all integers can be casted into doubles, so this is not a problem
        } catch (NumberFormatException e) {
            //if text is not actually a valid number (ie "23a"), this error will occur
            print(text + " is not a number"); //let the user know
            return -1; //you still have to return a double; we'll make -1 the default one
        }
    }
}
Common Mistakes
if (a = b)
Comparisons within an if statement is done with two equal signs rather than one:
if (a == b)
Using a single equal sign within an if statement is still valid when you are using it for variable assignment, so long as you are not initializing a variable within the statement. For example, you may do the following:
int c;
if ((c = a) == b)
int a = 5, b = 7;
System.out.println("a + b = " + a + b);
Though this is perfectly valid, it likely does not do what you expect it to. When we call println (with a parameter of a single String), the String is created from left to right. Had it started with a + b, the two integers would first be added before proceeding with the String. In this case, we start with a String, so once we hit a + b, the two values are concatenated instead of numerically added, resulting in 57 rather than 12. Order matters, so in this case, we may simply add parantheses:
int a = 5, b = 7;
System.out.println("a + b = " + (a + b));
String[] a = new String[3]
for (int i = a.length; i > 0; i--)
	//do something
ArrayIndexOutOfBoundsExceptions are always a common source of errors in intro Java courses. Keep in mind that valid indices for any array start at 0 and end at one less than their length. The example above was relatively simple, but there are harder cases:
int[][] a = new int[][]{{1, 2, 3}, {1, 3, 9}, {1}, {0, -1}};
int b = a[0].length;
for (int i = 0; i < a.length; i++) {
	for (int j = 0; j < b; j++) {
		System.out.println(a[i][j]);
	}
}
Object References

It is very important to distinguish the difference between a reference variable and something like a primitive variable. Objects are accessed through reference variables, which are pointers pointing to the actual objects. A pointer itself can be changed to point to a different object (unless it is declared final), and can also point to the same object as another reference variable.

When you pass an object into a method, a new reference variable is created, pointing to your original object. Since both variable point to the same object, modifying x in your method will modify x in your main method. However, once you reassign your method's reference variable, you no longer access the same object as your main, and whatever you change to that variable will not be reflected outside of that method.

Reference variable behaviour is different from primitive variable behaviour; you've probably already seen swap methods for integers, swap(int x, int y);, where changing the two in the method has no effect in the main. Primitive variables are passed as a separate variable altogether, so there is no longer any association between the two.

It may also be worth noting the behaviours of Strings when passed through methods. Though they are objects, Strings are immutable, so whenever they are modified, a new object is generated and pointed to from the reference variable. Therefore, the original String passed will never be modified by other methods. The same behaviour can be seen in other classes such as BigInteger.

Below is a sample class that shows how objects are affected when passed through other methods and modified. Feel free to copy it and run it to see the results.

public class ObjectReferences {

    /*
     * Try to see if you can figure out what gets printed at each step
     * Remember that objects, like arrays, are references.
     * Be careful as to what the objects are referencing
     * You can run the code to see the results
     * Note that printing a Number will print the integer it currently holds
     * \t just means tab (more spaces)
     */
    public static void main(String[] args) {
        Number x = new Number(5);
        Number y = new Number(3);
        //This should be easy; what prints?
        System.out.println("Starting:\tx=" + x + "\t\ty=" + y);
        step1(x, y);
        System.out.println("Step 1:\t\tx=" + x + "\t\ty=" + y);
        step2(x, y);
        System.out.println("Step 2:\t\tx=" + x + "\t\ty=" + y);
        x = step3(x, y);
        System.out.println("Step 3:\t\tx=" + x + "\t\ty=" + y);
        y = new Number(step4(x, new Number(5)));
        System.out.println("Step 4:\t\tx=" + x + "\t\ty=" + y);
        System.out.println("y=" + goodLuck(x, x) + " ");
    }

    static void step1(Number y, Number x) {
        Number temp = x;
        x = y;
        y = temp;
    }

    static void step2(Number z, Number zz) {
        z.set(8);
        zz = z;
    }

    static Number step3(Number x, Number y) {
        y.set(-1);
        x = y;
        x.set(-2);
        return x;
    }

    static int step4(Number x, Number y) {
        Number z = x;
        x.set(9);
        y.set(z.get() + y.get());
        return y.get();
    }

    static Number goodLuck(Number i, Number j) {
        Number l = new Number(1);
        j.set(0);
        System.out.print("x=" + i + " ");
        i.set(9);
        j.set(8);
        return j;
    }
}

/*
 * You don't have to know what a static inner class is
 * Just know that this behaves the same way as a separate class in another file
 * This is a basic class that holds one integer, along with a set and get method
 */
class Number {
    int value = 0;

    Number(int i) { //this is a constructor
        value = i;
    }

    void set(int i) {
        value = i;
    }

    int get() {
        return value;
    }

    //This allows us to print the number directly
    @Override
    public String toString() {
        return Integer.toString(value);
    }
}