Search Tips   |   Advanced Search

Java reference

  1. Environment Setup
  2. Hello World
  3. Enums
  4. Inheritance
  5. Methods
  6. The "new" keyword
  7. Source file
  8. Variables
    1. Instance variables
    2. Reference variables
    3. Local variables
    4. Class/Static variables
  9. Modifiers
  10. for loop
  11. The ? : Operator
  12. Number class
  13. Character class
  14. String class
  15. Accessor methods
  16. Concatenate
  17. Format strings
  18. Arrays
    1. Declare array variables
    2. Process array variables
    3. java.util.Arrays
  19. Method Calling
  20. The void keyword
  21. Pass Params
  22. Method Overloading
  23. Command-Line arguments
  24. Constructors
  25. The "this" keyword
  26. Variable arguments
  27. The finalize( ) Method
  28. java.io package
    1. Stream
    2. Byte Streams
    3. Character Streams
    4. Standard Streams
    5. FileInputStream
    6. FileOutputStream
  29. Create Directory
  30. List Directories
  31. Exceptions
    1. Checked
    2. Unchecked
    3. Catch exceptions
    4. Multiple Catch Blocks
    5. The "Throws" keyword
    6. Finally Block
  32. User-defined exceptions
  33. Inner Class
    1. Method-local Inner Class
    2. Anonymous Inner Class
    3. Static Inner Class
  34. The "extends" keyword
  35. The "super" keyword
  36. Superclass Constructor
  37. instanceof Operator
  38. The "implements" keyword
  39. Overriding
  40. Polymorphism
  41. Virtual Methods
  42. Abstract Class
  43. Abstract Methods
  44. Encapsulation
  45. Interface
    1. Extend Interfaces
    2. Multiple Inheritance for interfaces
    3. Tagging Interfaces
  46. Package
  47. Import
  48. Directory Structure of Packages
  49. Set CLASSPATH System Variable

Environment Setup

  1. Download Java and run the executable to install Java.

  2. Set PATH.

    For Windows select...

      My Computer (right-click) | Properties | Advanced tab| Environment variables

    ...and alter the 'Path' variable to include path Java executable. For example...

      C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin

    For Linux, UNIX, Solaris, FreeBSD, set environment variable PATH...

      export PATH =/path/to/java:$PATH'

Hello World

  1. Create file HelloWorld.java and add...

      public class HelloWorld 
         public static void main(String []args) 
            System.out.println("Hello World"); 

  2. Compile code...

      javac HelloWorld.java

  3. Run program.

      java HelloWorld
Java is case sensitive. "Hello" is not equivalent to "hello". With class names, the first letter should be in upper case. If several words are used to form a name of the class, each inner word's first letter should be in upper case. For example:

Method names should start with a lower case letter. If several words are used to form the name of the method, then each inner word's first letter should be in upper case. For example:

The name of the program file should exactly match the class name, with a ".java" suffix. For example: HelloWorld.java

Java program processing starts from the mandatory main() method.


Enums restrict a variable to have one of only a few predefined values.


Create a new subclass class derived from a superclass. Interfaces define the methods a subclass should use from the superclass.


Methods below include barking(), panting() and sleeping().

The "new" keyword

Objects are created from a class using the "new" keyword...

For example...

Source file

There is one public class per source file. The name of the source file should be the public class name appended with .java. A source file can have multiple non-public classes. If the class is defined inside a package, the package statement should be the first statement in the source file. Import statements must be written between the package statement and the class declaration. If there are no package statements, the import statement should be the first line in the source file.


Instance variables

Instance variables and methods are accessed via created objects. Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables are visible for all methods, constructors and blocks in the class.

Default instance value for numbers is 0. For Booleans it is false. For object references it is null. Values can be assigned during the declaration or within the constructor.

Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.

Reference variables

Reference variables are created using class constructors and are used to access objects. These variables are declared to be of a specific type that cannot be changed. The default value of any reference variable is null.

Local variables

Local variables are declared in methods, constructors, or blocks and are destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.

Here, age is a local variable defined inside the dogAge() method.

Class/Static variables

Static variables are declared in a class, using the static keyword, outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Static variables are rarely used other than being declared as constants which never change from their initial value. Static variables are created when the program starts and destroyed when the program stops.

Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.

Static variables can be accessed by calling with the class name ClassName.VariableName.

When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.


If the variables are accessed from an outside class, the constant should be accessed as Player.CONTEST


To use a modifier, include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement

Access modifieers...

Non-access modifiers

for loop

Traverse collection of elements, including arrays.

This will produce the following result...

The ? : Operator

The conditional operator ? : can be used to replace if...else statements.

If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression. If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression.

Number class

We can work with numbers using primitive data types...

...or we can use wrapper classes, which are subclasses of the abstract class Number, to wrap primitive data types...

To use we pass the value of the primitive data type to the constructor of the class...

Character class

We can use primitive data type char...

...or we can use Character objects using the wrapper class Character.

If a primitive char is passed into a method that expects an object, the compiler automatically converts the char to a Character.

