Java Tutorial 3: Arrays, Methods, Loops and Conditionals

This seems like a good point to mention that you can find documentation for all the built-in classes in Java here: Java 7 API docs.

Creating and Initializing Arrays in Java



You can declare an array of any type or class in Java by appending [] to the type declaration. When you initialize the array, must also specify either the number of items in the array or else the actual items themselves. The following code shows three different ways of creating and initializing an array. This code also illustrates accessing array elements, and finding the length of the array using the 'length' property.

    
// Array contains five references to strings, each one set to null.
String[] texts1 = new String[5];

// Set the first item in the array.
texts1[0] = "Hello";

// Create an array containing three elements
String[] texts2 = new String[]{"one", "two", "three"};

// Create an array containing four elements.
// This is a sort of shortcut for the above.
String[] texts3 = {"dog", "cat", "parrot", "snake"};

// We can get the length of an array using the length property.
System.out.println("Array three contains: " + texts3.length + " elements.");

System.out.println("The third element in the array is "" + texts3[2] + """);




Array three contains: 4 elements.
The third element in the array is "parrot"




"For" Loops in Java



"For" loops in Java luck much the same as for loops in many other languages. Here are two examples. In the second example, we iterate over an array.

// Basic 'for' loop
for(int i=0; i < 5; i++) {
    System.out.println("Index is: " + i);
}

// Output a blank line.
System.out.println("n");

// Iterate over an array.
String[] strings = {"one", "two", "three"};

for(int i=0; i < strings.length; i++) {
    System.out.println("Element " + i + " has value " + strings[i]);
}




Index is: 0
Index is: 1
Index is: 2
Index is: 3
Index is: 4


Element 0 has value one
Element 1 has value two
Element 2 has value three





"If" and "Switch"



The if and switch statements are also very similar to many other computer languages. The switch statement can often be used as an alternative to a long if ... else if ... else if ... But the disadvantage is that switch can only compare a variable to constant values.

int num = 3;
        
// If ... else statement
if(num == 1) {
    System.out.println("Number is one");
}
else if(num == 2) {
    System.out.println("Number is two");
}
else if(num == 3) {
    System.out.println("Number is three");
}

// We can use a switch instead, provided the thing
// we are comparing the variable ('num') to is constant
// (like '1' or '2' but not a variable like 'randomNumber')

switch(num) {
case 1:
    System.out.println("Case 1");
    break;
case 2:
    System.out.println("Case 2");
    break;
case 3:
    System.out.println("Case 3");
    break;
}




Methods



The following code shows a Java class that contains two methods; a 'main' method to act as the program entry point, and a method that simply displays "hello" on the console.


public class Orange {

    // Main method -- program start point
    public static void main(String[] args) {

        // Create a new "Orange" object.
        Orange orange = new Orange();
        
        // call the speak method.
        orange.speak();
        
    }
    
    // Declare a method that accepts no parameters and returns
    // none, just prints "hello"
    public void speak() {
        System.out.println("hello");
    }
    
}





hello




A Method that Accepts One Parameter



We can modify the method so that it accepts one parameter. If we pass a primitive type into a method, the method gets a copy of the variable. So the method can't modify the variable.


public class Orange {

    // Main method -- program start point
    public static void main(String[] args) {

        // Create a new "Orange" object.
        Orange orange = new Orange();
        
        // call the speak method.
        int value = 7;
        
        System.out.println("Value in method: " + value);
        
        orange.speak(value);
        
        System.out.println("Value after method: " + value);
    }
    
    // Declare a method that accepts no parameters and returns
    // none, just prints "hello"
    public void speak(int value) {
        System.out.println("Value in method: " + value);
        
        // Change 'value'. This only affects 'value' in the method
        // itself, since we are working with a copy here.
        value = 10;
    }
    
}





Value in method: 7
Value in method: 7
Value after method: 7




We can do the same thing with a string.

public class Orange {

    // Main method -- program start point
    public static void main(String[] args) {

        // Create a new "Orange" object.
        Orange orange = new Orange();
        
        // call the speak method.
        String text = "hello";
        
        System.out.println("'text' in method: " + text);
        
        orange.speak(text);
        
        System.out.println("'text' after method: " + text);
    }
    
