Diferență între revizuiri ale paginii „Java Syntax; A Program's Lexical Structure”

De la WikiLabs
Jump to navigationJump to search
 
Linia 1.106: Linia 1.106:
  
  
<div class="regula"><font color="#ff0000">Regulă:</font> If a class implements an interface, then it must implement all methods declared in the interface, otherwise it must be declared an abstract class, that defers the implementation of some methods to its subclasses.</div>
+
<div class="regula"><font color="#ff0000">Rule:</font> If a class implements an interface, then it must implement all methods declared in the interface, otherwise it must be declared an abstract class, that defers the implementation of some methods to its subclasses.</div>
  
 
More about interfaces in [[Advanced Notions About Object Oriented Programming#Class Hierarchies|Hierarchies]] and [[Advanced Notions About Object Oriented Programming#Polymorphism|Polymorphism]].
 
More about interfaces in [[Advanced Notions About Object Oriented Programming#Class Hierarchies|Hierarchies]] and [[Advanced Notions About Object Oriented Programming#Polymorphism|Polymorphism]].

Versiunea curentă din 5 decembrie 2015 01:47

A Java application is composed of two types of elements: classes and interfaces.

Rule: A Java file (.java) contains exactly one interface or regular class and zero or more inner classes.


Advice: Avoid using inner-classes. These can be implemented as regular classes with the appropriate access modifiers.

Before presenting the lexical structure of a class and interface, we need to list the data types.

Data Types

In Java, there are two types of data: primitives and references. The primitive types refer to those which have immediate values (numerical or logical), and references are "names" which identify objects.

Primitive Types

In Java, the primitive types are:

Name Category Bit count Possible values
byte integer 8 -128 : 127
short integer 16 -32768 : 32767
int integer 32 -2147483648 : 2147483647
long integer 64 -9223372036854775808 : 9223372036854775807
char character 16 Any Unicode character
boolean logic 8 true, false
float floating point 32 ±1.18 x 10-38 : ±3.4 x 1038
double floating point 64 ±2.23 x 10-308 : ±1.80 x 10308

Primitive type variables are declared just like in C. For example:

int someInteger;
int someOtherInteger = 10;
float someFloat = 10.5f;
double someDouble = 5.3 + someFloat;
boolean condition = true;
char oneChar = 'g';
char newLineChar = '\n';

Attention: In Java, there are no unsigned types.

Similar to C, there are cast operators for primitive types in Java as well. Some conversion operations are implicit (from integer to floating point), but some need to be explicitly specified (from floating point to integer, from char to integer), and others are not possible at all (from boolean to any other type and vice-versa).

In Java, primitive type variables are implicitly initialized with the value 0, and the logic ones with the value false.

Reference Types

Reference variables are objects identifiers. Two references can identify the same object but a reference can't identify two objects at the same time.

Rule: Objects, including arrays, are created with the new operator.

References are initialized implicitly with the null value.

Object References

Objects of any type (class), are created by using the new operator, just like in the following example:

1Object obj;
2new Object();
3obj = new Object();

You can see line 2, which instantiate a new object, of class Object, but there is no reference to this newly created object. Thus, immediately after instantiation, the allocated memory is freed by the garbage collector, and it can no longer be accessed. Line 3 instantiate a new object and the obj variable will reference the newly created object. More about instantiation of objects and constructors in the following sections.

Program example Diagram
//...
Object _obj1 = new Object(); //we name this object ID1
Object _obj2 = new Object(); //we name this object ID2
Object _obj3 = _obj1;        //reference to the same object ID1
Object _obj4 = null;         //does not reffer any object
Object _obj5;                //initialized implicitly with null
//...
Reference type variables example

Character Strings in Java - Class String

In Java, character strings are implemented by class String:

String _name;
_name = "George";
//the following two lines are equivalent
String _firstName = "Vasile";
String _firstName2 = new String("Vasile");

The only overloaded operator in the Java language is the operator +, used for concatenating character strings. If operator + is used for concatenating a String with a primitive value, or reference, then the latter is first automatically converted to a String, by using String.valueOf() method.

String _name;
_name= "George";
String _firstName = "Vasile";
String _fullName= _name + " " + _firstName ;
String _title = "I am number " + 7;


Rule: Comparing objects of type String is done by using the method equals(). The comparison operator == compare references in order to check if reference the same object, not if the objects contain the same data.


String _firstName = "Vasile";
String _firstName2 = new String("Vasile");

if(_firstName2 == _firstName ){
    System.out.println("Equal references");
}else{
    System.out.println("Different references");
}

if(_firstName2 .equals(_firstName )){
    System.out.println("Equal strings");
}else{
    System.out.println("Different strings");
}

Displaying a String in the standard output stream, in a console, is done by using the methods "print" or "println" of the field out of type PrintSteam in the System class:

System.out.println("Hello world!");
String _someString = "Trust " + "no. " + 1;
System.out.println(_someString);

Multi-dimensional Arrays

Arrays are treated as objects in Java, as in there are reference type variables which identify the memory area allocated for the array.

Attention: In the case of reference array instantiation (where each location is a reference, and not a primitive type), the new operator only allocate memory for the array, not each of the array's locations.

Attention: Just like in C, the counting of the elements start from 0. Thus, for an array of 5 elements, the valid positions are 0, 1, 2, 3 and 4.

Program example Diagram
int[] _array1;
_array1 = new int[5];
_array1[3] = 10;
Object[] _array2 = new Object[10];
_array2[2] = new Object();
int[][] _array3 = new int[5][3];
_array3[1][1] = 5;
char[][][] _array4;
Example of reference type variables - arrays

All arrays have a field called length which holds the number of locations in the array. This field is read-only.

int[] _array1 = new int[5];
System.out.println(_array1.length); //"5" will be displayed
int[][] _array2 = new int[5][9];
System.out.println(_array2.length); //"5" will be displayed
System.out.println(_array2[0].length); //"9" will be displayed

The Java Class

The class is the base type in Java, as in any other object oriented language.

Rule:Nothing can exist outside a class or interface, except for package and import directives.


Rule: Any file can contain only one regular class.

The keyword that define a class is class, being always followed by the class name and its implementation, between curly brackets.


Convention: Any class or interface name starts with an uppercase letter.


class SomeClass{
    // here comes the implementation of the class
}

The implementation of a class is made of field (property) definitions and method definitions and implementations. The fields represent the data contained by the class and the methods represent its functionality, meaning the functions that modify the field values.

Rule: The operator used to access a class member (field or method) is ".".

Java Packets

Classes of a Java application are structured in a hierarchy similar to the file system: files and directories (folders), with the classes being similar to files and packages to directories. The separator used between package names and classes is ".".

Rule: A Java package can contain classes, interfaces and other packages.

The keyword specifying the package that contains the class/ interface is package. If this directive is missing, the class is placed implicitly in the root of the package hierarchy.

Rule: In order to use a class in an application, that class needs to be imported in any other class that uses it, with two exceptions: the classes in the package java.lang which are automatically imported, and the classes that are in the same package which are implicitly visible.


package myPackage;

import java.util.ArrayList;
import java.io.*;

class TestClass{

public static void main(String[] _args){
    //ArrayList class is in package java.util so it needs to be imported
    ArrayList _arrayList = new ArrayList(); 

    //both FileOutputStream and IOException are in package java.io so they
    //are both available.
    try{
        FileOutputStream _fileOutputStream = new FileOutputStream("test");
        _fileOutputStream.close();
    }catch(IOException _ioe){
        _ioe.printStackTrace();
    }

    //Class System is in package java.lang so it is automatically imported
    System.out.println("Done!");
}

}

Field Definition

Fields, like any other variable, may be of primitive or reference type. They are declared inside the class, but outside any method.

Convention: Field names start with a lowercase letter.


Convention: In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").


class SomeClass{
    
    //fields here
    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;

}

Attention: Fields have different values for each instance of the class, meaning each object.

Program example Diagram
class MainClass{

public static void main(String[] _args){
    SomeClass _obj1 = new SomeClass(); //we name this object ID1
    SomeClass _obj2 = new SomeClass(); //we name this object ID2
    _obj1.somePrimitiveField = 5;
    _obj2.somePrimitiveField = 10;
    System.out.println("Field somePrimitiveField from _obj1 is = " + 
        _obj1.somePrimitiveField + " and from _obj2 is = " +
        _obj2.somePrimitiveField);
    if(_obj1.somePrimitiveField == _obj2.somePrimitiveField){
        System.out.println("They are equal!");
    }else{
        System.out.println("They are NOT equal!");
    }
}

}
Fields in objects example

Method Definition

Methods can be defined and implemented exclusively inside a class. Methods change the state of the object by changing the values of the fields. Just like in C, methods are declared using the following template:

  • zero or more modifiers;
  • returned type (or void if the method does not return a value) - attention, constructors does not have a return type, not even void;
  • method name
  • between parentheses, the list of arguments, defined by type and name, separated by commas (this list can be empty)
  • between curly brackets, the method body (implementation).
Convention: With the exception of constructors, the method names begin with a lowercase letter.


class SomeClass{
    
    //fields here
    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;

//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
    return somePrimitiveField;
}

//---------------------------------------------------------------------
void setSomePrimitiveField(int _somePrimitiveField){
    somePrimitiveField = _somePrimitiveField;
}

//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
    if(_aReferenceField != null){
        aReference = _aReferenceField;
    }

    return aReference != null;
}

}

Primitive or reference type variables declared inside a method, or as an argument of a method, are called local variables and are not class fields.

Convention: In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").

Class Constructors

Constructors are special methods of a class that are called automatically when an object is instantiated. Constructors have two specific properties:

Rule: Constructors have the exact same name with the class they belong to.


Rule: Constructors don't have a return type (not even void).

Example of constructors for class SomeClass:

class SomeClass{
    
    //fields here
    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;

//constructors here
//---------------------------------------------------------------------
SomeClass(){                                    //this is a constructor
    somePrimitiveField = 0;
    someOtherPrimitiveField = false;
    aReferenceField = new Object();
    anotherReferenceFieldToAnArray = null;
}

//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){       //this is another constructor
    somePrimitiveField = _somePrimitiveField;
    someOtherPrimitiveField = false;
    aReferenceField = new Object();
    anotherReferenceFieldToAnArray = null;
}


//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
    return somePrimitiveField;
}

//---------------------------------------------------------------------
void setSomePrimitiveField(int _somePrimitiveField){
    somePrimitiveField = _somePrimitiveField;
}

//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
    if(_aReferenceField != null){
        aReference = _aReferenceField;
    }

    return aReference != null;
}

}


