Java reference
- Environment Setup
- Hello World
- Enums
- Inheritance
- Methods
- The "new" keyword
- Source file
- Variables
- Modifiers
- for loop
- The ? : Operator
- Number class
- Character class
- String class
- Accessor methods
- Concatenate
- Format strings
- Arrays
- Method Calling
- The void keyword
- Pass Params
- Method Overloading
- Command-Line arguments
- Constructors
- The "this" keyword
- Variable arguments
- The finalize( ) Method
- java.io package
- Create Directory
- List Directories
- Exceptions
- User-defined exceptions
- Inner Class
- The "extends" keyword
- The "super" keyword
- Superclass Constructor
- instanceof Operator
- The "implements" keyword
- Overriding
- Polymorphism
- Virtual Methods
- Abstract Class
- Abstract Methods
- Encapsulation
- Interface
- Package
- Import
- Directory Structure of Packages
- Set CLASSPATH System Variable
Environment Setup
- Download Java and run the executable to install Java.
- Set PATH.
For Windows select...
System (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
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:
- Create file HelloWorld.java and add...
public class HelloWorld { public static void main(String []args) { System.out.println("Hello World"); } }- Compile code...
javac HelloWorld.java
- Run program.
java HelloWorld
class HelloWorldClass
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:
public void myMethodName()
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.
public static void main(String args[])
Enums
Enums restrict a variable to have one of only a few predefined values.
public class OrderSmoothieProc { public static void main(String args[]) { OrderSmoothie smoothie = new OrderSmoothie(); smoothie.size = OrderSmoothie.OrderSmoothieSize.MEDIUM ; System.out.println("Size: " + smoothie.size); } } class OrderSmoothie { enum OrderSmoothieSize{ SMALL, MEDIUM, LARGE } OrderSmoothieSize size; }
Inheritance
Create a new subclass class derived from a superclass. Interfaces define the methods a subclass should use from the superclass.
Methods
Methods below include barking(), panting() and sleeping().public class Dog { String breed; int age; String color; void barking() { } void panting() { } void sleeping() { } }
The "new" keyword
Objects are created from a class using the "new" keyword...For example...
public static void main(String []args) { // Create object myFinch Finch myFinch = new Finch( "beaky" ); } public class Finch { public Finch(String name) { // Constructor with one parameter, name. System.out.println("Passed Name is: " + name ); } }
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.
Variables
Variable Description Instance Defined within a class but outside any method. Reference Created using class constructors Local Defined inside methods, constructor or blocks. Class Defined within a class, outside any method, with the static keyword.
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.
public class Finch { /* Instance variable */ int finchAge; public static void main(String []args) { Finch myFinch = new Finch( "beaky" ); /* Call class methods to set and get finch's age */ myFinch.setAge( 2 ); myFinch.getAge( ); /* Access instance variable */ System.out.println("Variable Value: " + myFinch.finchAge ); } public Finch(String name) { // Constructor with one parameter, name System.out.println("Name chosen is: " + name ); } public void setAge( int age ) { finchAge = age; } public int getAge( ) { System.out.println("Finch's age is: " + finchAge ); return finchAge; } }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.
import java.io.*; public class Player { // "name" instance variable is visible for any child class. public String name; // "winnings" variable is visible in Player class only. private double winnings; public static void main(String args[]) { Player playerOne = new Player("Raonic"); playerOne.setWinnings(1000); playerOne.printEmp(); } // "name" variable is assigned in the constructor. public Player (String playerName) { name = playerName; } // The "winnings" variable is assigned a value. public void setWinnings(double prizeMoney) { winnings = prizeMoney; } // Print the player details. public void printEmp() { System.out.println("name: " + name ); System.out.println("winnings: " + winnings); } }
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.
Animal animal = new Animal("panda");
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.
public class Dog { public static void main(String args[]) { Dog dog = new Dog(); dog.dogAge(); } public void dogAge() { int age = 0; age = age + 7; System.out.println("Doggy age is: " + age); } }
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.
import java.io.*; public class Player { private static double winnings; // CONTEST is a constant public static final String CONTEST = "Lottery"; public static void main(String args[]) { winnings = 1000; System.out.println(CONTEST + "average winnings: " + winnings); } }Output...
Lottery average winnings: 1000If the variables are accessed from an outside class, the constant should be accessed as Player.CONTEST
Modifiers
To use a modifier, include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement
public class className { // ... } private boolean myFlag; static final double weeks = 9.5; protected static final int BOXWIDTH = 42; public static void main(String[] arguments) { // body of method }Access modifieers...
default Visible to the package. No modifiers are needed. private Visible to the class only public Visible to the world protected Visible to the package and all subclasses Non-access modifiers
static Create class methods and variables. final Finalize the implementations of classes, methods, and variables. abstract Create abstract classes and methods. strictfp
synchronized
volatileUsed for threads
for loop
Traverse collection of elements, including arrays.public class ForLoop { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names = {"James", "Roger", "Jo", "Tim"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }This will produce the following result...
10, 20, 30, 40, 50, James, Roger, Jo, Tim,
The ? : Operator
The conditional operator ? : can be used to replace if...else statements.Exp1 ? Exp2 : Exp3;
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...
int i = 500;
float era = 3.65;
double mask = 0xaf;...or we can use wrapper classes, which are subclasses of the abstract class Number, to wrap primitive data types...
- Integer
- Long
- Byte
- Double
- Float
- Short
To use we pass the value of the primitive data type to the constructor of the class...
public class Samplewrapper { public static void main(String args[]) { // Box int to an Integer object Integer x = 5; // Unbox the Integer object to an int x = x + 10; System.out.println(x); } }
Character class
We can use primitive data type char...char ch = 'a';
char uniChar = '\u039A';
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };...or we can use Character objects using the wrapper class Character.
Character ch = new Character('a');
If a primitive char is passed into a method that expects an object, the compiler automatically converts the char to a Character.
// Primitive char 'a' is boxed into the Character object ch Character ch = 'a'; // Primitive char 'x' is boxed for method test. Return is unboxed to char 'c' char c = test('x');Java escape sequences...
Escape Description \t tab \b backspace \n newline \r carriage return \f form feed \' single quote \" double quote \\ backslash To put quotes within quotes, use the escape sequence, \", on the interior quotes...
public class QuoteSample { public static void main(String args[]) { System.out.println("The \"new\" keyword creates an object."); } }
String class
Create a string...
String greeting = "Hello world!";We can also create String objects using the new keyword and a constructor.
public class StringSample { public static void main(String args[]) { char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String helloString = new String(helloArray); System.out.println( helloString ); } }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.
public class StringSample { public static void main(String args[]) { String napoleon = "Able was I ere I saw Elba."; int len = napoleon.length(); System.out.println( "String Length is : " + len ); } }
Concatenate
Concatenate two strings...
string1.concat(string2);Another method is with the + operator...
public class StringSample { public static void main(String args[]) { String string1 = "I ere I "; System.out.println("Able was " + string1 + "saw Elba"); } }
Format strings
The String class method format() returns a String object.
String fs;
fs = String.format("Float variable: %f. Integer variable: %d. String: %s", floatVar, intVar, stringVar);
System.out.println(fs);
Arrays
Declare array variables
Declare array...
dataType[] arrayRefVar;
Example...
double[] myList;
Create and assign...
arrayRefVar = new dataType[arraySize];
Declare, create, and assign...
dataType[] arrayRefVar = new dataType[arraySize];Alternative method...
dataType[] arrayRefVar = {value0, value1, ..., valuek};The array elements are accessed through the index. array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
double[] myList = new double[10];
Process array variables
We can use either the "for" loop or "foreach" loop to process arrays...
public class MyArray { public static void main(String[] args) { double[] myList = {1.1, 1.2, 1.3, 1.4}; for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Sum all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Find the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }Display all the elements using foreach loop...
public class ForeachArray { public static void main(String[] args) { double[] myList = {1.1, 1.2, 1.3, 1.4}; for (double element: myList) { System.out.println(element); } } }Pass array to a method...
public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }Invoke the printArray method...
printArray(new int[]{3, 1, 2, 6, 4, 2});Reverse an array...
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; }
java.util.Arrays
- public static int binarySearch(Object[] a, Object key)
Binary search of array Object. Returns index of the search key. Sort array prior to calling.
- public static boolean equals(long[] a, long[] a2)
Return true if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
- public static void fill(int[] a, int val)
Assign the specified int value to each element of the specified array of ints.
- public static void sort(Object[] a)
Sort array of objects into an ascending order.
Method Calling
public class SampleMinNumber { public static void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.println("Minimum Value = " + c); } public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } }
The void keyword
The void keyword creates methods which do not return a value.public class SampleVoid { public static void main(String[] args) { RankPoints(100.0); } public static void RankPoints(double points) { if (points >= 99.0) { System.out.println("Rank: 1st"); } else if (points >= 25.5) { System.out.println("Rank: 2nd"); } else { System.out.println("Rank: 3rd"); } } }
Pass Params
Values of a and b are swapped inside method only, and retain original values outside method.
public class SwapSample { public static void main(String[] args) { int a = 100; int b = 200; System.out.println("Before swapping, a = " + a + " and b = " + b); swapFunction(a, b); System.out.println("After swapping, a = " + a + " and b is " + b); } public static void swapFunction(int a, int b) { int c = a; a = b; b = c; } }
Method Overloading
Method overloading is when a class has two or more methods with the same name, but with different parameters.
public class SampleOverloading { public static void main(String[] args) { int a = 100; int b = 50; double c = 7.5; double d = 5.4; int result1 = minFunction(a, b); double result2 = minFunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2); } // Return integer public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } // Return double public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; } }
Command-Line arguments
Arguments are stored as strings in the String array passed to main( ).
public class CommandLine { public static void main(String args[]) { for(int i = 0; i<args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } }To execute...
$java CommandLine Here are some commandline arguments: 400 300 200 100
Constructors
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.
public class Finch { // Constructor with no parameters public Finch() { } // Constructor with one parameter, name public Finch(String name) { } }Constructor without a parameter...
public class ConsSample { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); } } class MyClass { int x; // Constructor MyClass() { x = 10; } }Constructor with a parameter...
public class ConsSample { { MyClass t1 = new MyClass( 10 ); MyClass t2 = new MyClass( 20 ); System.out.println(t1.x + " " + t2.x); } } class MyClass { int x; // Constructor MyClass(int i ) { x = i; } }
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.class Student { int age; Student(int age) { this.age = age; } }Call one type of constructor from other in a class (explicit constructor invocation).
class Student { int age Student() { this(20); } Student(int age) { this.age = age; } }Access the members of a class.
public class MySample { // Instance variable int num = 10; public static void main(String[] args) { // Instantiate the class MySample obj1 = new MySample(); // Invoke the print method obj1.print(); // Pass a new value to the num variable using constructor with parameter MySample obj2 = new MySample(30); // Invoke the print method again obj2.print(); } MySample() { System.out.println("Executing with keyword this"); } MySample(int num) { // Invoke the default constructor this(); // Assign the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println("Welcome aboard"); } public void print() { // Local variable int num = 20; System.out.println("value of local variable num is : "+num); System.out.println("value of instance variable num is : "+this.num); // Invoking the greet method of a class this.greet(); } }
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.
public class VarargsSample { public static void main(String args[]) { // Call method with variable args printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } public static void printMax(double... numbers) { if (numbers.length == 0) { System.out.println("No argument passed"); return; } double result = numbers[0]; for (int i = 1; i < numbers.length; i++) if (numbers[i] > result) result = numbers[i]; System.out.println("The max value is " + result); } }
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.protected void finalize( ) { // finalization code here }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.
Stream
There are two kinds of Streams...
InPutStream Read data from a source. OutPutStream Write data to a destination.
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...
import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }Create a a file, input.txt, with the following content...
This is test for copy file.Compile and execute the program...
$javac CopyFile.java $java CopyFile
Character Streams
FileReader reads two bytes at a time. FileWriter writes two bytes at a time.
import java.io.*; public class CharCopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Standard Streams
Create InputStreamReader to read standard input stream until the user types a "q"...
import java.io.*; public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println("Enter characters, 'q' to quit."); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != 'q'); } finally { if (cin != null) { cin.close(); } } } }Compile and execute. The program reads and outputs the same character until we press 'q'...
$javac ReadConsole.java $java ReadConsole Enter characters, 'q' to quit. 1 1 e e q q
FileInputStream
Read data from files.
InputStream f = new FileInputStream("C:/java/hello");Create a file object using File() method...
File f = new File("C:/java/hello"); InputStream f = new FileInputStream(f);
FileOutputStream
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...
OutputStream f = new FileOutputStream("C:/java/hello")Create a file object using File() method as follows...File f = new File("C:/java/hello"); OutputStream f = new FileOutputStream(f);Sample...
import java.io.*; public class FileStreamSample { public static void main(String args[]) { try { byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x < bWrite.length ; x++) { // Write the bytes os.write( bWrite[x] ); } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); } } }
Create Directory
Create directory /tmp/www/p
import java.io.File; public class CreateDir { public static void main(String args[]) { String dirname = "/tmp/www/p"; File d = new File(dirname); // Create directory d.mkdirs(); } }
List Directories
List files and directories.
import java.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // Create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // For each name in the path array for(String path:paths) { System.out.println(path); } } catch (Exception e) { e.printStackTrace(); } } }
Exceptions
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.
import java.io.File; import java.io.FileReader; public class FilenotFound_Sample { public static void main(String args[]) { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } }Compiling the above generates...
C:\>javac FilenotFound_Sample.java FilenotFound_Sample.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error
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.
public class Unchecked_Sample { public static void main(String args[]) { int num[] = {1, 2, 3, 4}; System.out.println(num[5]); } }If we compile and execute the above program, we will get the following exception.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at exceptions.Unchecked_Sample.main(Unchecked_Sample.java:8)
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.
try { // Protected code } catch (ExceptionName e1) { // Catch block }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.
import java.io.*; public class ExcepSample { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }This will produce the following result...
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
Multiple Catch Blocks
A try block can be followed by multiple catch blocks.
try { // Protected code } catch (ExceptionType1 e1) { } catch (ExceptionType2 e2) { } catch (ExceptionType3 e3) { }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...
try { file = new FileInputStream(fileName); x = (byte) file.read(); } catch (IOException i) { i.printStackTrace(); return -1; } // Not valid! catch (FileNotFoundException f) { f.printStackTrace(); return -1; }
The "Throws" keyword
Use the throws keyword to postpone the handling of a checked exception.
import java.io.*; public class className { public void deposit(double amount) throws RemoteException { throw new RemoteException(); } // Remainder of class definition }A method can declare that it throws more than one exception. The exceptions are declared in a list separated by commas.
import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } // Remainder of class definition }
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.
try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } finally { }Sample
public class ExcepSample { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } }This will produce the following result...
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executedStream and connection are closed explicitly using finally block....
import java.io.File; import java.io.FileReader; import java.io.IOException; public class ReadData_Sample { public static void main(String args[]) { FileReader fr = null; try { File file = new File("file.txt"); fr = new FileReader(file); char [] a = new char[50]; // Read the content to the array fr.read(a); for(char c : a) System.out.print(c); } catch (IOException e) { e.printStackTrace(); } finally { try { fr.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }Automatically close resources used within the try catch block...
try(FileReader fr = new FileReader("file path")) { // use the resource } catch () { // body of catch }Sample.
import java.io.FileReader; import java.io.IOException; public class Try_withSample { public static void main(String args[]) { try(FileReader fr = new FileReader("E://file.txt")) { char [] a = new char[50]; // Read the content to the array fr.read(a); for(char c : a) System.out.print(c); } catch (IOException e) { e.printStackTrace(); } } }
User-defined exceptions
To write a checked exception extend the exception class. To write a runtime exception, extend the RuntimeException class.
public class BankSample { public static void main(String [] args) { SavingsAccount c = new SavingsAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); System.out.println("Balance $" + c.getBalance()); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("Balance $" + c.getBalance()); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); } catch (InsufficientFundsException e) { System.out.println("\nInsufficient funds: $" + e.getAmount()); System.out.println("Balance $" + c.getBalance()); e.printStackTrace(); } } }
import java.io.*; public class SavingsAccount { private double balance; private int number; public SavingsAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } }
InsufficientFundsException.java
import java.io.*; public class InsufficientFundsException extends exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } }
Compile all the above three files, then run BankSample...
$ javac BankSample.java $ javac InsufficientFundsException.java $ javac SavingsAccount.java $ java BankSample Depositing $500... Balance $500.0 Withdrawing $100... Balance $400.0 Withdrawing $600... Insufficient funds: $200.0 Balance $400.0 InsufficientFundsException at SavingsAccount.withdraw(SavingsAccount.java:27) at BankSample.main(BankSample.java:18)
Inner Class
An inner class is a class within a class.
public class MyInnerClass { public static void main(String args[]) { // Instantiate the outer class Outer_Sample outer = new Outer_Sample(); // Access method inside inner class outer.display_Inner(); } } class Outer_Sample { int num; // inner class private class Inner_Sample { public void print() { System.out.println("Executing inner class"); } } void display_Inner() { Inner_Sample inner = new Inner_Sample(); inner.print(); } }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...public class InnerClassSample { public static void main(String args[]) { Outer_Sample outer = new Outer_Sample(); Outer_Sample.Inner_Sample inner = outer.new Inner_Sample(); System.out.println(inner.getNum()); } } class Outer_Sample { private int num = 175; public class Inner_Sample { public int getNum() { System.out.println("Executing getnum method of the inner class"); return num; } } }
Method-local Inner Class
For a class within a method, the scope of the inner class is restricted to be within the method.public static void main(String args[]) { Outerclass outer = new Outerclass(); outer.OuterClassMethod(); } public class Outerclass { void OuterClassMethod() { int num = 23; class MethodInner { public void print() { System.out.println("This is method inner class "+num); } } MethodInner inner = new MethodInner(); inner.print(); } }
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.
abstract class AnonInner { public abstract void mymethod(); } public class OuterClass { public static void main(String args[]) { AnonInner inner = new AnonInner() { public void mymethod() { System.out.println("Executing anonymous inner class"); } }; inner.mymethod(); } }A method can accept the object of an interface, an abstract class, or a concrete class.public class AnonInnerClass { public static void main(String args[]) { // Instantiate the class AnonInnerClass obj = new AnonInnerClass(); // Pass an anonymous inner class as an argument obj.displayMessage(new Message() { public String greet() { return "Hello"; } }); } // This method accepts the object of interface Message public void displayMessage(Message m) { System.out.println(m.greet() + ", executing anonymous inner class as an argument"); } } interface Message { String greet(); }
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.
public class OuterStatic { static class InnerClass public void my_method() { System.out.println("This is my nested class"); } } public static void main(String args[]) { OuterStatic.InnerClass = new OuterStatic.InnerClass nested.my_method(); } }
The "extends" keyword
Use the "extends" keyword to inherit the properties of a class.
public class MyCalc extends Calculation { public static void main(String args[]) { int a = 20, b = 10; MyCalc demo = new MyCalc(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); } public void multiplication(int x, int y) { z = x * y; System.out.println("The product of the given numbers:"+z); } } class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println("The sum of the given numbers:"+z); } public void Subtraction(int x, int y) { z = x - y; System.out.println("The difference between the given numbers:"+z); } }
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.
class SuperClass { int num = 20; public void display() { System.out.println("Display method of superclass"); } } public class SubClass extends SuperClass { int num = 10; public static void main(String args[]) { SubClass obj = new SubClass(); obj.my_method(); } public void display() { System.out.println("Inside the display method of subclass"); } public void my_method() { SubClass sub = new SubClass(); // Invoke the display() method of sub class sub.display(); // Invoke the display() method of superclass super.display(); System.out.println("Variable num in sub class: "+ sub.num); System.out.println("Variable num in super class: "+ super.num); } }When invoking a superclass version of an overridden method the super keyword is used.
public class SampleDog { public static void main(String args[]) { // Animal reference but Dog object Animal b = new Dog(); // Run the method in Dog class b.move(); } } class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { // Invoke the super class method super.move(); System.out.println("Dogs can walk and run"); } }
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.
public class CoSubClass extends Superclass { CoSubClass(int age) { super(age); } public static void main(String argd[]) { CoSubClass s = new CoSubClass(24); s.getAge(); } } class Superclass { int age; Superclass(int age) { this.age = age; } public void getAge() { System.out.println("Variable age in super class: " +age); } }
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.
class Animal { } class Mammal extends Animal { } class Reptile extends Animal { } public class MyDog extends Mammal { public static void main(String args[]) { Animal a = new Animal(); Mammal m = new Mammal(); MyDog d = new MyDog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal); } }Output...
$ java MyDog true true true
The implements keyword
Use the implements keyword inherit the properties of an interface.interface Animal{} class Mammal implements Animal{} public class IDog extends Mammal { public static void main(String args[]) { Mammal m = new Mammal(); IDog d = new IDog(); System.out.println(m instanceof Animal); System.out.println(d instanceof Mammal); System.out.println(d instanceof Animal);
Overriding
If a class inherits a method from its superclass, and if the method is not marked final, we can override the method.
public class SampleDog { public static void main(String args[]) { Animal a = new Animal(); Animal b = new Dog(); a.move(); b.move(); } } class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } }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...
class Animal { public void move() { System.out.println("Animals can move"); } } class Dog extends Animal { public void move() { System.out.println("Dogs can walk and run"); } public void bark() { System.out.println("Dogs can bark"); } } public class SampleDog { public static void main(String args[]) { Animal a = new Animal(); Animal b = new Dog(); a.move(); b.move(); b.bark(); } }This will produce the following result...
SampleDog.java:26: error: cannot find symbol b.bark(); ^ symbol: method bark() location: variable b of type Animal 1 errorThis program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.
Polymorphism
Objects that pass more than one is-a test are considered to be polymorphic.
A Reindeer is-a Animal A Reindeer is-a Vegetarian A Reindeer is-a Reindeer A Reindeer is-a ObjectIf not declared final, reference variables can be reassigned to other objects.
public interface Vegetarian{} public class Animal{} public class Reindeer extends Animal implements Vegetarian{} Reindeer d = new Reindeer(); Animal a = d; Vegetarian v = d; Object o = d;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./* File name: VirtualSample.java */ public class VirtualSample { public static void main(String [] args) { Stipend s = new Stipend("Carl Smith", "Columbus, OH", 3, 7600.00); Recipient e = new Stipend("John Adams", "Minot, ND", 2, 5400.00); System.out.println("Call mailCheck using Stipend reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Recipient reference--"); e.mailCheck(); } }
/* File name: Recipient.java */ public class Recipient { private String name; private String address; private int number; public Recipient(String name, String address, int number) { System.out.println("Constructing a Recipient"); this.name = name; this.address = address; this.number = number; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }
/* File name: Stipend.java */ public class Stipend extends Recipient { private double stipend; // Annual stipend public Stipend(String name, String address, int number, double stipend) { super(name, address, number); setStipend(stipend); } public void mailCheck() { System.out.println("Executing mailCheck method of Stipend class "); System.out.println("Mailing check to " + getName() + " with stipend " + stipend); } public double getStipend() { return stipend; } public void setStipend(double newStipend) { if(newStipend >= 0.0) { stipend = newStipend; } } public double computePay() { System.out.println("Computing stipend for " + getName()); return stipend; } }
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.
/* File name: MyStipend.java */ public class MyStipend { public static void main(String [] args) { Stipend s = new Stipend("Carl Smith", "Columbus, OH", 3, 7600.00); Recipient e = new Stipend("John Jones", "Minot, ND", 2, 5400.00); System.out.println("Call mailCheck using Stipend reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Recipient reference--"); e.mailCheck(); } }
/* File name: Recipient.java */ public abstract class Recipient { private String name; private String address; private int number; public Recipient(String name, String address, int number) { System.out.println("Creating a recipient"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Executing method computePay inside Recipient class"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }
/* File name: Stipend.java */ public class Stipend extends Recipient { // Annual stipend private double stipend; public Stipend(String name, String address, int number, double stipend) { super(name, address, number); setStipend(stipend); } public void mailCheck() { System.out.println("Within mailCheck of Stipend class "); System.out.println("Mailing check to " + getName() + " with stipend " + stipend); } public double getStipend() { return stipend; } public void setStipend(double newStipend) { if(newStipend >= 0.0) { stipend = newStipend; } } public double computeStipend() { System.out.println("Computing stipend for " + getName()); return stipend; } }
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.
public abstract class Recipient { private String name; private String address; private int number; public abstract double computePay(); // Remainder of class definition }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...
/* File name: Stipend.java */ public class Stipend extends Recipient { // Annual stipend private double stipend; public double computePay() { System.out.println("Computing stipend for " + getName()); return stipend; } // Remainder of class definition
Encapsulation
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...
- Declare the variables of a class as private.
- Provide public setter and getter methods to modify and view the variables values.
/* File name: RunEncap.java */ public class RunEncap { public static void main(String args[]) { EncapSample encap = new EncapSample(); encap.setName("Bobby"); encap.setAge(57); encap.setIdNum("1446"); System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()); } }
/* File name: EncapSample.java */ public class EncapSample { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } }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.
Interface
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.
/* File name: MyInterface.java */ import java.lang.*; public interface MyInterface { // Final, static fields // Abstract method declarations }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.
/* File name: Animal.java */ interface Animal { public void eat(); public void travel(); }
/* File name: Mammal.java */ public class Mammal implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { Mammal m = new Mammal(); m.eat(); m.travel(); } }
Extend Interfaces
An interface can extend another interface. The child interface inherits the methods of the parent interface.
// Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); }
// Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); }
// Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }
Multiple Inheritance for interfaces
Unlike a class, interfaces can extend more than one parent interface...
public interface Hockey extends Sports, Event
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...
package java.util; public interface EventListener {}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.
Package
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...
javac -d /path/to/folder file_name.java
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...
package animalia; /* File name: Animal.java */ interface Animal { public void eat(); public void travel(); }
package animalia; /* File name: Mammal.java */ public class Mammal implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { Mammal m = new Mammal(); m.eat(); m.travel(); } }Compile the java files into package animalia in the current directory...
$ javac -d . Animal.java $ javac -d . Mammal.java
Import
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...
package payroll; public class Manager { public void payEmployee(Employee e) { e.mailCheck(); } }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.
- The fully qualified name of the class...
payroll.EmployeeImport package can be imported using the import keyword and the wild card (*). For example... import payroll.*;The class itself can be imported using the import keyword. For example... import payroll.Employee;
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.
// File Name : Boat.java package vehicle; public class Boat { // Class implementation. }Now, put the source file in a directory whose name reflects the name of the package to which the class belongs...
..\vehicle\Boat.javaNow, the qualified class name and pathname would be as follows...
Class name → vehicle.Boat Path name → vehicle\Boat.java (in windows)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 − ..\com\ibm\computers\thinkpad.javaAt 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.javaThe files will be compiled as follows...
.\com\ibm\computers\thinkpad.class .\com\ibm\computers\Ups.classYou 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 −
<path-one>\sources\com\ibm\computers\thinkpad.java <path-two>\classes\com\ibm\computers\thinkpad.classBy 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