-------------------------------------- Java Sag is under construction: 2012
Please inform us if you find a non good advertisement : info.enim dot gmail.com

Best Web Hosting

mercredi 9 mai 2012

How do I create static variables in Java?

Class variables or static variable is variable that declared with static modifier. A given class will have only one copy of each of its static variables, regardless of how many times the class has been instantiated.

If the value of a static variable is changed, the new value is available equally in all instances of the class. The final keyword could be added to indicate the value of static variable will never change. If you try to assign a new value to final variable, you will get a compile error.
package org.kodejava.example.fundametal;

public class StaticDemo {
    // static variable
    static int x = 12;

    // static variable with final value that never change
    final static int Y = 20;

    // non-static variable
    int z;

    public static void main(String[] args) {
        StaticDemo sd0 = new StaticDemo();

        System.out.println("x before update = " + StaticDemo.x);
        System.out.println("y= " + StaticDemo.Y);

        sd0.z = StaticDemo.x + StaticDemo.Y;
        System.out.println("z= " + sd0.z);

        StaticDemo.x = 15;
        System.out.println("x after update = " + StaticDemo.x);

        StaticDemo sd1 = new StaticDemo();
        StaticDemo sd2 = new StaticDemo();
        StaticDemo.x = 20;

        System.out.println("StaticDemo.x = " + StaticDemo.x);
        System.out.println("sd0 = " + sd0.getX());
        System.out.println("sd1 = " + sd1.getX());
        System.out.println("sd2 = " + sd2.getX());

        //
        // try to assign value to final variable, it will cause a
        // compile time error
        //
        // StaticDemo.Y = 30;
    }

    public int getX() {
        return StaticDemo.x;
    }
}

Here is the output printed by the program:

x before update = 12
y= 20
z= 32
x after update = 15
StaticDemo.x = 20
sd0 = 20
sd1 = 20
sd2 = 20

How do I catch multiple exceptions?

If a try block can throw several different kind of exceptions and you want to handle each exception differently, you can put several catch blocks to handle it.
package org.kodejava.example.fundametal;

public class MultipleCatchExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 4, 5};
        int[] numbers2 = {1, 2, 3, 4, 5, 6};

        try {
            //
            // This line throws an ArrayIndexOutOfBoundsException
            //
            MultipleCatchExample.printResult(numbers1);

            //
            // This line throws an ArithmeticException
            //
            MultipleCatchExample.printResult(numbers2);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     */
    private static int divide(int x, int y) {
        return x / y;
    }

    /**
     * Print the output result of divide operation by calling the
     * divide() method.
     *
     * @param numbers integer arrays of the divided number
     * @throws ArrayIndexOutOfBoundsException when an exception
     * occurs.
     */
    private static void printResult(int[] numbers) {
        int x, z, y = 1;
        for (int i = 0; i < 6; i++) {
            x = numbers[i];
            if (i == 5) {
                y = 0;
            }
            z = MultipleCatchExample.divide(x, y);
            System.out.println("z = " + z);
        }
    }
}

How do I use the super keyword?

When a class extends from other class, the class or usually called as subclass inherits all the accessible members and methods of the superclass. If the subclass overrides a method provided by its superclass, a way to access the method defined in the superclass is through the super keyword.
package org.kodejava.example.fundametal;

public class Bike {
    public void moveForward() {
        System.out.println("Bike: Move Forward.");
    }
}

In the ThreeWheelsBike's moveForward() method we call the overridden method using the super.moveForward() which will print the message from the Bike class.
package org.kodejava.example.fundametal;

public class ThreeWheelsBike extends Bike {
    @Override
    public void moveForward() {
        super.moveForward();
        System.out.println("Three Wheels Bike: Move Forward.");
    }

    public static void main(String[] args) {
        Bike bike = new ThreeWheelsBike();
        bike.moveForward();
    }
}

How do I use the this keyword in Java?

The program below demonstrate how to use the switch statement. The switch statement can work with thebyteshortint and char primitive data types and the corresponding wrappers of these data type such asByteShortInteger and Character. It also work with work with enumerated types, refer to the following example: How do I use enum in switch statement?.
The switch block or the body can contains one or more case or default labels. The switch statement evaluates its expression and evaluate the appropriate case.
You'll also notice that after each case labels we have a break statement. This break statement causes the program execution to continue outside the switch block. Without using a break the case will fall-through to another case or default label.
package org.kodejava.example.lang;