Rule: If a class does have a constructor defined, then the Java compiler will automatically define a default compiler, with no arguments. However, if there is even one constructor defined, the default constructor will not be automatically inserted anymore.


Rule: When instantiating an object (but not arrays), after the new operator, the next element is always a constructor call.

Example of constructor calling:

class MainClass{

public static void main(String[] _args){
    SomeClass _obj1 = new SomeClass();    //this calls the first constructor
    SomeClass _obj2 = new SomeClass(1234);  //this calls the second constructor

    System.out.println(_obj1.getSomePrimitiveField()); //this will print 0
    System.out.println(_obj2.getSomePrimitiveField()); //this will print 1234
}
    
}

this and super Keywords

Keyword this can be used in two ways:

  • as a call to a constructor from another constructor of the same class;
  • as a reference to the current object as an instance of the current class;

Example if using keyword this:

import java.util.ArrayList;

class SomeClass{
    
    //fields here
    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;

//constructors here
//---------------------------------------------------------------------
SomeClass(){                                    //this is a constructor
    this(10);    //this is a call to the other constructor
                 // (see method overloading)
}

//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){       //this is another constructor
    somePrimitiveField = _somePrimitiveField;
    someOtherPrimitiveField = false;
    aReferenceField = new Object();
    anotherReferenceFieldToAnArray = null;
}