Java escape sequences...

To put quotes within quotes, use the escape sequence, \", on the interior quotes...

String class

Create a string...

We can also create String objects using the new keyword and a constructor.

The String class is immutable. After creation, a String object cannot be changed. Use String Buffer and String Builder classes to modify strings.

Accessor methods

Accessor methods are used to obtain information about an object. For example, length() returns the number of characters in a string object.


Concatenate two strings...

Another method is with the + operator...

Format strings

The String class method format() returns a String object.


Declare array variables

Declare array...


Create and assign...

Declare, create, and assign...

Alternative method...

The array elements are accessed through the index. array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Process array variables

We can use either the "for" loop or "foreach" loop to process arrays...

Display all the elements using foreach loop...

Pass array to a method...

Invoke the printArray method...

Reverse an array...


Method Calling

The void keyword

The void keyword creates methods which do not return a value.

Pass Params

Values of a and b are swapped inside method only, and retain original values outside method.

Method Overloading

Method overloading is when a class has two or more methods with the same name, but with different parameters.

Command-Line arguments

Arguments are stored as strings in the String array passed to main( ).

To execute...


Each class has a constructor with the same name as the class. Constructors initialize objects. Constructors typically perform startup procedures required to create a fully formed object, such as giving initial values to the instance variables, Java automatically provides a default constructor that initializes all member variables to zero. A class can have more than one constructor. Java supports singleton classes where only instance of a class can be created.

Constructor without a parameter...

Constructor with a parameter...

The "this" keyword

The "this" keyword references the object of the current class, and is used to differentiate instance variables from local variables with the same name.

Call one type of constructor from other in a class (explicit constructor invocation).

Access the members of a class.

Variable arguments

In the method declaration, specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.

The finalize( ) Method

The finalize( ) method is called just before the final destruction of an object by the garbage collector to ensure that an object terminates cleanly. We specify actions to be performed before an object is destroyed.

The keyword "protected" prevents access to finalize( ) by code defined outside its class. If the program ends before garbage collection occurs, finalize( ) will not execute.

java.io package

The java.io package contains input and output (I/O) classes. All these streams represent an input source and an output destination.


There are two kinds of Streams...

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. The most frequently used classes are, FileInputStream and FileOutputStream.

Copy an input file into an output file...

Create a a file, input.txt, with the following content...

Compile and execute the program...

Character Streams

FileReader reads two bytes at a time. FileWriter writes two bytes at a time.

Standard Streams

Create InputStreamReader to read standard input stream until the user types a "q"...

Compile and execute. The program reads and outputs the same character until we press 'q'...


Read data from files.

Create a file object using File() method...


Create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.

Constructor that takes a file name as a string to create an input stream object to write the file...

Create a file object using File() method as follows...


Create Directory

Create directory /tmp/www/p

List Directories

List files and directories.


Checked exceptions

A checked exception occurs at compile time.

For example, if we use the FileReader class, and the file specified in its constructor doesn't exist, then a FileNotFoundException occurs.

Compiling the above generates...

Unchecked exceptions

An unchecked exception occurs at the time of execution. Also called Runtime exceptions.

For example, we have declared an array of size 4 in our program, and try to call the 5th element of the array then an arrayIndexOutOfBoundsExceptionexception occurs.

If we compile and execute the above program, we will get the following exception.

Catch exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.

When an exception occurs, that exception occurred is handled by catch block associated with the try block. Every try block should be immediately followed either by a catch block or finally block.

If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.

This will produce the following result...

Multiple Catch Blocks

A try block can be followed by multiple catch blocks.

If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches exceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Sample...

The "Throws" keyword

Use the throws keyword to postpone the handling of a checked exception.

A method can declare that it throws more than one exception. The exceptions are declared in a list separated by commas.

Finally Block

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an exception.


This will produce the following result...

Stream and connection are closed explicitly using finally block....

Automatically close resources used within the try catch block...


User-defined exceptions

To write a checked exception extend the exception class. To write a runtime exception, extend the RuntimeException class.




Compile all the above three files, then run BankSample...

Inner Class

An inner class is a class within a class.

To access private members, return them from a method within the inner class. To instantiate the inner class, first instantiate the outer class. Thereafter, use the object of the outer class...

Method-local Inner Class

For a class within a method, the scope of the inner class is restricted to be within the method.

Anonymous Inner Class

An inner class declared without a class name is known as an anonymous inner class. Anonymous classes are declared and instantiated at the same time. Generally, used to override the method of a class or an interface.

A method can accept the object of an interface, an abstract class, or a concrete class.

Static Inner Class

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

The "extends" keyword

Use the "extends" keyword to inherit the properties of a class.

The "super" keyword

The "super" keyword differentiates members of a superclass from the members of a subclass with the same name, invoking the superclass constructor from the subclass. In the example below, both SubClass and SuperClass have a method named display() with different implementations, and a variable named num with different values. We use "super" keyword to differentiate the members of the superclass from the subclass.

When invoking a superclass version of an overridden method the super keyword is used.