public class SwitchDemo {
    public static void main(String[] args) {
        System.out.println("The Planets");
        System.out.println("===================================");
        System.out.println("1. Mercury");
        System.out.println("2. Venus");
        System.out.println("3. The Earth");
        System.out.println("4. Mars");
        System.out.println("5. Jupiter");
        System.out.println("6. Saturn");
        System.out.println("7. Uranus");
        System.out.println("8. Neptune");
        System.out.println("");
        System.out.print("Please choose your favorite destination: ");

        int destionation = 0;
        try {
            destionation = Integer.valueOf(System.console().readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        System.out.print("Welcome to ");
        switch (destionation) {
            case 1:
                System.out.println("Mercury"); break;
            case 2:
                System.out.println("Venus"); break;
            case 3:
                System.out.println("The Earth"); break;
            case 4:
                System.out.println("Mars"); break;
            case 5:
                System.out.println("Jupiter"); break;
            case 6:
                System.out.println("Saturn"); break;
            case 7:
                System.out.println("Uranus"); break;
            case 8:
                System.out.println("Neptune"); break;
            default:
                System.out.println("Invalid Destination");
        }
    }
}

When you run the program you'll have to following on the screen:

The Planets
===================================
1. Mercury
2. Venus
3. The Earth
4. Mars
5. Jupiter
6. Saturn
7. Uranus
8. Neptune

Please choose your favorite destination: 3
Welcome to The Earth

How do I define a constant variable?

To define a constant in Java, use final modifier which combined with static modifier. The final modifier indicates that the value of this field cannot change.

If you change the value of the constant, you need to recompile the class to get the current value. Other feature in Java that provide similar functionality is enumeration (a list of named constants). You can simply create an enumeration by using the enum keyword.
package org.kodejava.example.fundametal;

public class ConstantDemo {
    public static void main(String[] args) {
        int sunday = DayConstant.SUNDAY;
        System.out.println("Sunday= " + sunday);

        String dozen = MeasureConstant.DOZEN;
        System.out.println("Dozen: " + dozen);
    }

}

class DayConstant {
    public final static int SUNDAY = 0;
    public final static int MONDAY = 1;
    public final static int TUESDAY = 2;
    public final static int WEDNESDAY = 3;
    public final static int THURSDAY = 4;
    public final static int FRIDAY = 5;
    public final static int SATURDAY = 6;
}

class MeasureConstant {
    final static String UNIT = "unit";
    final static String DOZEN = "dozen";
}

How do I use the return keyword in Java?

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it.

A method can return a value or reference type or does not return a value. If a method does not return a value, the method must be declared void and it doesn't need to contain a return statement.

If a method declare to return a value, then it must use the return statement within the body of method. The data type of the return value must match the method's declared return type.
package org.kodejava.example.fundametal;

public class ReturnDemo {

    public static void main(String[] args) {
        int z = ReturnDemo.calculate(2, 3);
        System.out.println("z = " + z);

        Dog dog = new Dog("Spaniel", "Doggie");
        System.out.println(dog.getDog());
    }

    public static int calculate(int x, int y) {
        //
        // return an int type value
        //
        return x + y;
    }

    public void print(){
        System.out.println("void method");

        //
        // it does not need to contain a return statement, but it
        // may do so
        //
        return;
    }

    public String getString(){
        return "return String type value";

        //
        // try to execute a statement after return a value will
        // cause a compile-time error.
        //
        String error = "error";
    }
}

class Dog {
    private String breed;
    private String name;

    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }

    public Dog getDog() {
        //
        // return Dog type
        //
        return this;
    }

    public String toString(){
        return "breed: " + breed.concat("name: " + name);
    }
}

How do I use the while loop statement?

The code below demonstrate how to use the while loop statement. The while statement will check if its expression evaluates to true and execute the while statement block.

The program below will executes while the countDown value is bigger or equals to zero.
package org.kodejava.example.lang;

public class WhileDemo {
    public static void main(String[] args) {
        //
        // Start the count down from 10
        //
        int countDown = 10;

        //
        // Do the count down process while the value of
        // countDown is bigger or equals to zero.
        //
        while (countDown >= 0) {
            System.out.println(countDown);
            countDown--;

            try {
                //
                // Adds one second delay.
                //
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I get constants name of an enum?

To get the constants name of an enumeration you can use the values() method of the enumeration type. This method return an array that contains a list of enumeration constants.
package org.kodejava.example.fundametal;

enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}

public class EnumValuesTest {
    public static void main(String[] args) {
        //
        // values() method return an array that contains a list of the
        // enumeration constants.
        //
        Month[] months = Month.values();
        System.out.println("Month size: " + months.length);
        
        //
        // We can user for each statement to print each enumeration
        // constant.
        //
        for (Month month : Month.values()) {
            System.out.println("Month: " + month);
        }
    }
}

How do I use the do-while loop statement?

There is also a do-loop in the Java programming language. Instead of evaluating the expression at the beginning like the while loop does the do-while loop evaluates its expression at the end of the loop. Due to this the loop executes at least once during the program execution.
package org.kodejava.example.lang;

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

        //
        // The do-while statement executes at least once because
        // the expression is checked at the end of the loop
        // process.
        //
        do {
            //
            // This block will be executed while i is smaller or
            // equals to 10.
            //
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

The program prints the following result:

0
1
2
3
4
5
6
7
8
9
10

How do I create a class in Java?

A class is a specification or blueprint from which individual objects are created. A class contains fields that represent the object's states and methods that defines the operations that are possible on the objects of the class.

The file name that contains the definition of a class is always the same as the public class name and the extension is .java to identify that the file contains a Java source code.

A class has constructors, a special method that is used to create an instance or object of the class. When no constructor define a default constructor will be used. The constructor method have the same name with the class name without a return value. The constructors can have parameters that will be used to initialize object's states.

Here is a Person.java file that defines the Person class.
package org.kodejava.example.fundametal;

public class Person {
    private String name;
    private String title;
    private String address;

    /**
     * Constructor to create Person object
     */
    public Person() {

    }

    /**
     * Constructor with parameter
     *
     * @param name
     */
    public Person(String name) {
        this.name = name;
    }

    /**
     * Method to get the name of person
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * Method to set the name of person
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Method to get the title of person
     *
     * @return title
     */
    public String getTitle() {
        return title;
    }

    /**
     * Method to set the title of person
     *
     * @param title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * Method to get address of person
     *
     * @return address
     */
    public String getAddress() {
        return address;
    }

    /**
     * Method to set the address of person
     *
     * @param address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Method to get name with title of person
     *
     * @return nameTitle
     */
    public String getNameWithTitle() {
        String nameTitle;
        if (title != null) {
            nameTitle = name + ", " + title;
        } else {
            nameTitle = name;
        }
        return nameTitle;
    }

    /**
     * Method used to print the information of person
     */
    @Override
    public String toString() {
        return "Info [" +
                "name='" + name + '\'' +
                ", title='" + title + '\'' +
                ", address='" + address + '\'' +
                ']';
    }
}

Here is a ClassExample.java file that defines the ClassExample class that use the Person class
package org.kodejava.example.fundametal;

public class ClassExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Andy");
        person.setTitle("MBA");
        person.setAddress("NY City");
        System.out.println(person);

        String nameTitle1 = person.getNameWithTitle();
        System.out.println("Name with title: " + nameTitle1);

        Person person2 = new Person("Sarah");
        String nameTitle2 = person2.getNameWithTitle();
        System.out.println("Name with title 2: " + nameTitle2);
    }
}

How do I use the this keyword in Java?

Every instance method has a variable with the name this that refers to the current object for which the method is being called. You can refer to any member of the current object from within an instance method or a constructor by using this keyword.

Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this keyword.
package org.kodejava.example.fundamental;

public class RemoteControl {
    private String channelName;
    private int channelNum;
    private int minVolume;
    private int maxVolume;

    RemoteControl() {

    }

    RemoteControl(String channelName, int channelNum) {
        // 
        // use the this keyword to call another constructor in the 
        // same class
        //
        this(channelName, channelNum, 0, 0);  
    }

    RemoteControl(String channelName, int channelNum, int minVol, int maxVol) {
        this.channelName = channelName;
        this.channelNum = channelNum;
        this.minVolume = minVol;
        this.maxVolume = maxVol;
    }

    public void changeVolume(int x, int y) {
        this.minVolume = x;
        this.maxVolume = y;
    }

    public static void main(String[] args) {
        RemoteControl remote = new RemoteControl("ATV", 10);
        
        // 
        // when the following line is executed, the this variable in
        // changeVolume() is refer to remote object.
        //
        remote.changeVolume(0, 25);
    }
}

How do I use the final keyword in Java?

The final modifier is used to mark a class final so that it cannot inherited, to prevent a method being overridden, and to prevent changing the value of a variable. Arguments of a method if declared as final is also can not be modified within the method.
package org.kodejava.example.fundametal;

public class FinalExample {
    //
    // breed is declared final. 
    // can't change the value assigned to breed
    //
    public final String breed = "pig";   
    private int count = 0;

    // 
    // sound() method is declared final, so it can't be overridden
    //
    public final void sound() {     
        System.out.println("oink oink");
    }

    // 
    // number parameter is declared final. can't change the value 
    // assigned to number
    //
    public int count(final int number) {
        //
        // assign a value to number variable will cause a 
        // compile-time error
        //
        number = 1;
        
        count = +number;
        return count;
    }

    public static void main(String[] args) {
        FinalExample fe = new FinalExample();
        // 
        // assign a value to breed variable will cause a 
        // compile-time error
        //
        fe.breed = "dog";
        
        int number = fe.count(20);
    }
}

final class SubFinalExample extends FinalExample {

    //
    // try to override sound() method of superclass will cause a 
    // compile-time error
    //
    public void sound() {
         System.out.println("oink");
    }
}

//
// try to inherit a class that declared final will cause a 
// compile-time error
//
class OtherFinalExample extends SubFinalExample {
}

How do I use the boolean negation (!) operator in Java?

The ! operator is a logical compliment operator. The operator inverts the value of a boolean expression
package org.kodejava.example.fundametal;

public class NegationOperator {
    public static void main(String[] args) {
        //
        // negate the result of boolean expressions
        //
        boolean negate = !(2 < 3);
        boolean value = !false;

        System.out.println("result: " + negate);
        System.out.println("value : " + value);
    }
}

Here is the result of the program:

result: false
value : true

dimanche 6 mai 2012

How do I use the for loop statement?

The for loop can be use to iterate over a range of values. For instance if you want to iterate from zero to 10 or if you want to iterate through all the items of an array. Below you'll see two forms of a for loop. The first one is the general form of a for loop and the second one is an enhanced for loop that also known as the for..each loop.

The general form of for loop consists of three parts:
-----------------------------------------------------
for (initialization; termination; increment) {
....
}
-----------------------------------------------------
The initialization: it initializes the loop, it executed once at the beginning of the loop.
The termination: the loop executes as long as the termination evaluates to true.
The increment: it executed at the end of every loop, the expression can be either an increment or decrement.

package org.kodejava.example.lang;

public class ForDemo {
    public static void main(String[] args) {
        //
        // Do a loop from 0 to 10.
        //
        for (int i = 0; i <= 10; i++) {
            System.out.println("i = " + i);
        }

        //
        // Loop through all the array items.
        //
        int[] numbers = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int number : numbers) {
            System.out.println("number = " + number);
        }
    }
}

The result of the program is:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
number = 0
number = 1
number = 2
number = 3
number = 4
number = 5
number = 6
number = 7
number = 8
number = 9
number = 10

How do I define a field in enum type?

As we know that Java enumeration type is powerful compared to enum implementation in other programming language. Basically enum is class typed so it can have constructors, methods and fields.

In the example below you'll see how a field is defined in an enumeration type. Because each constant value for the Fruit enum is a type of Fruit itself it will have its own price field. The price field holds a unique value for each constant such as APPLE, ORANGE, etc.

In the result you'll see that the constructor will be called for each constant value and initialize it with the value passed to the constructor.
package org.kodejava.example.fundametal;

enum Fruit {
    APPLE(1.5f), ORANGE(2), MANGGO(3.5f), GRAPE(5);