//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
    return somePrimitiveField;
}

//---------------------------------------------------------------------
void setSomePrimitiveField(int somePrimitiveField){
    this.somePrimitiveField = somePrimitiveField;
    /*here, "this" is a reference to the 
     *current object. It is used to make the difference 
     *between the field somePrimitiveField and the local
     *variable with the same name. Writing "somePrimitiveField" 
     *with no object specifier ("this") will direct the compiler
     *to the closest defined variable with that name: the local
     *variable:
     */
     somePrimitiveField = 10; //this is the local variable
     this.somePrimitiveField = 10; // this is the field

     /*"this" can also be used for passing the current object
      *as argument to other methods:
      */
     ArrayList _list = new ArrayList();
     _list.add(this);
}

//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
    if(_aReferenceField != null){
        aReference = _aReferenceField;
    }

    return aReference != null;
}

}


Keyword super can be used in two ways (vezi class hierarchies)

  • as a call to a super-class constructor from a constructor in the current class;
  • as a reference to the current object, as an instance of the super-class.
import java.util.ArrayList;

class SomeClass{
    
    //fields here
    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;

//constructors here
//---------------------------------------------------------------------
SomeClass(){                                    //this is a constructor
    this(10);    //this is a call to the other constructor
                 // (see method overloading)
}

//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){       //this is another constructor
    super(); 

    /* Class SomeClass is extended from Object class so
     * the super() call is the call to the Object() 
     * constructor.
     */

    somePrimitiveField = _somePrimitiveField;
    someOtherPrimitiveField = false;
    aReferenceField = new Object();
    anotherReferenceFieldToAnArray = null;
}


//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
    return somePrimitiveField;
}

