Saturday 27 June 2015

Flow Control 7: Branching Statements - continue

public class ContinueDemo {
        /* The continue statement works in a similar way
         * to the break statement. It works with for,
         * while and do-while loops and comes in labelled
         * and unlabelled forms.
         *
         * When invoked, continue skips the current iteration
         * of the loop.
         */
        public static void main(String[] args) {
                // Unlabelled example of continue.
                String searchMe = "peter piper picked a peck of pickled peppers.";
                int max = searchMe.length();
                int numPs = 0;

                for (int i = 0; i < max; i++) {
                        if (searchMe.charAt(i) != 'p')
                                continue;

                        numPs++;
                }
                System.out.println("Found " + numPs + " Ps.\n");

                // Labelled example of continue.
                searchMe = "Look for a sub string in me.";
                String substring = "sub";
                boolean foundIt = false;
                max = searchMe.length() - substring.length();

                test:
                        for (int i = 0; i <= max; i++) {
                                int n = substring.length();
                                int j = i;
                                int k = 0;

                                while (n-- != 0) {
                                        if (searchMe.charAt(j++) != searchMe.charAt(k++)) {
                                                continue test;
                                        }
                                }

                                foundIt = true;
                                        break test;
                        }
                        System.out.println(foundIt ? "Fount it" : "Didn't find it");
        }
}

Wednesday 17 June 2015

Flow Control 6: Branching Statements - Labelled break

public class LabelledBreakDemo {
        /* In this example the labelled break statement
         * terminates the outermost loop.
         */
        public static void main(String[] args) {
                int[][] numbers = {
                                {1,2,3,4,5},
                                {10,20,30,40,50},
                                {100,200,300,400,500}
                };
                boolean foundIt = false;
                int searchFor = 30;
                int i = 0;
                int j = 0;

                search: // This is the label for the outer loop.
                        for (i = 0; i < numbers.length; i++) {
                                for (j = 0; j < numbers[i].length; j++) {
                                        if (numbers[i][j] == searchFor) {
                                                foundIt = true;
                                                break search;
                                        }
                                }
                        }

                if (foundIt) {
                        System.out.println(searchFor + " found at position " + i + ":" + j);
                } else {
                        System.out.println(searchFor + " could not be found.");
                }
        }
}

Monday 15 June 2015

Flow Control 5: Branching Statements - break

public class BreakDemo {
        /* break statements are used to terminate
         * switch blocks, for, while and do-while loops.
         */
        public static void main(String[] args) {
                // Variable declarations;
                int i = 2;
                int searchFor = 3;
                int[] numbers = {0,1,2,3,4,5};
                boolean foundIt = false;

                // Simple switch block with break statements.
                switch (i) {
                        case 0:
                                System.out.println("A = " + (i++));
                                break;
                        case 1:
                                System.out.println("A = " + (i++));
                                break;
                        case 2:
                                System.out.println("A = " + (i++));
                                break;
                        default:
                                System.out.println("Resetting A.");
                                i = 0;
                                break;
                }

                // Simple for loop with a break statement.
                for (i = 0; i < numbers.length; i++) {
                        if (numbers[i] == searchFor) {
                                foundIt = true;
                                break;
                        }
                }
                if (foundIt) {
                        System.out.println(searchFor + " is at index " + i);
                } else {
                        System.out.println(searchFor + " could not be found.");
                }

                // Simple while loop with a break statement.
                while(foundIt) {
                        System.out.println("i = " + (i++));
                        if (i == 100) {
                                System.out.println("i = " + i);
                                i = 0;
                                break;
                        }
                }

                // Simple do-while loop with a break statement.
                do {
                        if (i == 100) {
                                System.out.println("i = " + i);
                                break;
                        }
                        System.out.println("i = " + (i++));
                } while (foundIt);

                /* Since there is no code included in either
                 * of the while or do-while loops to make foundIt
                 * false. Both loops should effectively be infinite.
                 * However using if-then with break gives us another
                 * opportunity to test for a condition that should
                 * terminate the loop.
                 */
        }
}