Superclass Constructor

If a class is inheriting the properties of another class via the extends keyword, the subclass automatically acquires the default constructor of the superclass. Use the super keyword to invoke the constructor of the superclass with a parameter.

instanceof Operator

With the use of the extends keyword, subclasses can inherit all the properties of the superclass except for the private properties of the superclass. We can assure that Mammal is actually an Animal with the use of the instance operator.


The implements keyword

Use the implements keyword inherit the properties of an interface.


If a class inherits a method from its superclass, and if the method is not marked final, we can override the method.

Even though b is a type of Animal, it runs the move method in the Dog class. During compilation, a check is made on the reference type. During runtime, JVM figures out the object type and runs the method belonging to that particular object. The program compiles properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object. Consider the following example...

This will produce the following result...

This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.


Objects that pass more than one is-a test are considered to be polymorphic.

If not declared final, reference variables can be reassigned to other objects.

All the reference variables d, a, v, o refer to the same Reindeer object in the heap.

Virtual Methods

An overridden method is not invoked unless the child class uses the super keyword within the overriding method. Below, at run time the JVM invokes mailCheck() in the Stipend class. This behavior is referred to as virtual method invocation.

Abstract Class

A class declared "abstract" is not instantiated using the "new" keyword. Rather, an abstract class is inherited by another class. For example, the Stipend class below inherits the properties of the abstract Recipient class. We cannot instantiate the Recipient class, but we can instantiate the Stipend Class, and using this instance we can access all the fields and methods of the Recipient class.

Abstract Methods

An abstract method contains a method signature, but no method body. The actual implementation of the method is determined by child classes. Instead of curly braces, an abstract method will have a semi-colon (;) at the end.

Declare the class containing the abstract method as abstract. Eventually, a descendant class has to implement the abstract method; otherwise, we would have a hierarchy of abstract classes that cannot be instantiated.

Suppose Stipend class inherits the Recipient class, then it should implement the computePay() method...


Encapsulation wraps variables and methods together as a single unit. The variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Encapsulation is also known as data hiding.

To achieve encapsulation in Java...

The get and set methods are referred as getters and setters. A class that wants to access the variables should access them through these getters and setters.


Interfaces are collections of abstract methods that are later inherited by a class. Interfaces may also contain constants, default methods, static methods, and nested types. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface cannot be instantiated and does not contain any constructors. All of the methods in an interface are abstract. The only fields that can appear in an interface must be declared both static and final. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

We do not need to use the abstract keyword with an interface as it is implicitly abstract. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Extend Interfaces

An interface can extend another interface. The child interface inherits the methods of the parent interface.

Multiple Inheritance for interfaces

Unlike a class, interfaces can extend more than one parent interface...

Tagging Interfaces

The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as...

An interface with no methods is referred to as a tagging interface. A tagging interface...

Creates a common parent As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, we can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.


Packages group related classes, interfaces, enumerations and annotations. For example, java.lang and java.io. Packages create a new namespace, eliminating name conflicts with names in other packages. Packages also provide access control.

We can define our own packages. Choose a name for the package, and include a package statement along with that name as the first line in each source file. One package statement per source file only.

To compile a Java program with package statements, use -d...

A folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. Best practice is to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.

Example: Create package named animalia...

Compile the java files into package animalia in the current directory...


If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax. Here, a class named Manager is added to the payroll package that already contains Employee. The Manager class can then refer to the Employee class without using the payroll prefix...

If the Employee class is not in the payroll package the Manager class must use one of the following techniques for referring to a class in a different package.

Directory Structure of Packages

When a class is placed in a package the name of the package becomes a part of the name of the class.

Now, put the source file in a directory whose name reflects the name of the package to which the class belongs...

Now, the qualified class name and pathname would be as follows...

In general, a company uses its reversed Internet domain name for its package names.

  • A company's Internet domain name is ibm.com, then all its package names would start with com.ibm. Each component of the package name corresponds to a subdirectory.

  • The company had a com.ibm.computers package that contained a thinkpad.java source file, it would be contained in a series of subdirectories like this −


    At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.

    For example...

      // File Name: IBM.java
      package com.ibm.computers;
      public class thinkpad 
      class Ups {

    Now, compile this file as follows using -d option...

      $javac -d . thinkpad.java

    The files will be compiled as follows...


    You can import all the classes or interfaces defined in \com\ibm\computers\ as follows −

      import com.ibm.computers.*;

    Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −


    By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

    The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

    Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\computers.

    A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

    Set CLASSPATH System Variable

    View value of current CLASSPATH variable...

    • Windows - C:\> set CLASSPATH
    • UNIX - % echo $CLASSPATH

    Delete contents of CLASSPATH variable.

    • Windows - C:\> set CLASSPATH =
    • UNIX - % unset CLASSPATH; export CLASSPATH

    Set the CLASSPATH variable

    • Windows - set CLASSPATH = C:\users\jack\java\classes
    • UNIX - % CLASSPATH = /home/jack/java/classes; export CLASSPATH