Introduction to Java

Beginner java tutorial site is rehosted with updated content and useful information under the domain name javabeginner.com

    

Basic Language Elements  

(Identifiers, keywords, literals, white spaces and comments)  

 

Keywords

 

    There are certain words with a specific meaning in java which tell  (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case. 

Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase.

	abstract    default    if            private      this
	boolean     do         implements    protected    throw
	break       double     import        public       throws
	byte        else       instanceof    return       transient
	case        extends    int           short        try
	catch       final      interface     static       void
	char        finally    long          strictfp     volatile
	class       float      native        super        while
	const       for        new           switch
	continue    goto       package       synchronized
 

Keywords are marked in yellow as shown in the sample code below 

/**    This class is a Hello World Program used to introduce 
the Java Language*/
public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");	//Prints output to console
	}
}
 
For more information on different Keywords - Java Keywords
 
 
Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to 
the C programming language. const and goto are Java keywords. The word finalize is the name of a method 
of the Object class and hence not a keyword. enum and label are not keywords.
 

Comments

 

    Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program. 

Java supports three comment styles. 

Block style comments begin with /* and terminate with */ that spans multiple lines.

Line style comments begin with // and terminate at the end of the line. (Shown in the above program)

Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program)

name of this compiled file is comprised of the name of the class with .class as an extension.

 

Variable, Identifiers and Data Types

 

   Variables are used for data that change during program execution. All variables have a name, a type, and a scope. The programmer assigns the names to variables, known as identifiers. An Identifier must be unique within a scope of the Java program. Variables have a data type, that  indicates the kind of value they can store. Variables declared inside of a block or method are called local variables; They are not automatically initialized. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned.

public class localVariableEx {
  public static int a;                       
  public static void main(String[] args) {  
    int b;                                  
    System.out.println("a : "+a);             
    System.out.println("b : "+b); 	//Compilation error            
}}

     

    Note in the above example, a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.

 

    The data type indicates the attributes of the variable, such as the range of values that can be stored and the operators that can be used to manipulate the variable. Java has four main primitive data types built into the language. You can also create your own composite data types.

    Java has four main primitive data types built into the language. We can also create our own data types. 

The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.

Data Type Default Value (for fields) Range
byte 0 -127 to +128
short 0 -32768 to +32767
int 0  
long 0L  
float 0.0f  
double 0.0d  
char '\u0000' 0 to 65535
String (object)   null  
boolean false  

    When we declare a variable we assign it an identifier and a data type.

For Example

String message = "hello world"

In the above statement, String is the data type for the identifier message. If you don't specify a value when the variable is declared, it will be assigned the default value for its data type.

Identifier Naming Rules

Classes

 

      A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.

 

Objects

 

    An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation.

An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables

 

Interface

 

    An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

 

Instance Members

 

      Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot '.' notation with a object reference is used to access Instance Members.

 

Static Members

 

      Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references.

Below is a program showing the various parts of the Java Program that were discussed above. 

/** Comment 
 * Displays "Hello World!" to the standard output. 
 */
public class HelloWorld {
      String output = "";
      static HelloWorld helloObj;  //Line 1 

      public HelloWorld(){
            output = "Hello World";
      } 

      public String printMessage(){
            return output;
      } 

      public static void main (String args[]) {
            helloObj = new HelloWorld();  //Line 2
            System.out.println(helloObj.printMessage());  
  }
 
}

     

Class Name: HelloWorld
Object Reference: helloObj (in Line 1)
Object Created: helloObj (In Line 2)
Member Function: printMessage
Field: output (String)
Static Member: helloObj
Instance Member : output (String)

 

Arrays

   

    An array creation expression must either have a dimension expression or an initializer. If both are present, then a compile-time error is generated. Also if both are absent, then again a compile-time error is generated. If only the dimension expression is present, then an array with the specified dimension is created with all elements set to the default values. If only the initializer is present, then an array will be created that has the required dimensions to accommodate the values specified in the initializer.

Below is a program showing the default initialization of Array's

public class ArrayExample {
  public static void main (String[] args) {
    byte[] a = new byte[1]; 
    long[] b = new long[1];
    float[] c = new float[1];
    Object[] d = new Object[1];
//    int[] e1 = new int[];              // Compile Time Error
//    int[] f5 = new int[5]{1,2,3,4,5};  // Compile Time Error
    System.out.print(a[0]+", "+b[0]+", "+c[0]+", "+d[0]);
}}

     

Output

0, 0, 0.0, null

    Each array contains the default value for its type. The default value of a primitive byte or a primitive long is printed as 0. The default value of a float primitive is printed as 0.0. The default value of an Object is null.

Below is a program showing the working of Java Arrays

 
import java.util.Arrays;

public class ArrayExample {

//	Array Declaration Examples
    public static void arrayDeclarationExample() {

        System.out.println("Array Declaration Example");
        System.out.println();

//	We can first declare the reference and then create the array
        int[] array1;			//or int Array1[];
        array1 = new int[10];

//    Or we can do delaration and creating memory for the Array in one step
        int[] array2 = new int[24];

//  We can create an array declare, initialize in one step as shown with 7 Strings
        String[] array3 = {"beginner", "-", "java", "-", "tutorial",".", "com"};

//        We can create an array of objects as shown

        Double[] array4 = {new Double(100),new Double(200), new Double(300),
								new Double(400)};

        String[] array5 = new String[5];

        array5[0] = new String("beginner");
        array5[1] = new String("java");
        array5[2] = new String("tutorial");
        array5[3] = new String(".");
        array5[4] = new String("com");
        
//Printing array elements 
        System.out.println("Array3 Elements : ");
        for (int i = 0; i < array3.length; i++) {
            System.out.print(array3[i]+" , ");
        }
        System.out.println();
        System.out.println("Array4 Elements with Default Values :");
        for (int i = 0; i < array4.length; i++) {
            System.out.print(array4[i]+" , ");
        }
        System.out.println();
        
        System.out.println("Array5 Elements : 5");
        for (int i = 0; i < array5.length; i++) {
            System.out.print(array5[i]+" , ");
        }
        System.out.println();
        System.out.println("-----------------------------------------------");

    }