    // Declare a method that accepts no parameters and returns
    // none, just prints "hello"
    public void speak(String text) {
        System.out.println("'text' in method: " + text);
        
        // Change 'text'. This only affects 'text' in the method
        // itself, since we are working with a copy here.
        text = "goodbye";
    }
    
}




'text' in method: hello
'text' in method: hello
'text' after method: hello




Passing by Reference vs. Passing by Value



However, there is a crucial difference between passing a primitive type and passing an object to a class. When we pass a primitive type, the type is literally copied as its passed into the method. This is called "passing by value". If we pass an object to a method, the variable that refers to the object is copied, but the variable still points to the same object, potentially allowing us to modify that object. This is called "passing by reference", or more simply, "passing a reference to an object".


In the program above, where we pass a string into a method, reassigning the string variable simply points the copy of the reference at a new string.

Let's take a look at a program that actually modifies an object via passing it to a method. First we'll create an object that allows its name to be set. This object also illustrates returning a String variable from a method. (Note -- we can pass many variables into a method using a comma-separated list, but we're only allowed to return one value).

/*
 * The Fruit class allows us to set its name instance variable.
 */
public class Fruit {
    String name = "fruit";
    
    // This method allows name to be set. Note
    // the use of 'this' which refers to the object itself.
    // 'this' allows us to distinguish the passed-in 'name'
    // parameters from the instance variable also called 'name'.
    public void setName(String name) {
        this.name = name;
    }
    
    // This method returns the name instance variable.
    public String getName() {
        return name;
    }
}




Now we'll create a FruitChanger class that starts the program, creates a fruit and passes the fruit to one of its methods, which sets the name of the fruit.


public class FruitChanger {

    // Main method -- program start point
    public static void main(String[] args) {
        
        // Create an FruitChanger so we can call its method
        FruitChanger changer = new FruitChanger();

        // Create a fruit.
        Fruit fruit = new Fruit();
        
        // Pass the fruit to a method of 'FruitChanger'
        changer.changeFruit(fruit);
        
        System.out.println("Fruit is called: " + fruit.getName());
    }
    
    public void changeFruit(Fruit fruit) {
        fruit.setName("apple");
    }
}





Fruit is called: apple




You can see that you can pass your own objects into a method just like you can pass primitive types and built-in classes like 'String' to methods.

Passing Variables to Constructors



You can also add a parameter (or multiple parameters) to a constructor in a Java class. You must then pass in a value whenever you create an object.

public class Params {
    
    // Constructor takes one parameter.
    public Params(int value) {
        System.out.println("Constructor; value is " + value);
        
        // We could use this here to initialize an instance
        // variable.
    }

    // Main method -- program start point
    public static void main(String[] args) {
        
        // We must pass the parameter to the constructor when we 
        // create an object.
        Params params = new Params(5);
        
    }
}





Constructor; value is 5




Using Static Variables to Count Objects



Sometimes you might be inclined to pass an integer to a constructor in order to assign an ID to the object. Often a better way of doing this is to use a static variable. Static variables are shared by all objects of a class. This means they can be incremented in object constructors (which are associated with particular objects, NOT the whole class) in order to provide an ID for each object.


public class Person {
    
    // This is shared by all objects of the Person class.
    static int count = 0;
    
    // This is per object
    int id = 0;

    // This is the constructor
    public Person() {
        // Increment count. So, count will be incremented every time
        // a new object is created.
        count = count + 1;
        
        // Use count to assign an ID to the object.
        id = count;
    }
    
    // This method allows us to get the ID of an object.
    public int getId() {
        return id;
    }

    // Main method -- program start point
    public static void main(String[] args) {
        
        // Create some person objects.
        Person p1 = new Person();
        Person p2 = new Person();
        Person p3 = new Person();
        
        // Display the IDs of the Person objects.
        System.out.println(p1.getId());
        System.out.println(p2.getId());
        System.out.println(p3.getId());
        
    }
}





1
2
3





Tips for Eclipse



If you're using Eclipse, the might find the following shortcuts handy:





CTRL+ddeletes the current line
type 'main' then CTRL+SPACEcreates a main method
type 'sysout' then CTRL+SPACEadds System.out.println()