Sunday 14 June 2015

Flow Control 4: for

public class ForLoopDemo {
        /* In addition to the while and do-while loops.
         * The Java language also provides the for loop.
         * This is used to iterate through a range of values.
         */
        public static void main(String[] args) {
                // Count to 5 with a basic for loop.
                for (int A = 0; A <= 5; A++){
                        System.out.println("A = " + A);
                }

                /* So the code above executes for as long as the
                 * value of A is less than or equal to 5.
                 *
                 * The next example will work it's way through
                 * an array. This is called an enhanced for loop.
                 */
                int[] B = {6,7,8,9,10};
               
                for (int item : B) {
                        System.out.println("B = " + item);
                }

                // We can also do the same for strings.
                String[] months = {"January","February","March","April","May","June",
                        "July","August","September","October","November","December"};

                for (String item : months) {
                        System.out.println("The month is " + item);
                }
        }
}

Flow Control 3: while, do-while

public class WhileLoopDemo {
        /* The Java Language provides the while and do-while
         * loops to allow code to execute repeatedly until a
         * condition is no longer true.
         *
         * The primary difference between while and do-while
         * is the point at which the expression is evaluated.
         *
         * For while loops the expression is evaluated at the
         * top of the loop. The beginning of the code block.
         * So if the expression evaluates to false. The
         * following statements will not run.
         *
         * do-while loops evaluate their expression at the bottom
         * of the loop. The end of the code block. So do-while
         * loops ALWAYS execute their statements at least once.
         */
        public static void main(String[] args) {
                int A = 0;
                int B = 5;

                /* The code in this while loop will only run
                 * because A is less than B.
                 */
                while(A < B) {
                        System.out.println("A = " + (A++));
                }

                // Now that A is = to B the code won't run any more.
                while(A < B) {
                        System.out.println("A = " + (A++));
                }

                /* But if we use a do-while loop. The code should run at
                 * least once.
                 */
                do {
                        System.out.println("\nThis is a do-while loop.");
                        System.out.println("A = " + (A++));
                } while (A < B);
        }
}

Flow Control 2: Switch Blocks