    /* Cloning an array will create a new array of the same size and type 
  and copying all the old elements into the new array. In the case of primitive elements,
  the new array has copies of the old elements, so changes to the elements of one are 
  not reflected in the copy. 
      
  Java arrays do not override the Object.equals() method, which returns true only if the 
  argument is the same object. The java.util.Arrays utility class provides functions for
  element-by-element equality testing and hash value. 
     */
    public static void copyCloneArrayExample() {

        System.out.println();
        System.out.println("Copying and Cloning of Arrays");
        String[] array1 = {"beginner", "-", "java", "-", "tutorial",".", "com"};

        String[] copiedArray1 = new String[array1.length];
        System.arraycopy(array1, 0, copiedArray1, 0, array1.length);
        
        String[] clonedArray1 = (String[])array1.clone();

        System.out.println();
        System.out.println("  Original Array: Array1 -> ");
        for (int i=0; i < array1.length; i++) {
            System.out.print(array1[i]+" , ");
        }

        System.out.println();
        System.out.println("  Copied Array: copiedArray1 -> ");
        for (int i=0; i < copiedArray1.length; i++) {
            System.out.print(copiedArray1[i]+" , ");
        }
        
        System.out.println();
        System.out.println("  Cloned Array1 -> ");
        for (int i=0; i < clonedArray1.length; i++) {
            System.out.print(clonedArray1[i]+ " , ");
        }

        System.out.println();
        System.out.println();
        System.out.println(" originalArray3 == copiedArray3  : " 
        					+ (array1 == copiedArray1));
        System.out.println("originalArray3.equals(copiedArray3) : "
        					+ (array1.equals(copiedArray1)));
        System.out.println(" Arrays.equals(originalArray3, copiedArray3) : " 
        					+ (Arrays.equals(array1, copiedArray1)));
        System.out.println(" originalArray3 == clonedArray3 : "
						+ (array1 == clonedArray1));
        System.out.println(" originalArray3.equals(clonedArray3) : "
        					+ (array1.equals(clonedArray1)));
        System.out.println(" Arrays.equals(originalArray3, clonedArray3) : " 
        					+ (Arrays.equals(array1, clonedArray1)));
        System.out.println();
        System.out.println("-----------------------------------------------");

    }

// Demostrates the use of utility functions of Arrays Class found in java.util package

    public static void useOfArraysClass() {

        System.out.println();

        String[] array1 = new String[5];
        String[] array2 = new String[5];

        //Use of Arrays.fill() Method
        Arrays.fill(array1, "*");
        Arrays.fill(array2, "-");

        //Use of Arrays.equals() Method
        System.out.println(Arrays.equals(array1, array2) ? "Array1 equals Array2" : 
        						"Array1 Not Equal Array2");
        System.out.println();

//        Use of Arrays.sort() method
        int[] array3 = new int[10];
        for (int i = 0; i < array3.length; i++) {
            array3[i] = (int)(Math.random()*2 );
        }

        System.out.println(" Original Array3 -> ");
        for (int i = 0; i < array3.length; i++) {
            System.out.print(array3[i]+" , ");
        }
        System.out.println();

        System.out.println(" Sorted Array3 -> ");
        Arrays.sort(array3);
        for (int i = 0; i < array3.length; i++) {
            System.out.print(array3[i]+" , ");
        }
        System.out.println();

//     Use of Arrays.binarySearch() method to search for an element in the Array
        int index = Arrays.binarySearch(array3, 5);
        if (index < 0) {
        	 System.out.println("Could not locate the number 5.");
        } else {
            System.out.println("Found the number 5 at location: " + index);
        }
        System.out.println();
        System.out.println("-----------------------------------------------");

    }

    public static void main(String[] args) {

        arrayDeclarationExample();
        copyCloneArrayExample();
        useOfArraysClass();
    }

}

 

Output  

Array Declaration Example

Array3 Elements :
beginner , - , java , - , tutorial , . , com ,
Array4 Elements with Default Values :
100.0 , 200.0 , 300.0 , 400.0 ,
Array5 Elements : 5
beginner , java , tutorial , . , com ,
-----------------------------------------------

Copying and Cloning of Arrays

Original Array: Array1 ->
beginner , - , java , - , tutorial , . , com ,
Copied Array: copiedArray1 ->
beginner , - , java , - , tutorial , . , com ,
Cloned Array1 ->
beginner , - , java , - , tutorial , . , com ,

originalArray3 == copiedArray3 : false
originalArray3.equals(copiedArray3) : false
Arrays.equals(originalArray3, copiedArray3) : true
originalArray3 == clonedArray3 : false
originalArray3.equals(clonedArray3) : false
Arrays.equals(originalArray3, clonedArray3) : true

-----------------------------------------------

Array1 Not Equal Array2

Original Array3 ->
0 , 1 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 0 ,
Sorted Array3 ->
0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 1 ,
Could not locate the number 5.

Download Java Array's Source Code