    private float price;

    Fruit(float price) {
        System.out.println("Name: " + this.name() + " initialized.");
        this.price = price;
    }

    public float getPrice() {
        return this.price;
    }
}

public class EnumFieldDemo {
    public static void main(String[] args) {
        //
        // Get the name and price of all enum constant value.
        //
        for (Fruit f : Fruit.values()) {
            System.out.println("Fruit = " + f.name() + "; Price = " + f.getPrice());
        }
    }
}

Our demo result is below:

Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price = 1.5
Fruit = ORANGE; Price = 2.0
Fruit = MANGGO; Price = 3.5
Fruit = GRAPE; Price = 5.0

How do I use the if-then-else statement?

The if-then-else control flow statement adds a secondary path to the if statement when the expression evaluates to false. When it evaluates to false the else block will be executed.

Below is the program that takes input of user test score and evaluates the score to get the corresponding grade.
package org.kodejava.example.lang;

import java.io.Console;

public class IfThenElseDemo {
    public static void main(String[] args) {
        //
        // Get an instance of system console for taking user
        // input.
        //
        Console c = System.console();

        int score = 0;
        String grade;

        System.out.print("Please enter your score: ");

        try {
            //
            // Take user score input and convert the input
            // value into number.
            //
            score = Integer.valueOf(c.readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 50) {
            grade = "D";
        } else {
            grade = "F";
        }

        System.out.println("Grade = " + grade);
    }
}

-----------------------------------------------
When the program executed you'll need to input the test score and the program will give you the grade.

Please enter your score: 75
Grade = C

How do I count the occurrences of a number in an array?

package org.kodejava.example.lang;

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class NumberOccurrenceInArray {
    public static void main(String[] args) {
        int[] numbers = new int[] {1, 8, 3, 4, 3, 2, 5, 7, 3, 1, 4, 5, 6, 4, 3};

        Map map = new HashMap();
        for (int i = 0; i < numbers.length; i++) {
            int key = numbers[i];
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }

        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            int key = (Integer) iterator.next();
            int occurrence = map.get(key);

            System.out.println(key + " occur " + occurrence + " time(s).");
        }
    }
}

The result are:

1 occur 2 time(s).
2 occur 1 time(s).
3 occur 4 time(s).
4 occur 3 time(s).
5 occur 2 time(s).
6 occur 1 time(s).
7 occur 1 time(s).
8 occur 1 time(s).

What is reference variable in Java?

The only way you can access an object is through a reference variable. A reference variable is declared to be of a specific type and that type can never be changed. Reference variables can be declared as static variables, instance variables, method parameters, or local variables.

A reference variable that is declared final can't ever be reassigned to refer to a different object. The data within the object can be modified, but the reference variable cannot be changed.
package org.kodejava.example.fundametal;

public class ReferenceDemo {
    public static void main(String[] args) {
        //
        // declaration of reference variable
        //
        Reference ref1, ref2;
        
        // 
        // ref3 is declared final, it will cause it can reassign 
        // or refer to different object
        //
        final Reference ref3; 

        // 
        // assign ref1 with object Reference
        //
        ref1 = new Reference("This is the first reference variable", 1);
        
        //
        // access method getNumber() of object Reference through 
        // variable ref1
        //
        int number = ref1.getNumber(); 
        System.out.println("number= " + number);

        // 
        // assign ref2 with object Reference
        //
        ref2 = new Reference("This is the second reference variable", 2);
        
        //
        // passing ref2 as method parameter of printText() method
        //
        ReferenceDemo.printText(ref2); 

        //
        // assign ref3 with object Reference
        //
        ref3 = new Reference("This is the third reference variable", 3);
        
        //
        // try to reassign ref3 will cause a compile-time error
        //
        //ref3 = new Reference("Try to reassign",3);

    }