//---------------------------------------------------------------------
void setSomePrimitiveField(int somePrimitiveField){
    this.somePrimitiveField = somePrimitiveField;
    /*here, "this" is a reference to the 
     *current object. It is used to make the difference 
     *between the field somePrimitiveField and the local
     *variable with the same name. Writing "somePrimitiveField" 
     *with no object specifier ("this") will direct the compiler
     *to the closest defined variable with that name: the local
     *variable:
     */
     somePrimitiveField = 10; //this is the local variable
     this.somePrimitiveField = 10; // this is the field

     /*"this" can also be used for passing the current object
      *as argument to other methods:
      */
     ArrayList _list = new ArrayList();
     _list.add(this);
}

//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
    if(_aReferenceField != null){
        aReference = _aReferenceField;
    }

    return aReference != null;
}

//---------------------------------------------------------------------
String toString(){
    return "SomeClass " + super.toString();

    /* Here, the "super" keyword is used as a reference to the current
     * object but it is calling the method "toString" defined in the
     * superclass (see method overwriting). If the "super" was missing,
     * it would recursively call the same method, crashing the program.
     * Instead, it is now calling an entirely different method belonging
     * to the superclass.
     */
}

}


Rule: Any constructor must start with a call to another constructor (by using either super or this). If this is not explicitly specified, then a super() call is implicitly added by the compiler. In this case, compilation errors may occur, if the super-class does not have a constructor with no arguments defined. To avoid this, an explicit constructor call must be added.


Rule: Any constructor call done by using super or this must be the first statement in a constructor.

Static Members

Static members of a class represent the members which do not change their value or behavior for each distinct object, meaning they are exist in the class context, not the object, or instance context.

class SomeClass{
 
    //fields here
    static int someStaticField;

    int somePrimitiveField;
    boolean someOtherPrimitiveField;
    Object aReferenceField;
    int[][] anotherReferenceFieldToAnArray;
 
}


Program Example Block Diagram
class MainClass{

public static void main(String[] _args){
    SomeClass _obj1 = new SomeClass(); //notam acest obiect cu ID1
    SomeClass _obj2 = new SomeClass(); //notam acest obiect cu ID2
    _obj1.someStaticField = 5;
    _obj2.someStaticField = 10;
    System.out.println("Field someStaticField from _obj1 is = " + 
        _obj1.someStaticField + " and from _obj2 is = " +
        _obj2.someStaticField);
    if(_obj1.someStaticField == _obj2.someStaticField){
        System.out.println("They are equal!");
    }else{
        System.out.println("They are NOT equal!");
    }

    System.out.println("Proper way of accessing static members: " +
        SomeClass.someStaticField);
}

}
Example of static fields in objects


Advice: All methods that only access static fields of the class or no fields at all, should be also declared static.


Convention: Access to static members of a class is done by using the class name, not object references.


Rule: Only fields, methods and inner-classes can be declared static, and not regular classes.

Special Modifiers

Access Modifiers

Modifier Current Class Package Derived Class Outside Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default(no specifier) Yes Yes No No
private Yes No No No
import java.util.ArrayList;

public class SomeClass{
    
    //fields here
    private int somePrimitiveField;
    private boolean someOtherPrimitiveField;
    private Object aReferenceField;
    private int[][] anotherReferenceFieldToAnArray;

//constructors here
//---------------------------------------------------------------------
public SomeClass(){                             //this is a constructor
    this(10);    //this is a call to the other constructor
                 // (see method overloading)
}

//---------------------------------------------------------------------
public SomeClass(int _somePrimitiveField){//this is another constructor
    super(); 

    /* Class SomeClass is extended from Object class so
     * the super() call is the call to the Object() 
     * constructor.
     */

    somePrimitiveField = _somePrimitiveField;
    someOtherPrimitiveField = false;
    aReferenceField = new Object();
    anotherReferenceFieldToAnArray = null;
}


//methods here
//---------------------------------------------------------------------
public int getSomePrimitiveField(){
    return somePrimitiveField;
}

//---------------------------------------------------------------------
protected void setSomePrimitiveField(int somePrimitiveField){
    this.somePrimitiveField = somePrimitiveField;
    /*here, "this" is a reference to the 
     *current object. It is used to make the difference 
     *between the field somePrimitiveField and the local
     *variable with the same name. Writing "somePrimitiveField" 
     *with no object specifier ("this") will direct the compiler
     *to the closest defined variable with that name: the local
     *variable:
     */
     somePrimitiveField = 10; //this is the local variable
     this.somePrimitiveField = 10; // this is the field

     /*"this" can also be used for passing the current object
      *as argument to other methods:
      */
     ArrayList _list = new ArrayList();
     _list.add(this);
}

//---------------------------------------------------------------------
private boolean aMoreComplexMethod(Object _aReferenceField){
    if(_aReferenceField != null){
        aReference = _aReferenceField;
    }

    return aReference != null;
}

//---------------------------------------------------------------------
public String toString(){
    return "SomeClass " + super.toString();

    /* Here, the "super" keyword is used as a reference to the current
     * object but it is calling the method "toString" defined in the
     * superclass (see method overwriting). If the "super" was missing,
     * it would recursively call the same method, crashing the program.
     * Instead, it is now calling an entirely different method belonging
     * to the superclass.
     */
}

}