public class SwitchBlockDemo {
        public static void main(String[] args) {
                int A = 0;

                // if-then-else purely for comparison to switch
                if(A == 0){
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else if(A == 1) {
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else if(A == 2) {
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else if(A == 3) {
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else if(A == 4) {
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else if(A == 5) {
                        System.out.println("A = " + A + "\n");
                        ++A;
                } else {
                        System.out.println("A = " + A);
                        System.out.println("A is not 0. A will be reset.");
                        System.out.println("If only we had some way to loop this code.");
                        A = 0;
                }

                /* Unlike the if-then-else code above, the switch
                 * block below will execute all the code that comes
                 * after the matching case statement.
                 */
                switch (A) {
                        case 0: System.out.println("A = " + (A++));
                        case 1: System.out.println("A = " + (A++));
                        case 2: System.out.println("A = " + (A++));
                        case 3: System.out.println("A = " + (A++));
                        case 4: System.out.println("A = " + (A++));
                        case 5: System.out.println("A = " + A);
                        default:
                        System.out.println("A is not 0. A will be reset.\n");
                                A = 0;
                                break;
                }

                // This is a condensed version of the above switch block.
                switch (A) {
                        case 1: case 2: case 3: case 4: case 5:
                                System.out.println("\nA = " + (A++));
                        default:
                                System.out.println("A is not equal to 0. A will be reset");
                                System.out.println("If only I could loop this code.");
                                A = 0;
                                break;
                }

                /* Adding break statements "breaks" the program out of the switch
                 * block. The default code executes when none of the case statements
                 * are satisfied. A break statement is not needed here. But it can
                 * help make the code more robust and readable.
                 */
                switch (A) {
                        case 0:
                                System.out.println("A = " + (A++));
                                break;
                        case 1:
                                System.out.println("A = " + (A++));
                                break;
                        case 2:
                                System.out.println("A = " + (A++));
                                break;
                        case 3:
                                System.out.println("A = " + (A++));
                                break;
                        case 4:
                                System.out.println("A = " + (A++));
                                break;
                        case 5:
                                System.out.println("A = " + A);
                                break;
                        default:
                                System.out.println("A is not 0. A will be reset.");
                                A = 0;
                                break;
                }
        }
}

Note:
When coding the switch blocks in the examples above. Eclipse decided they should not be indented. Forcing Eclipse to indent these switch blocks properly wasn't too hard. It just meant correcting the error a few times.

Indentation is clearly not mandatory in Java. However Oracle's own examples are indented. So I presume this is how switch blocks are supposed to be written.

Saturday 13 June 2015

Flow Control 1: if-then-else

public class IfThenElse {
        /* Programs normally execute one line after the other
         * from top to bottom. But sometimes we need to make
         * decisions while a program is running. Some of these
         * decisions will send a program down one path or another.
         *
         * To do this in Java we use if-then and if-then-else
         * statements.
         */
        public static void main(String[] args) {
                int A = 0;

                /* Basic if-then statement
                 * Since there is only one line of code to be
                 * executed after the if-then statement we
                 * don't need braces {}.
                 *
                 * NOTE: We don't actually need to type "then", it is implied.
                 */
                if(A == 0)
                        System.out.println("First run.\nA = " + A);

                /* A more complex if-then statement. We now need braces
                 * to enclose our "block" of code.
                 */
                if(A == 0) {
                        System.out.println("\nSecond Run.");
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + A);
                }

                /* Both of the examples above will only print A if it
                 * is 0 when tested. When A is not 0 we need to be
                 * able to take a different course of action. Even
                 * if that is simply telling the user what has happened.
                 * We do this by adding else to if-then.
                 */
                if(A == 0) {
                        System.out.println("\nThird Run.");
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + (A++));
                        System.out.println("A = " + A);
                } else {
                        System.out.println("\nThird Run.");
                        System.out.println("A is not 0. A will be reset.");
                        A = 0;
                }

                /* It is also possible to add additional if statements.
                 * This allows us to have many options. In the code below
                 * only of the options will execute depending on the value
                 * of A.
                 */
                if(A == 0){
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else if(A == 1) {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else if(A == 2) {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else if(A == 3) {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else if(A == 4) {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else if(A == 5) {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        ++A;
                } else {
                        System.out.println("\nFourth Run.");
                        System.out.println("A = " + A);
                        System.out.println("A is not 0. A will be reset.");
                        System.out.println("If only we had some way to loop this code.");
                        A = 0;
                }
        }
}

Thursday 11 June 2015

Type Comparison Demo

class Bicycle{
        // Just a Stub.
}
class MBike extends Bicycle{
        // Just a Stub.
}

public class TypeComparisonDemo {
        /* The instanceof operator allows us to compare an
         * object to a specific type.
         */
        public static void main(String[] args) {
                Bicycle bike1 = new Bicycle();
                MBike bike2 = new MBike();

                System.out.println("bike1 is a Bicycle? " + (bike1 instanceof Bicycle));
                System.out.println("bike1 is a Bicycle? " + (bike1 instanceof MBike));
                System.out.println("bike2 is a Bicycle? " + (bike2 instanceof Bicycle));
                System.out.println("bike2 is a Bicycle? " + (bike2 instanceof MBike));
        }
}

Wednesday 10 June 2015

Conditional Operators

public class ConditionalDemo {
        /* && conditional AND
         * || conditional OR
         */
        public static void main(String[] args) {
                int val1 = 100;
                int val2 = 500;

                // Test if val1 is equal 100 AND val2 is equal to 500.
                if((val1 == 100) && (val2 == 500))
                        System.out.println("val1 equals 100 and val2 equals 500");

                /* Change val2 to 300. But keep the test the same. The
                 * print statement should not execute as the values no longer
                 * meet the test criteria.
                 */
                val2 = 300;

                if((val1 == 100) && (val2 == 500))
                        System.out.println("val1 equals 100 and val2 equals 500");

                /* Test if val1 is 100 OR val2 is 500. Only one of the values
                 * will need to meet the test criteria.
                 */

                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);

                // Change the test so val2 is 500 and val1 is 900.
                val1 = 900;
                val2 = 500;

                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);

                // Now none of the values match.
                val2 = 0;
                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);
        }
}

Equality And Relational Operators 2

public class ComparisonDemo2 {
        /* > greater than
         * >= greater than or equal to
         * < less than
         * <= less than or equal to
         */
        public static void main(String[] args) {
                int A = 1;
                int B = 0;

                // Test if A is greater than B.
                if(A > B)
                        System.out.println("A is greater than B.");

                // Test if A is greater than or equal to B;
                if(A >= B)
                        System.out.println("A is greather than or equal to B.");

                ++B; // Increment B.

                // Test if A is greater than or equal to B.
                if(A >= B)
                        System.out.println("A is greather than or equal to B.");

                // Test if A is less than or equal to B.
                if(A <= B)
                        System.out.println("A is less than or equal to B.");

                --A; // Decrement A.

                // Test if A is less than or equal to B.
                if(A <= B)
                        System.out.println("A is less than or equal to B.");

                // Test if A is less than B.
                if(A < B)
                        System.out.println("A is less than B.");
        }
}

Equality And Relational Operators 1

public class ComparisonDemo {
        public static void main(String[] args) {
                int A = 0;
                int B = 0;

                // Test if A and B are equal.
                if(A == B)
                        System.out.println("A is equal to B.");

                ++B; // Increment B.

                // Test if A and B are not equal.
                if(A != B)
                        System.out.println("A and B are not equal.");
        }
}

Unary Operators Demo 2

public class PrePostDemo {
        /* In Java the unary operators ++ and -- can appear
         * before or after the variable. This will affect
         * how a program behaves.
         */
        public static void main(String[] args) {
                // ++ added before the variable.
                int result = 0;
                ++result;
                System.out.println(result);
                result = 0; // reset result to 0.
                System.out.println(++result);

                // ++ added after the variable.
                result = 0;
                result++;
                System.out.println(result);
                result = 0; // reset result;
                System.out.println(result++);

                /* Why wasn't result incremented by 1? The answer
                 * is, it was. As the next line of code will prove.
                 */

                System.out.println(result);

                /* So what's going on? The Oracle tutorial explains
                 * it like so "The only difference is that the prefix
                 * version (++result) evaluates to the incremented value,
                 * whereas the postfix version (result++) evaluates to
                 * the original value."
                 * 
                 * In practice, in this example, the prefix ++ increments
                 * result before the expression or line of code is completed.
                 * The postfix version increments result after the expression
                 * or line of code is completed. Which is why result is incremented
                 * when printed again with the additional println() call.
                 * 
                 * The -- decrement operator works in the same way.
                 */
        }
}

Tuesday 9 June 2015

Unary Operators Demo

public class UnaryDemo {
        public static void main(String[] args) {
                // Assign a positive or negative value to a number.
                int positive = +1;
                int negative = -1;
                System.out.println("positive = " + positive);
                System.out.println("negative = " + negative);
                positive = -1;
                negative = +1;
                System.out.println("\npositive = " + positive);
                System.out.println("negative = " + negative);

                // Increment and decrement a value.
                int result = 5;
                result++;
                System.out.println("\nif result is set to 5 then result++ = " + result);
                result--;
                System.out.println("if result is set to 6 then result-- = " + result);

                // Change a boolean value with !.
                boolean success = false;
                System.out.println("\nsuccess = " + success);
                System.out.println("success = " + !success);
        }
}

Joining Strings

public class JoinStrings {
        /* The process of joining one string to another is called
         * concatenation. Java does this in a similar way to most other
         * popular languages. And that is to use the + sign in the
         * same way as adding two numbers together.
         */
        public static void main(String[] args) {
                // + sign used for addition.
                int result = 1 + 2;
                System.out.println("Addition: 1 + 2 = " + result);

                // + used to concatenate two strings.
                String thing1 = "Joe ";
                String thing2 = "Blogs";
                String result_string = thing1 + thing2;
                System.out.println("Concatenation: thing1 + thing2 = " + result_string);
        }
}

Monday 8 June 2015

Arithmetic Operators

public class ArithmeticOperators {
        /* Arithmetic operators offered by the Java language are;
         * + Addition.
         * - Subtraction.
         * * Multiplication.
         * / Division.
         * % Remainder.
         */
        public static void main(String[] args) {
                int result = 1 + 2;
                // The result is now 3.
                System.out.println("1 + 2 = " + result);
                int original_result = result;

                result = result - 1;
                // The result is now 2.
                System.out.println(original_result + " - 1 = " + result);
                original_result = result;

                result = result * 2;
                // The result is now 4.
                System.out.println(original_result + " * 2 = " + result);
                original_result = result;

                result = result / 2;
                // The result is now 2.
                System.out.println(original_result + " / 2 = " + result);
                original_result = result;

                result = result + 8;
                // The result is now 10;
                System.out.println(original_result + " + 8 = " + result);
                original_result = result;

                result = result % 7;
                // The result is now 3.
                System.out.println(original_result + " % 7 = " + result);
        }
}

This example was lifted pretty much "as is" from the Oracle Java tutorials.

Sunday 7 June 2015

Manipulating Arrays Demo

public class ManipulatingArraysDemo {

        /* This example uses copyOfRange method in the java.util.Arrays class to
         * copy a range of values from copyFrom to copyTo.
         * 
         * This allows us to cut out a whole line of code. Which doesn't seem like
         * much in this small demo. But it would make quite a difference to a larger
         * project.
         * 
         * copyOfRange requires 3 parameters. The first is the source array.
         * The second is the index starting point in the source array. The third
         * is the last index. However you'll notice the 'a' is not copied.
         * 
         * This is because that last index is exclusive. In other words we copy
         * from index 2 upto but not including index 9.
         */

        public static void main(String[] args) {
                char[] copyFrom = {'d','e','c','a','f','f','e',
                                'i','n','a','t','e','d'};
                char[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9);

                System.out.println(new String(copyFrom) + " to " + new String(copyTo));
        }
}

Copying Arrays

public class CopyingArrays {
        /* This example uses the arraycopy method of the System class
         * to copy part of the char array copyFrom to the char array copyTo.
         */
        public static void main(String[] args) {
                char[] copyFrom = {'d','e','c','a','f','f','e',
                        'i','n','a','t','e','d'};
                char[] copyTo = new char[7];

                System.arraycopy(copyFrom, 2, copyTo, 0, 7);
                System.out.println(new String(copyFrom) + " to " + new String(copyTo));
        }
}

The Bicycle Example

The Bicycle example is covered in a discussion on Oracle's Java "trails". It touches on the concepts of a software object and inheritance. It also touches on the concepts of "contracts", "interfaces" and "APIs". But I don't go that deep in this code example.

I really just needed a break from arrays. :)

class Bicycle {
        int bikenum = 0;
        int cadence = 0;
        int speed = 0;
        int gear = 1;

        void changeCadence(int newvalue) {
                cadence = newvalue;
        }

        void changeGear(int newvalue) {
                gear = newvalue;
        }

        void speedUp(int increment) {
                speed = speed + increment;
        }

        void applyBrakes(int decrement) {
                speed = speed - decrement;
        }

        void printStates() {
                System.out.println("Bike:" + bikenum + " Candence:" +
                                cadence + " Speed:" + speed + " Gear:" + gear + "\n");
        }
}

class MountainBike extends Bicycle {
        /* The "extends" keyword will allow MountainBike to inherit
         * all of the attributes of Bicycle. So MountainBike will also
         * have bikenum, cadence, speed, gear and the five methods that
         * were defined.
         */
        boolean frontShocks = true;
        boolean rearShocks = false;

        /* The method "printStates" needs to be redefined as there are
         * two more fields to print.
         */
        void printStates() {
                System.out.println("Bike:" + bikenum + " Front Shocks: " +
                                frontShocks + " Rear Shocks:" + rearShocks +
                                " Candence:" + cadence + " Speed:" + speed +
                                " Gear:" + gear + "\n");
        }
}

public class BicycleDemo {
        public static void main(String[] args) {
                // Create two different Bicycle objects
                Bicycle bike1 = new Bicycle();
                Bicycle bike2 = new Bicycle();
                bike1.bikenum = 1;
                bike2.bikenum = 2;
                bike1.printStates();
                bike2.printStates();

                // Invoke methods on those objects
                bike1.changeCadence(50);
                bike1.speedUp(10);
                bike1.changeGear(2);
                bike1.printStates();

                bike2.changeCadence(50);
                bike2.speedUp(10);
                bike2.changeGear(2);
                bike2.changeCadence(40);
                bike2.changeGear(3);
                bike2.printStates();

                bike1.applyBrakes(3);
                bike1.printStates();

                // Create MountainBike object.
                MountainBike bike3 = new MountainBike();
                bike3.bikenum = 3;
                bike3.printStates();
        }


}

Multidimensional Arrays

public class multidimensionalArraysDemo {

        public static void main(String[] args) {

                /* In the Java programming language,
                 * a multidimensional array is an array whose components
                 * are themselves arrays.
                 * 
                 * This is like a box which contains several boxes. Each of which
                 * contains several more boxes. Which contain an item or value.
                 */

                String[][] names = {
                                {"Mr. ","Mrs. ","Ms. "},
                                {"Smith","Jones"}
                };

                /* We reference the array in the same way as before.
                 * But this time we have two indeces instead of one.
                 */
                System.out.println(names[0][0] + names[1][0]); // Mr. Smith
                System.out.println(names[0][1] + names[1][0]); // Mrs. Smith
                System.out.println(names[0][2] + names[1][0]); // Ms. Smith
                System.out.println(names[0][0] + names[1][1]); // Mr. Jones
                System.out.println(names[0][1] + names[1][1]); // Mrs. Jones
                System.out.println(names[0][2] + names[1][1]); // Ms. Jones

                /* We can also print the length of the array using the
                 * length property.
                 */
                System.out.println("\nLength of names: " + names.length);
                System.out.println("Length of names index 0: " + names[0].length);
                System.out.println("Length of names index 1: " + names[1].length);
        }
}

Second Array Demo

public class secondArrayDemo {

        public static void main(String[] args) {
                // Integer array from first array demo.
                // Declare an array of integers.
                int[] anIntegerArray;

                // Allocate memory for 5 integers.
                anIntegerArray = new int[5];
               
                // Initialise the array elements.
                anIntegerArray[0] = 100;
                anIntegerArray[1] = 200;
                anIntegerArray[2] = 300;
                anIntegerArray[3] = 400;
                anIntegerArray[4] = 500;
               
                // Print out the contents of the array.
                System.out.println("Integer array defined using the first method.");
                System.out.println("Element at index 0: " + anIntegerArray[0]);
                System.out.println("Element at index 1: " + anIntegerArray[1]);
                System.out.println("Element at index 2: " + anIntegerArray[2]);
                System.out.println("Element at index 3: " + anIntegerArray[3]);
                System.out.println("Element at index 4: " + anIntegerArray[4]);
                System.out.println("\n"); // Adds a blank line to the output.

                /* Alternative method for declaring an array.
                 * The number of items in the array are determined by the
                 * number of items provided between the braces.
                 * 
                 * NOTE: An "end of line" semi-colon has been used after the
                 * closing brace.
                 */
                int[] integerArray2 = {
                                500, 600, 700, 800, 900
                };
                System.out.println("Integer array defined using the second method.");
                System.out.println("Element at index 0: " + integerArray2[0]);
                System.out.println("Element at index 1: " + integerArray2[1]);
                System.out.println("Element at index 2: " + integerArray2[2]);
                System.out.println("Element at index 3: " + integerArray2[3]);
                System.out.println("Element at index 4: " + integerArray2[4]);
        }
}

First Array Demo

public class firstArrayDemo {

        /* An array is like a box of boxes with each box containing
         * an item or value.
         */

        public static void main(String[] args) {
                // Declare an array of integers.
                int[] anIntegerArray;

                // Allocate memory for 5 integers.
                anIntegerArray = new int[5];

                // Initialise the array elements.
                anIntegerArray[0] = 100;
                anIntegerArray[1] = 200;
                anIntegerArray[2] = 300;
                anIntegerArray[3] = 400;
                anIntegerArray[4] = 500;

                // Print out the contents of the array.
                System.out.println("Element at index 0: " + anIntegerArray[0]);
                System.out.println("Element at index 1: " + anIntegerArray[1]);
                System.out.println("Element at index 2: " + anIntegerArray[2]);
                System.out.println("Element at index 3: " + anIntegerArray[3]);
                System.out.println("Element at index 4: " + anIntegerArray[4]);
        }
}

Variables, Fields and Primitive Data Types

class Man {
        int age = 36;
        static String sex = "Male";
        static final int numEyes = 2;
}

public class variablesAndFields {

        /*
         * The Java language has four different kinds of variable.
         * Parameters, local variables, static and non-static fields.
         * Also known as class variables and instance variables
         * respectively.
         * 
         * Variables will also be one of eight primitive data types.
         * Which are byte, short, int, long, float, double, boolean
         * and char.
         * 
         * String is not a primitive data type. It is an object provided
         * by the java.lang.String class.
         */

        public static void main(String[] args) {
                /* Literals
                 * Literals do not need to be defined with the keyword
                 * "new" as they are part of the language and not objects.
                 */
                boolean result = true;
                char character = 'A';
                byte b = 100;
                short s = 1000;
                int i = 100000;
                float pi = 3.14F;

                // We can reference locally declared variables directly.
                System.out.println("Primitive Data Types");
                System.out.println("boolean: " + result);
                System.out.println("char: " + character);
                System.out.println("byte: " + b);
                System.out.println("short: " + s);
                System.out.println("int: " + i);
                System.out.println("float: " + pi);

                /* A variable becomes a field when we try to access it
                 * from "outside" the class or object.
                 */
                Man Bob = new Man();
                Man Joe = new Man();

                System.out.println("\nPrinting the content of a field.");
                System.out.println("Bob.age has a value of " + Bob.age);
                System.out.println("Joe.age has a value of " + Joe.age);

                /* If a field is defined with the "static" keyword
                 * only one instance of that field will exist no matter
                 * however many iterations of the object exist.
                 * 
                 * So if we change object Bob's sex to "female" then
                 * object Joe's sex will also change to "female" because
                 * they are referencing the same instance of the same field.
                 */
                System.out.println("Bob is a " + Bob.sex);
                System.out.println("Joe is a " + Joe.sex);

                Bob.sex = "Female"; // This affect Bob and Joe.
                Joe.age = 50; // This will only affect Joe.

                System.out.println("\nBob is a " + Bob.sex);
                System.out.println("Joe is a " + Joe.sex);
                System.out.println("Bob.age has a value of " + Bob.age);
                System.out.println("Joe.age has a value of " + Joe.age);

                /* If the "final" keyword is added. That variable or field
                 * cannot be changed.
                 * 
                 * Remove the // from the line below and the program will
                 * not run because numEyes was defined in the Man class
                 * with the "final" keyword.
                 */
                //Bob.numEyes = 30;
                System.out.println("\nBob has " + Bob.numEyes + " eyes.");

        }
}

Translate