    public static void printText(Reference reference) {
        String text = reference.getText();
        System.out.println(text);
    }
}

class Reference {
    private int number;
    private String text;

    Reference(String text, int number) {
        this.text = text;
        this.number = number;
    }

    public String getText() {
        return text;
    }

    public int getNumber() {
        return number;
    }
}

How do I use the ternary operator?

The ternary operator or conditional operator can be use as a short version of the if-then-else statement. When you have a simple if-then-else statement in your code that return a value you might use the ternary operator, it can make your code easier to read.

The ternary operator is written using the symbol of ?: and it has the following syntax:
-----------------------------------------
result = testCondition ? value1 : value2;
----------------------------------------
When the test condition evaluates to true the expression value1 will be returned else the expression value2 will be returned. The value1 or value2 is not only for a simple field or variable, it can be a call to a method for example. But it is advisable to use the ternary operator for a simple thing, because if you over do it, it will make your code harder to read.

Let's see the following code:
package org.kodejava.example.lang;

public class TernaryOperatorDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        //
        // Get the maximum value
        //
        int min = a < b ? a : b;

        //
        // The use of ternary operator above is an alternative
        // of the following if-then-else statement.
        //
        int minValue;
        if (a < b) {
            minValue = a;
        } else {
            minValue = b;
        }