Advice: Usually, fields are declared private (see encapsulation), and getters and setters methods and constructors are declared public. There are, of course, exceptions.


The public modifier

A public class or member can be accessed from any other class.

The protected modifier

A protected field or method is accessible for the classes defined in the same package and for derived classes.

Rule: A regular class can't have the protected access modifier.
The default modifier (not explicit)

The lack of an access specifier means that the element is accessible from the current class or classes from the same package, but not other classes.

The private modifier

A private field or method can only be accessed from the defining class.

Rule: A regular class can't have the private access modifier.

The final modifier

The final modifier can be applied to:

  • a class - the class can't be extended;
  • an interface - the interface can't be extended;
  • a method - the method can't be overridden;
  • a field - the field can only take one value and it will remain constant throughout of the object's lifetime;

A field which is both static and final is called a class constant.

The abstract modifier

Any method without body (without implementation) is an abstract method

Rule:If a class contains at least one abstarct method, that class must be declared abstract, too.


Rule:An abstract class cannot be instantiated, but you may extend it. Any class derived from an abstract class must implement the inherited abstract methods, or be also declared abstract.

Example:

abstract class Sorter{

    protected Object[] data;

public Sorter(Object[] _data){
    data = _data;
}

//this is an abstract method
protected abstract void sort();

public Object[] getResult(){
    sort();
    return data;
}

}


class BubbleSorter extends Sorter{

public BubbleSorter(Object[] _data){
    super(data);
}

//this is the implementation of the abstract method
protected void sort(){
    boolean _done;
    do{
        _done = true;
        for(int i=0; i<data.length - 1; i++){
            if(compare(data[i], data[i + 1]) < 0){
                Object _tmp = data[i];
                data[i] = data[i + 1];
                data[i + 1] = _tmp;
                _done = false;
            }
        }
    }while(!_done);
}

private int compare(Object _obj1, Object obj2){
    //...
} 

}

The volatile modifier

A field is declared volatile when that field for some object is accesed by more than one thread, and you want any update to be propagated into the main memory. When a thread writes into a volatile field, any other thread that access that field will see its updated value. Otherwise, the update might stay in the thread's local cache while the other threads continue to use the old value from their local caches.

The volatile fields allow threads to communicate without employing the synchronization mechanism, but this is possible only if there is no any risk to run into race conditions. More details in Concurrent Programming - Threads.

The transient modifier

A class field is declared transient if you do not want it's value to be serialized together with the other object's fields when the object is serialized. It's value will be the default value after the object is deserialized (see Serialization).

The synchronized modifier

A synchronized method or block of statements cannot be executed by more than one thread at a time. If two threads need to call such a method, or execute such a block, one of them must wait for the other to return from the method or to exit the block.
Example:

import java.util.ArrayList;

public class Queue extends ArrayList{

public Queue(){
    super();
}

public synchronized void push(Object _obj){
    add(_obj);
}

public Object pop(){
    if(size() != 0){
        synchronized(this){
            return remove(0);
        }
    }else{
        throw new RuntimeException("Queue empty!");
    }
}

}

More about threads and their synchronization in Concurrent Programming - Threads.

The native modifier

It may be the case that a certain system function or a library function (.dll or .so for example) cannot be called from Java. In that case, the Java application must rely on some functions that are compiled in the native language of the real machine (C or C++ for example), not in the JVM's language. These functions are marked native. The Jana Native Interface JNI allows you to call such functions from a Java program, and also to call Java functions from a native language program.

More about native methods implemntation at Oracle's site.

Advice: Try to avoid using native methods because they are not portable.

Class Constants

A field declared at the same time static and final is called a class constant.

Class Extension

The Java language supports simple inheritance (see class hierarchies and polymorphism). The keyword use for extending a class is extends.

Rule: A Java class extends exactly one other class (if this is not specified, then the base class is Object).

Example:

//---------------------------------------------------
//file Vehicle.java
public class Vehicle{          //class Vehicle extends Object

    protected int cylinders;
    protected float maxSpeed;
    protected static float maxAcceptedVehicleMass;
    protected float vehicleMass;

public void startEngine(){
    //...
}

}

//---------------------------------------------------
//file Truck.java
public class Truck extends Vehicle{  //class Truck extends Vehicle