        //
        // Get the minimum value.
        //
        int max = a > b ? a : b;

        //
        // Get the absolute value.
        //
        int abs = a < 0 ? -a : a;

        System.out.println("min      = " + min);
        System.out.println("minValue = " + minValue);
        System.out.println("max      = " + max);
        System.out.println("abs      = " + abs);
    }
}

How do I create custom exception class?

You can define your own exception class for your application specific purposes. The exception class is created by extending the java.lang.Exception class for checked exception or java.lang.RuntimeException for unchecked exception. By creating your own Exception classes, you could identify the problem more precisely.
package org.kodejava.example.fundametal;

public class CustomExceptionExample {
    public static void main(String[] args) {
        int x = 1, y = 0;

        try {
            int z = CustomExceptionExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (DivideByZeroException e) {
            e.printStackTrace();
        }

    }

    public static int divide(int x, int y)
            throws DivideByZeroException {
        try {
            return (x / y);
        } catch (ArithmeticException e) {
            String m = x + " / " + y + ", trying to divide by zero";
            throw new DivideByZeroException(m, e);
        }
    }
}

class DivideByZeroException extends Exception {
    DivideByZeroException() {
    }

    DivideByZeroException(String message) {
        super(message);
    }

    DivideByZeroException(String message, Throwable cause) {
        super(message, cause);
    }
}

How do I do bitwise OR operation?

package org.kodejava.example.lang;

public class ORDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 4;

        //
        // Operator "|" is used for doing bitwise OR operation
        //
        int result = numberA | numberB;

        System.out.println(numberA + " | " + numberB + " = " + result);

        //
        // Print the result in binary format
        //
        System.out.println(Integer.toBinaryString(numberA) +
                " | " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}

How do I get name of enum constant?

This example demonstrate how to user enum's name() method to get enum constant name exactly as declared in the enum declaration.
package org.kodejava.example.fundametal;

enum ProcessStatus {
    IDLE, RUNNING, FAILED, DONE;