    protected float maxCargoWeight;
    protected float currentCargoWeight;

public void loadCargo(float _cargo){
    // protected fields maxAcceptedVehicleMass and vehicleMass 
    // are inherited from Vehicle class
    if(currentCargoWeight + _cargo <= maxCargoWeight &&
        vehicleMass + currentCargoWeight + _cargo <= maxAcceptedVehicleMass){
        currentCargoWeight += _cargo;
    }
}

}

Generic classes

There are situations where a particular instance of a class works exclusively with a particular type of data. In this case, if the class is designed to use data of some base type (for example of Object type), then additional and time consuming steps must be taken to down-cast the base data type (the Object type data) to the particular type in order to use them. More than that, these down-cast operations are checked only at runtime, increasing the risk of inserting programming errors that are not detectable at compile time. As an example, we describe below a Stack class that stores references of Object type, and another class, StringStacker, that uses this stack exclusively for String objects::

public class Stack{

    private Object[] stackArray;
    private int stackTop;

public Stack(int _size){
    stackArray = new Object[_size];
    stackTop = 0;
}

public Object pop() throws Exception{
    if(stackTop > 0){
        return stackArray[--stackTop];
    }

    throw new Exception("Stack empty");
}

public void push(Object _obj) throws Exception{
    if(stackTop < stack.length){
        stackArray[stackTop++] = _obj;
        return;
    }

    throw new Exception("Stack full");
}

}


public class StringStacker{

public static void main(String[] _args){
    Stack _stack = new Stack(10);
    try{
        // String is automatically up-cast to Object
        // we could just as well push any kind of reference
        // on this stack, by mistake, and reading and trying
        // to down-cast it to String will throw a runtime ClassCastException
        _stack.push("Hello world!");
        _stack.push("Byebye world");

        // Object must be manually down-cast to String
        // every time, even if it's obvious that all 
        // objects on the stack are Strings
        String _secondString = (String)_stack.pop();
        String _firstString = (String)_stack.pop();

        System.out.println(_secondString + ", " + _firstString);
    }catch(Exception _e){
        System.out.println("Stack error: " + _e.getMessage());
    }
}

}

This example may be solved elegantly with a generic Stack class. The StringStacker needs not downcast the data.

public class Stack <GenericType>{

    private GenericType[] stackArray;
    private int stackTop;

public Stack(int _size){
    stackArray = new GenericType[_size];
    stackTop = 0;
}

public GenericType pop() throws Exception{
    if(stackTop > 0){
        return stackArray[--stackTop];
    }

    throw new Exception("Stack empty");
}

public void push(GenericType _obj) throws Exception{
    if(stackTop < stack.length){
        stackArray[stackTop++] = _obj;
        return;
    }

    throw new Exception("Stack full");
}

}


public class StringStacker{

public static void main(String[] _args){
    // at this point, the _stack object is an instance
    // of the class Stack, where GenericType has been
    // replaced by String
    Stack<String> _stack = new Stack<String>(10);
    try{
        // now the push method only takes Strings as
        // an argument; trying to push an Object will 
        // fail with a compile time error
        _stack.push("Hello world!");
        _stack.push("Byebye world");

        // pop() will now return a String so casting
        // is no longer necessary
        String _secondString = _stack.pop();
        String _firstString = _stack.pop();

        System.out.println(_secondString + ", " + _firstString);
    }catch(Exception _e){
        System.out.println("Stack error: " + _e.getMessage());
    }
}

}

More about generics in this tutorial from Oracle.

Java Interfaces

The Java interface is a structure equivalent to an abstract class without variables and whose methods are all abstract. The only fields that interfaces may have are static constants. Unlike class inheritance, that allows a class to inherit only one base class (simple inheritance), a class may implement any number of interfaces.

Hint: Avoid fields in interfaces. Conflicts may appear when a class implements two interfaces with the same name for some constants.


//---------------------------------------------------
//file Closeable.java
public interface Closeable{
    public void close();
}

//---------------------------------------------------
//file Openable.java
public interface Openable{
    public void open();
}

//---------------------------------------------------
//file Stream.java
public class Stream implements Openable, Closeable{

public void close(){
    //.. something here
}
public void open(){
    //... something here
}

}
//---------------------------------------------------


Rule: If a class implements an interface, then it must implement all methods declared in the interface, otherwise it must be declared an abstract class, that defers the implementation of some methods to its subclasses.

More about interfaces in Hierarchies and Polymorphism.

Iterative Constructs

The for statement

The for statement has two variants. One of them is identical to the C for statement:

for (initializations; condition; updates) {
    //...
}
  • initializations - statements that are executed only once, at the beginning of the first iteration;
  • condition - an expression that controls the loop. It is evaluated prior to entering an iteration. Enter the iteration if the condition is true, otherwise exit the loop. If the condition is missing, it is assumed to be always true.
  • updates - statements that are executed at the end of each iteration;


Example 1: a loop that displays all elements of an array.

int[] someArray = getArray();

for (int i=0; i < someArray.length; i++) {
    System.out.println(someArray[i]);
}


Example 2: a loop that iterates through a list:

Node firstNode = getList();

for (Node _eachNode = firstNode; _eachNode != null; _eachNode = _eachNode.getNextNode()) {
    System.out.println(_eachNode);
}


Example 3: an infinite for loop (don't do that!):

for ( ; ; ) {
    System.out.println("Freedom!");
}


The other variant of the for statement is used to iterate through an array, and uses a reference that directly points to the elements of the array.
Its syntax is:

for (declaration; array) {
    //...
}
  • declaration - declares a reference whose type is that of the elements of the array;
  • array - the name of the array. The loop starts with the reference pointing to the first element of the array. At the end of each iteration the reference is moved to the next element. The loop ends after its iteration for the last element of the array or if a break or return statement is encountered within some iteration.


Example 4: a for loop that behaves exactly as the loop from Example 1:

int[] someArray = getArray();

for (int element : someArray) {
    System.out.println(element);
}

The while statement

The while statement has the same syntax as in C:

while (condition){
    //... something
}
  • condition - an expression evaluated at the beginning of each iteration. If true, the loop continues. If false, exit the loop.


Example 5: At each iteration a is incremented while b is decremented. The loop ends when a becomes greater than b.

int a = 3;
int b = 13;
while (a < b) {
    a++;
    b--;
    System.out.println(a * b);
}

The do-while statement

This statement is also written as in C:

do {
    //... something
} while (condition);
  • condition - an expression evaluated at the end of each iteration. If true, the loop goes to the another iteration. If false, exit the loop.


Example 6: runs exactly as the previous one.

int a = 3;
int b = 13;
do{
    a++;
    b--;
    System.out.println(a * b);
} while (a < b);


The difference between while and do-while loops is in the way the condition is evaluated. For while loops it is evaluated at the beginning of each iteration, whereas for do-while loops it's evaluated at the end of each iteration. A do-while loop executes at least one iteration, whereas a while loop may not be entered at all if its condition is false upon entering the loop.

The break and continue statements

The break and continue statements behaves exactly as in C/C++, and they are used to exit a loop (break) or to jump to the end of the current iteration (continue).

Example 7: search after the first element of an unsorted array of numbers whose value is greater than 100. If the number is odd, jump to the next number. If the number is even and greater than 100, exit the loop:

int search(int[] someArray){
    int result = 0;

    for (int element: someArray) {
        if (element % 2 != 0) {
            continue;
        }
        if (element > 100) {
            result = element;
            break;
        }
    }

    return result;
}


The for, while and do-while loops may be nested one within another.

Rule: break and continue statements affect only the most inner for, while or do-while loop in which they reside.

Conditional Constructs

Conditional operator (the ? operator)

The conditional operator is written and works as in C:

(evaluation_expression ? expression_for_true : expression_for_false)

The value of this conditional operation depends on the logic value of the evaluation_expression. If it's true, the conditional operation takes the value of the expression_for_true, otherwise it takes the value of expression_for_false.

Example 8: the static method max returns the greatest value of a pair of numbers. The reurn value, either the value of a, or the value of b, depends on how the evaluation_expression, a > b, is evaluated.

public class Utils{

//private constructor means the class can't be instantiated
private Utils(){ 
    //nothing here
}

public static float max(float a, float b){
    // if a is greater than b, the expression is
    // evaluated to a and the value of a is returned
    // else the expression is evaluated to b and the 
    // value of b is returned
    return a > b ? a : b;
}

}

The if - else statements

The if - else statements are the standard conditional statements, and their syntax is exactly as in C:

if (condition) {
    // statements_if_true
} else {
    // statements_if_false
}
  • condition - a logic expression. If it evaluates to true, the statements from statements_if_true block are executed, otherwise the statements of the else block, statements_if_false, are executed.


Example 9: returns the maximum number from a pair.

public static float max(float a, float b){
    float _result = 0;
    if (a > b) {
        result = a;
    } else {
        result = b;
    }
    return result;
}


The if - else statements may be nested as in the example below.

Example 10: limit the range of an input value to [lowLimit, highLimit].

public static float clamp(float value, float lowLimit, float highLimit){
    float _result = 0;
    if (_value < _lowLimit) {
        return lowLimit;
    } else if (_value > _highLimit) {
        return highLimit;
    } else {
        return value;
    }
}


The else block may be missing. The if block is executed only if condition is true.

Example 11: compute the absolute value of a number.

public static float abs(float a){
    if( a < 0) {
        a = -a;
    }
    return a;
}

The switch statement

It is also written as in C. It is useful when there are more than two possible branches from a point in your program:

switch (expression) {
    case Value_1:
        // branch_1
        break;
    case Value_2:
        // branch_2
        break;
    case Value_3:
        // branch_3
        break;
    default:
        // branch_default
}
  • expression - an expression that evaluates to an integer;
  • If expression evaluates to Value_i the program jumps to branch_i. Value_i is an integer constant (of type byte, short, int or long).
  • If expression evaluates to a value other than any of the Value_i constants, the program jumps to the branch_default block, or if default keyword is missing, to the first instruction after the whole switch block.
  • The break statement may be written only at the end of branches, and it forces the program to exit the switch block.


Be careful: If the break statements is missing from some branch the program enters the next branch! The statements are executed branch after branch until a break statement is encountered, or until the end of the whole switch block.


Example 12:

public String intToString(int _value) {
    String _result = "";
    switch (_value){
        case 0: _result = "zero"; break;
        case 1: _result = "one"; break;
        case 2: _result = "two"; break;
        case 3: _result = "three"; break;
        case 4: _result = "four"; break;
        case 5: _result = "five"; break;
        case 6: _result = "six"; break;
        case 7: _result = "seven"; break;
        case 8: _result = "eight"; break;
        case 9: _result = "nine"; break;
        default: _result = "more than nine"; break;
    }
    return _result;
}


Starting from JDK 1.7 strings are also accepted for evaluation. If you use a String object as expression, all Value_i constants must be literal strings;

Keywords Related to Exceptions

  • throw - used to generate an exception. The throw keyword is followed by a reference to the exception object to be thrown, or by an explicit instantiation of that exception object.
  • throws - appears in the declaration of a method that does not handle some types of exception. The throws keyword is followed by a coma-separated list of that exception types (their order is not important).
  • try and catch - used if you want to handle locally the exception. The try keyword is attached to a block of statements that is prone to throw exceptions. The catch keyword precedes a block of statements designed to handle a particular exception. A try block may be followed by multiple catch blocks, each designed to handle a particular type of exception (the order of catch blocks is critical: derived exceptions must precede the basic ones).


Example 13:

public class TestClass{

    private int value;

public static void main(String[] _args){
    try{
        TestClass _obj = new TestClass(10);
        _obj.someMethod();
    }catch(Exception _e){
        System.out.println("Exception caught: " + _e.getMessage());
    }

    try{
        TestClass _obj = new TestClass(-10);
        _obj.someMethod();
    }catch(Exception _e){
        System.out.println("Exception caught: " + _e.getMessage());
    }

}

public TestClass(int _value) throws Exception{
    if(_value < 0){
        throw new Exception("The value must not be negative: " + _value);
    }
    value = _value;
}

public void someMethod(){
    System.out.println("Running method for value " + value);
}

}

More about exceptions and how they are handled in Exception Handling.

Operators

The complete list of Java operators:

Precedence Operator Description Associativity
1 () method call from left to right
[] acces an array's element
. "dot" operator (acces to a class' member)
2 ++ -- postfix increment and decrement
3 ++ -- prefix increment and decrement from right to left
+ - unary plus and minus
! ~ logic NOT and bitwise NOT
(type) val type cast
new object or array instantiation
4 * / % Multiplication, division and modulo (remainder) from left to right
5 + - addition and subtraction
+ string concatenation
6 << >> >>> leftshift, rightshift, arithmetic righshift (preserves sign)
7 < <= "less than" and "less than or equal" logic comparisons
> >= "greater than" and "greater than or equal" logic comparisons
instanceof type comparison
8 == != "equal" and "not equal" logic comparisons
9 & bitwise AND
10 ^ bitwise XOR (exclusive OR)
11 | bitwise OR (inclusive OR)
12 && logic AND
13 || logic OR
14 c ? t : f ternary conditional operator (see #Conditional operator (the ? operator)) from right to left
15 = assignment
+= -= compound assignment with addition or subtraction
*= /= %= compound assignment with multiplication, division, modulo
<<= >>= >>>= compound assignment with leftshift, rightshift and arithmetic rightshift
&= ^= |= compound assignment with bitwise AND, XOR, and OR

Unlike in C++, the operators cannot be overloaded in Java.

Web Resources

  1. The Java Language Specifications, v.7
  2. The Java Virtual Machine Specifications, v.7 (advanced topic)
  3. Java Syntax - Wikipedia