    @Override
    public String toString() {
        return "Process Status: " + this.name();
    }
}

public class EnumNameDemo {
    public static void main(String[] args) {
        for (ProcessStatus ps : ProcessStatus.values()) {
            //
            // Gets the name of this enum constant, exactly as
            // declared in its enum declaration.
            //
            System.out.println(ps.name());
            
            //
            // Here we call to our implementation of the toString
            // method to get a more friendly message of the
            // enum constant name.
            //
            System.out.println(ps.toString());
        }
    }
}

Our program result:

IDLE
Process Status: IDLE
RUNNING
Process Status: RUNNING
FAILED
Process Status: FAILED
DONE
Process Status: DONE

How do I use static import feature?

In order to use a static member of a class in Java we have to qualify the reference with the class name where they came from. For instance to access the PI and abs() from the Math class we should write:
double circle = Math.PI * 10;
int absolute = Math.abs(-100);

For sometime you might want to call the members without the class name. This is allowed in Java 5.0 by using a feature called static import. It's an import statement that allows you to statically import static class member. A static import declaration enables you to refer to imported static members as if they were declared in the class that uses them, the class name and a dot (.) are not required to use an imported static member.
You can write something like the following to static import.
import static java.lang.Math.PI;
import static java.lang.Math.*;

For a clear code it is better to import each member separately and not using the "*" to import every static member in your code.
Let's a a simple static import below:
package org.kodejava.example.fundametal;

import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.System.out;
import java.util.Date;

public class StaticImport {
    public static void main(String[] args) {
        //
        // Using static field PI and static method abs() from the
        // java.lang.Math class.
        //
        double circle = PI * 10;
        int absolute = abs(-100);

        //
        // Using static field of the java.lang.System class to
        // print out the current date.
        //
        out.println("Today: " + new Date());
    }
}

How do I get the remainder of a division?

The remainder or modulus operator (%) let you get the remainder of a division of a two numbers. This operator can be used to obtain a reminder of an integer or floating point types.
package org.kodejava.example.lang;

public class RemainderOperatorDemo {
    public static void main(String[] args) {
        int a = 10;
        double b = 49;

        //
        // The reminder operator (%) gives your the remainder of
        // an integer or floating point division operation.
        //
        System.out.println("The result of " + a + " % 5 = " + (a % 5));
        System.out.println("The result of " + b + " % 9.5 = " + (b % 9.5));
    }
}

Here is the result of the program:

The result of 10 % 5 = 0
The result of 49.0 % 9.5 = 1.5

How do I get ordinal value of enum constant?

This example demonstrate the use of enum ordinal() method to get the ordinal value of an enum constant.
package org.kodejava.example.fundametal;

enum Color {
    RED, GREEN, BLUE
}

public class EnumOrdinal {
    public static void main(String[] args) {
        //
        // Gets the ordinal of this enumeration constant (its 
        // position in its enum declaration, where the initial 
        // constant is assigned an ordinal of zero)
        //
        System.out.println("Color.RED  : " + Color.RED.ordinal());
        System.out.println("Color.GREEN: " + Color.GREEN.ordinal());
        System.out.println("Color.BLUE : " + Color.BLUE.ordinal());
    }
}


The program print the following result:

Color.RED : 0
Color.GREEN: 1
Color.BLUE : 2

How do I get enum constant value corresponds to a string?

The valueOf() method of an enum type allows you to get an enum constant that the value corresponds to the specified string. When we pass a string that not available in the enum an exception will be thrown.
package org.kodejava.example.fundametal;

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumValueOfTest {
    public static void main(String[] args) {
        //
        // Using valueOf() method we can get an enum constant whose
        // value corresponds to the string passed as the parameter.
        //
        Day day = Day.valueOf("SATURDAY");
        System.out.println("Day = " + day);
        day = Day.valueOf("WEDNESDAY");
        System.out.println("Day = " + day);

        try {
            //
            // The following line will produce an exception because the
            // enum type does not contains a constant named JANUARY.
            //
            day = Day.valueOf("JANUARY");
            System.out.println("Day = " + day);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}

How do I do bitwise AND operation?

package org.kodejava.example.lang;

public class ANDDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 16;

        //
        // Operator "&"  is used for doing bitwise AND operation
        //
        int result = numberA & numberB;

        System.out.println(numberA + " & " + numberB + " = " + result);

        //
        // Print the result in binary format
        //
        System.out.println(Integer.toBinaryString(numberA) +
                " & " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}

How do I use enum in switch statement?

This example show you how to use enumeration or enum type in a switch statement
package org.kodejava.example.fundamental;

enum RainbowColor {
    RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET
}

public class EnumSwitch {
    public static void main(String[] args) {
        RainbowColor color = RainbowColor.INDIGO;

        EnumSwitch es = new EnumSwitch();
        String colorCode = es.getColorCode(color);
        System.out.println("ColorCode = #" + colorCode);
    }

    public String getColorCode(RainbowColor color) {
        String colorCode = "";

        //
        // We use the switch-case statement to get the hex color code of our
        // enum type rainbow colors. We can pass the enum type as expression
        // in the swith. In the case statement we only use the enum named
        // constant excluding its type name.
        //
        switch (color) {
            //
            // We use RED instead of RainbowColor.RED
            //
            case RED:
                colorCode = "FF0000";
                break;
            case ORANGE:
                colorCode = "FFA500";
                break;
            case YELLOW:
                colorCode = "FFFF00";
                break;
            case GREEN:
                colorCode = "008000";
                break;
            case BLUE:
                colorCode = "0000FF";
                break;
            case INDIGO:
                colorCode = "4B0082";
                break;
            case VIOLET:
                colorCode = "EE82EE";
                break;
            default:
                break;
        }
        return colorCode;
    }
}

How do I define constructor in enum type?

In the following example you'll see how to add a constructor to an enum type value. Because an enum is just another class type it can have constructors, fields and methods just like any other classes. Below we define a constructor that accept a string value of color code. Because our enum now have a new constructor declared we have to define the constant named value as RED("FF0000"), ORANGE("FFA500"), etc.
package org.kodejava.example.fundamental;

//
// In Java enumeration expanded beyond just as a named constants. Because enum 
// is a class type we can add methods, fields and constructors to the enum type
// as you can see in the example below.
//
enum Rainbow {
    RED("FF0000"),
    ORANGE("FFA500"),
    YELLOW("FFFF00"),
    GREEN("008000"),
    BLUE("0000FF"),
    INDIGO("4B0082"),
    VIOLET("EE82EE");

    private String colorCode;

    //
    // The constructor of Rainbow enum.
    //
    Rainbow(String colorCode) {
        this.colorCode = colorCode;
    }

    /**
     * Get the hex color code.
     * @return
     */
    public String getColorCode() {
        return colorCode;
    }
}

public class EnumConstructor {
    public static void main(String[] args) {
        
        //
        // To get all values of the Rainbow enum we can call the Rainbow.values() 
        // method which return an array of Rainbow enum values.
        //        
        for (Rainbow color : Rainbow.values()) {
            System.out.println("Color = " + color.getColorCode());
        }
    }
}

How do I create type specific collections?

package org.kodejava.example.intro;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class TypeSpecificCollection {
    public static void main(String[] args) {
        //
        // Using a Generic can enable us to create a type specific collection
        // object. In the example below we create a Map whose key is an Integer
        // a have the value of a String.
        //
        Map grades = new HashMap();

        grades.put(1, "A");
        grades.put(2, "B");
        grades.put(3, "C");
        grades.put(4, "D");
        grades.put(5, "E");

        //
        // A value obtained from type specific collection doesn't not need to
        // be casted, it knows the type returned.
        //
        String value = grades.get(1);

        //
        // Creating a List that will contains a String only values.
        //
        List dayNames = new ArrayList();
        dayNames.add("Sunday");
        dayNames.add("Monday");
        dayNames.add("Tuesday");
        dayNames.add("Wednesday");

        //
        // We also don't need to cast the retrieved value because it knows the
        // returned type object.
        //
        String firstDay = dayNames.get(0);
    }
}

What is SuppressWarnings annotation?

The @SuppressWarnings annotation tells the compiler to suppress the warning messages it normally show during compilation time. It has some level of suppression to be added to the code, these level including: all, deprecation, fallthrough, finally, path, serial and unchecked.
package org.kodejava.example.annotation;

import java.util.Date;

public class SuppressWarningsExample {
    @SuppressWarnings(value={"deprecation"})
    public static void main(String[] args) {
        Date date = new Date(2008, 9, 30);

        System.out.println("date = " + date);
    }
}


In the example above if we don't use @SuppressWarnings annotation the compiler will report that the constructor of the Date class called above has been deprecated.

How do I compare string regardless their case?

Here is an example of comparing two string for equality without considering their case sensitivity.
package org.kodejava.example.lang;

public class EqualsIgnoreCase {
    public static void main(String[] args) {
        String uppercase = "ABCDEFGHI";
        String mixed = "aBCdEFghI";

        //
        // To compare two string equality regarding it case use the
        // String.equalsIgnoreCase method.
        //

        if (uppercase.equalsIgnoreCase(mixed)) {
            System.out.println("Uppercase and Mixed equals.");
        }
    }
}

How do I clone an object?

To enable our object to be cloned we need to override Object class clone method. We can also add a java.lang.Cloneable interface to our class, this interface is an empty interface. When we call the clone() method we need the add a try-catch block to catch the CloneNotSupportedException. This exception will be thrown if we tried to clone an object that doesn't suppose to be cloned.

Calling the clone() method does a stateful, shallow copy down inside the Java Virtual Machine (JVM). It creates a new object and copies all the fields from the old object into the newly created object.
package org.kodejava.example.lang;

public class CloneDemo implements Cloneable {
    private int number;
    private transient int data;

    /**
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) {
        CloneDemo clone = new CloneDemo();
        clone.number = 5;
        clone.data = 1000;

        try {
            //
            // Create a clone of CloneDemo object. When we change the value of
            // number and data field in the cloned object it won't affect the
            // original object.
            //
            CloneDemo objectClone = (CloneDemo) clone.clone();
            objectClone.number = 10;
            objectClone.data = 5000;

            System.out.println("cloned object = " + objectClone);
            System.out.println("origin object = " + clone);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }

    public String toString() {
        return "[number = " + number + "; data = " + data + "]";
    }
}

How do I mark method as deprecated?

To mark a method as deprecated we can use the Javadoc @deprecated tag. This is what we did since the beginning of Java. But when a new metadata support introduced to the Java language we can also use annotation. The annotation for marking method as deprecated is @Depreated.

The difference between these two that the @deprecated is place in the Javadoc comment block while the @Deprecated is placed as a source code element.
package org.kodejava.example.annotation;

import java.util.Date;
import java.util.Calendar;

public class DeprecatedExample {
    public static void main(String[] args) {
        DeprecatedExample de = new DeprecatedExample();
        de.getDate();
        de.getMonthFromDate();
    }

    /**
     * Get current system date.
     *
     * @return current system date.
     * @deprecated This method will removed in the near future.
     */
    @Deprecated
    public Date getDate() {
        return new Date();
    }

    public int getMonthFromDate() {
        return Calendar.getInstance().get(Calendar.MONTH);
    }
}

How do I create an inner class?

An inner class is a class defined inside another class. Inner classes can, in fact, be constructed in several contexts. An inner class defined as a member of a class can be instantiated anywhere in that class. An inner class defined inside a method can only be referred to later in the same method. Inner classes can also be named or anonymous.
package org.kodejava.example.lang;

public class InnerClassDemo {
    private Bean bean;

    /**
     * Inner class, the compiled class will be named InnerClassDemo$Bean.class
     */
    class Bean {
        public int width;
        public int height;

        @Override
        public String toString() {
            return width + " x " + height;
        }
    }

    public InnerClassDemo() {
        Bean bean = new Bean();
        bean.width = 100;
        bean.height = 200;

        this.bean = bean;
    }

    public Bean getBean() {
        return this.bean;
    }

    public static void main(String[] args) {
        InnerClassDemo inner = new InnerClassDemo();
        System.out.println("inner.getBean() = " + inner.getBean());
    }
}

How do I do bitwise exclusive OR operation?

package org.kodejava.example.lang;

public class XORDemo {
    public static void main(String[] args) {
        int numberA = 16;
        int numberB = 32;

        //
        // Operator ^ is used for doing bitwise exclusive OR operation
        //
        int result = numberA ^ numberB;

        System.out.println(numberA + " ^ " + numberB + " = " + result);

        //
        // Print the result in binary format
        //
        System.out.println(Integer.toBinaryString(numberA) +
                " ^ " + Integer.toBinaryString(numberB) +
                " = " + Integer.toBinaryString(result));
    }
}
The program prints the following output:
16 ^ 32 = 48 10000 ^ 100000 = 110000

How do I use Override annotation?

We use the @Override annotation as part of method declaration. The @Override annotation is used when we want to override methods and want to make sure have overriden the correct methods.

As the annotation name we know that there should be the same method signature in the parent class to override. That means using this annotation let us know earlier when we are mistakenly override method that doesn't exist in the base class.
package org.kodejava.example.annotation;

public class OverrideExample {
    private String field;
    private String attribute;

    @Override
    public int hashCode() {
        return field.hashCode() + attribute.hashCode();
    }

    @Override
    public String toString() {
        return field + " " + attribute;
    }
}

How do I get the command line arguments passed to the program?,

When creating a Java application we might want to pass a couple of parameters to our program. To get the parameters passed from the command line we can read it from the main(String[] args) method arguments.
As you know to make a class executable you need to create a method as follow:
---------------------------------------------------------
public static void main(String[] args) {}
------------------------------------------ 
This method take an array of String as the parameter. You can guess that this array is the parameters that we pass to the program in the command line.
package org.kodejava.example.fundametal;

public class ArgumentParsingExample {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println("Argument " + (i + 1) + " = " +
                    args[i]);
        }

        // 
        // If you want to check if the number of supplied parameters
        // meet the program requirement you can check the size of 
        // the arguments array.
        //
        if (args.length < 3) {
            System.out.println(
                    "You must call the program as follow:");
            System.out.println(
                    "java ArgumentParsingExample arg1 arg2 arg3");

            //
            // Exit from the program with an error status, for 
            // instance we return -1 to indicate that this program 
            // exit abnormally
            //
            System.exit(-1);
        }

        System.out.println("Hello, Welcome!");
    }
}

Java Programming Keywords Summary

Here are the summary of the available keywords in the Java programming language. Keywords are a reserved word that already taken and internally used by Java, so we cannot create variables and name it using this keyword.
Keyword Meaning
abstract an abstract class or method
assert used to locate internal program errors
boolean the Boolean type
break breaks out of a switch or loop
byte the 8-bit integer type
case a case of a switch
catch the clause of a try block catching an exception
char the Unicode character type
class defines a class type
const not used
continue continues at the end of a loop
default the default clause of a switch
do the top of a do/while loop
double the double-precision floating-number type
else the else clause of an if statement
extends defines the parent class of a class
final a constant, or a class or method that cannot be overridden
finally the part of a try block that is always executed
float the single-precision floating-point type
for a loop type
goto not used
if a conditional statement
implements defines the interface(s) that a class implements
import imports a package
instanceof tests if an object is an instance of a class
int the 32-bit integer type
interface an abstract type with methods that a class can implement
long the 64-bit long integer type
native a method implemented by the host system
new allocates a new object or array
null a null reference
package a package of classes
private a feature that is accessible only by methods of this class
protected a feature that is accessible only by methods of this class, its children, and other classes in the same package
public a feature that is accessible by methods of all classes
return returns from a method
short the 16-bit integer type
static a feature that is unique to its class, not to objects of its class
strictfp Use strict rules for floating-point computations
super the superclass object or constructor
switch a selection statement
synchronized a method or code block that is atomic to a thread
this the implicit argument of a method, or a constructor of this class
throw throws an exception
throws the exceptions that a method can throw
transient marks data that should not be persistent
try a block of code that traps exceptions
void denotes a method that returns no value
volatile ensures that a field is coherently accessed by multiple threads
while a loop


Hello World example in Java

Hello World is a classic sample to start when we learn a new programming language. Below is the Java version of Hello World program, it simple enough to start.

package org.kodejava.example.intro;

public class HelloWorld {
    public static void main(String[] args) {
        //
        // Say hello to the world
        //
        System.out.println("Hello World");
    }
}

The code contains one class called HelloWorld, a main(String[] args) method which is the execution entry point of every Java application and a single line of code that write a Hello World string to the console.
The HelloWorld class must be saved in a file named HelloWorld.java, the class file name is case sensitive. In the example we also define a package name for the class. In this case the HelloWorld.java must be placed in a org\kodejava\example\intro directory.
To run the application we need to compile it first. I assume that you have your Java in your path. To compile it type
-------------------------------------------------------------------------
javac -cp . org\kodejava\example\intro\HelloWorld.java
-------------------------------------------------------- 
The compilation process will result a file called HelloWorld.class, this is the binary version of our program. As you can see that the file ends with .class extension because Java is everyting about class.
To run it type the command bellow, class name is written without it extension.
------------------------------------------------------------------
java -cp . org.kodejava.example.intro.HelloWorld
------------------------------------------------------------------

What's needed to be prepared for learning Java programming?

When you decided to start to learn Java Programming you can start by downloading the Java Development Kit (JDK) from Java Official website. They are three different type of JDK, the JSE (Java Standard Edition), JEE (Java Enterprise Edition), JME (Java Mobile Edition). From the website you can also download the Java API documentations which will sure be your first companion when learning the language. It is better also to download the Java Tutorial Series that was written by the Java expert.
From the tutorial you can learn from the basic of Java programming, the introduction of the fundamental object oriented programming (OOP) which is Java all about. Next you can also find trails in each subject of the API (application programming interface) that is provided by Java, such as the core package, how to communicate with database, Java GUI programming, Image manipulation, RMI, Java Beans Framework, etc.
When you want to write a code you might wonder what editor or IDE that you'll need to use to start learning. A good text editor that support a coloring will be a good candidate, colorful screen is better that just black and white isn't it?
There are a lot of good text editor available today such as the VIM, NotePad++, TextPad, Editplus, UltraEdit. If you already have your prefered editor you can use it of course.
If you'll ready for the big stuff, a bigger homework of project you might considering to use an IDE (Integrated Development Environment) as you'll be working with lots of Java classes and other configuration files and build script for examples. There are many great IDE on the Java world from the free to the commercial product.
What IDE to use is really a developer decision, use whatever tools that can help you to improve your learning and coding activity. You can find IDE such as NetBeans, Eclipse, JCreator, IDEA, JDeveloper, etc.
Beside learning from the Java tutorials there are also many forum on the internet where you can discuss your doubts or your problems. Forums like JavaRanch, Java Forum are great forums with Java gurus that can help you to clarify your doubts and help you to solve your problem. But remember one thing when you ask for help, be polite, elaborate your problem clearly.
A good Java books on your desktop is also a good resource to study Java, from a good books you can learn the bolts and nuts of the Java programming languages. When you have all your arsenal you can get the best out of you in learning Java. Have fun!

Best Web Hosting