Вы находитесь на странице: 1из 99

1

Basics of Java Technology


this section provides an overview of Java technology as programming language and a platform. Java
technology is a simple, secure, robust, complete object oriented and platform independent high level
programming language. It is also portable, high performance, multithreaded and networks that enable it in
constructing software that can run along in small machines. The whole technology is based on the concept
of Java Virtual Machine (JVM) that acts as translators of byte code into machine language. In other words
JVM converts the java byte codes into platform specific machine language.

Understanding the Java Technology


Java technology is high-level, object-oriented, very robust programming language. Java is platform
independent programming language and you can run your compiled code on any operating system without
recompiling your source code. Java technology is based on the concept of a single Java virtual machine
(JVM) -- a translator between the language and the underlying software and hardware. All implementations
of the programming language must emulate the JVM, enabling Java programs to run on any system that has
a version of the JVM.

If you want to start java programming then you need to use a text editor to create and edit the source code.
By using the Java complier, you can change the source code into byte code. The byte code can be run on
any platform having Java interpreter that can convert the byte code into codes suitable for the operating
system.

Why Java Technology is so important?


This high-level powerful programming language provides a powerful software platform as the JVM
installed on different platform understand the same byte code. This is ideal for server side web
programming and runs in a secured manner over internet. It enhance the computing power of the users by
taking merely from desktop to the resource of the web. It contains JVM and Java Application Programming
Interface (API) that are kinds of readymade software components, and for using any component, the need is
just to import a related package in your program use the functionality. It offers development tools that can
be used in compiling, running, debugging and documenting the application, making the Java programming
fun and easy. The automatic garbage collection mechanism helps in avoiding memory leaks and its coding
takes less development time than other programming languages like C++.

Different Editions of Java Technology

a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can use to create server
applications, desktop applications, and even applets. These programs developed using Java SE can be run
on almost every popular operating system, including Linux, Macintosh, Solaris, and Windows.

b) JEE - Based on the foundation framework of the standard edition, Java Enterprise Edition helps in
web application service, component model and enterprise class service oriented architecture (SOA).

c) JME - Java Micro Edition or JME for short is an accumulation of Java APIs that are used for the
development of software for devices like mobile phones, PDAs, TV set-top boxes, game programming. The
platform of micro edition generally consists of an easy user interface, a robust security model and a wide
variety of built-in networks for running Java based application.

Components of each edition

JSE Components

JavaBeans - It is the component architecture for J2SE platform and one can develop and assemble these
software programs for better web application. It is a reusable software component that can be manipulated
2

visually in a builder tool. This software assists visual builder tools in using reflection, introspection, and
also analyzes and customizes JavaBeans.

Java Foundation Classes (JFC) - It is a part of Java class libraries based on the Java platform used
for developing graphical user interface (GUI). JFC helps in 2D graphics, imaging, text formatting and
printing with the help of Abstract Window Toolkit (AWT), Swing and Java2D. With the help of input
method framework, the JFC technology assists in preparing application that can be accessible to all users
around the world in different languages. Drag and Drop is another feature of JFC that supports data
transfers between different Java applications.

JavaHelp - It is a platform independent and a feature oriented software system that offers developer an
automated help component. JavaHelp 2.0 API is useful while building online documentation and presenting
online information to the application users.

Java Web Start - It is framework in the Java platform that assists in starting Application software
directly from the internet by using a web browser. As we know Java applet can run in a browser but in case
of Java Web Start, it doesn't run inside and solve many complex problems associated with Java plugins and
JVM. It also provides many classes that in turn provide various services and allow better access to
resources. Version 1.0 was introduced in the year 2001. Now with the release of J2SE 1.4, Java Web Start is
included with Java Runtime Environment and does need any separate installation.

Java Database Connectivity (JDBC) - JDBC API is a part of Java Standard Edition that helps in
accessing data from a SQL based database. Besides, it also processes the result and allows in using the
programming language with "Write Once, Run Anywhere" feature. Some of its key features are like full
access to metadata, no special installation and database identification.

Java Media Framework (JMF) - It’s an advanced API that allows Java developers to process and
add audio-video source to Java application and applets. It is useful for multimedia developers to capture,
playback, transcode different media formats.

JEE - Components:

Enterprise JavaBeans (EJB) - This technology is a server side component of Java platform used for
the construction of enterprise application. It is one of the Java APIs attached with the enterprise edition. By
using Java technology, EJB helps in quick development of small, distributed, transactional and secure
application.

JavaMail - This JavaMail API technology allows to build mails and messaging application in a platform
independent and protocol independent framework. It is both a part of JSE and JEE platform. Thus,
JavaMail uses an extensible platform for transferring all kinds of Multimedia Internet Mail Extension
(MIME).

Java Message Service (JMS) - Developed under Java community process, JMS technology is used
for sending messages between users. Basically, it is an enterprising messaging tool used for building
enterprising application. The JMS API is a combination of Java technology and enterprising messaging that
provides facilities for building small message based application. It functions under two models: Point-to-
Point and Publishing & Subscribing model.

Java Server Pages (JSP) - The JSP technology enables web developers in developing and
maintaining web content pages in formats like HTML and XML. With the help of JSP, it becomes very easy
to build server and platform independent web based application. This uses HTML and XML tags that offers
3

logical solution for the content. This separately user interface and content development from each other,
which allows the designer to change page layout without changing the content.

Java Servlets - This enables a developer in adding content to a web server by using Java platform. This
provides the mechanism for enhancing the functionality of web server. In short, servlets provides platform
independent and component based web based application without the performance limiting of CGI
program.

JME - Components:
Connected Limited Device Configuration (CLDC) - It is one of the configurations of Java
Micro Edition. 'Configuration' describes minimal features of a complete Java. The CLDC specifies the
capabilities of JVM, the base set of API for resource limited devices like pager and mobile phones. There
are two version of CLDC: version 1.0 was released in 2000 and came to be known as Java Specification
Request (JSR)30. Later version 1.1 or JSR 139 but 1.0 is more widely used. The Connected Limited Device
Configuration and the Mobile Information Device Profile (MIDP) together provides solid Java platform for
developing application to run on less processing power devices.

Mobile Information Device Profile (MIDP) - This is another configuration of Java Micro Edition
and coupled with CLDC, it provides a farm Java Runtime Environment for various mobile devices and
other personal digital assistance (PDA). With the help of MIDP, developers can develop application once
and then redistribute them into various mobile information devices in a very small period of time. Its
principal functions include the user interface, network connectivity data storage and overall application
process management. There are two versions of MIDP: one is MIDP 2.0 or JSR 118 and the second one is
the MIDP 1.0 or JSR 37.

Connected Device Configuration (CDC) - Developed under the Java Community Process (JCP), it
is a standard framework of Java technology used for building and delivering application that can be shared
in a wide range of networks and devices ranging from pagers, mobile phones, set top box and other PDA
devices. It is in two versions: the JSR 36 (CDC 1.0) and the latest one is the JSR 218 (CDC 1.1).

What should be my learning path:

a.Learn Core Java - The Core Java Technology is the foundation of Java Platform of JSE. It is
used in all classes of Java programming from desktop to Java Enterprise Edition. This include Java
APIs, Java Application, JVM, JavaBeans, JavaScript, JSP etc.

a.Learn JSP - JSP technology assists developers in generating HTML, XML web pages. It uses
Java code and some predefined actions while creating web content. This helps in the creation of JSP
tag libraries that acts as extensions to HTML and XML tags.

b.Learn Servlets - In a Java Platform, Servlets assists developers in adding content to a web server.
Servlets with Java server pages acts as a competitor to various dynamic web content technologies like CGI,
ASP.NET, JavaScript etc.

c.Learn about Tomcat and other servers - Developed by Apache Software Foundation Tomcat is a
Java based web application server used to run Servlet and JSP. It is not merely limited to application server
and provides an open platform to develop extensible web and content management service.

d.Learn Open Source technologies (Struts, Hibernate, Spring) - Basically in Java there are
three open source technologies known as frameworks; these are Spring, Hibernate and Struts. These open
4

source application frameworks solves many problems related to JSE and J2EE, and helps in effective
development of web application.

e.Learn EJB - Enterprise Java Beans are a part of J2EE and also a server sided component used mostly
in large projects. It helps in easy and rapid development of distributed, transactional and small application
based on Java technology.

f.Learn about Database Management System - It is software designed to manage and run a
database. Generally, it is used in company back office work, accounting, customer support system and
several other purposes.
__________________________________________________________________

Introduction to Java
Basic Language Elements
(Identifiers, keywords, literals, white spaces and comments)
Keywords

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

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

abstract default if private this


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

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

/** This class is a Hello World Program used to introduce the Java Language*/
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World"); //Prints output to console
}
}

For more information on different Keywords - Java Keywords


5

Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related
to the C programming language. const and goto are Java keywords. The word finalize is the name of a
method of the Object class and hence not a keyword. enum and label are not keywords.

Comments

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

Java supports three comment styles.

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

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

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

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

Variable, Identifiers and Data Types

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

public class localVariableEx


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

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

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

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

• Integer: byte, short, int, and long.


• Floating Point: float and double
6

• Character: char
• Boolean: variable with a value of true or false.

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

Data Type Default Value (for fields) Range


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

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

For Example

String message = "hello world"

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

Identifier Naming Rules

• Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ )
character.
• Must begin with a letter, dollar sign, or an underscore
• Are case sensitive
• Keywords cannot be used as identifiers
• Within a given section of your program or scope, each user defined item must have a unique
identifier
• Can be of any length.

Classes

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

Objects
7

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

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

Interface

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

Instance Members

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

Static Members

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

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

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

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

public String printMessage()


{
return output;
}

public static void main (String args[])


{
helloObj = new HelloWorld(); //Line 2
System.out.println(helloObj.printMessage());
}
8

Class Name: HelloWorld


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

Arrays

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

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

public class ArrayExample


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

Output

0, 0, 0.0, null

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

Below is a program showing the working of Java Arrays

import java.util.Arrays;
public class ArrayExample {
// Array Declaration Examples
public static void arrayDeclarationExample() {
System.out.println("Array Declaration Example");
System.out.println();
// We can first declare the reference and then create the array
int[] array1; //or int Array1[];
9

array1 = new int[10];


// Or we can do delaration and creating memory for the Array in one step
int[] array2 = new int[24];
// We can create an array declare, initialize in one step as shown with 7 Strings
String[] array3 = {"beginner", "-", "java", "-", "tutorial",".", "com"};
// We can create an array of objects as shown
Double[] array4 = {new Double(100),new Double(200), new Double(300),
new Double(400)};

String[] array5 = new String[5];


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

System.out.println("Array5 Elements : 5");


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

/* Cloning an array will create a new array of the same size and type
and copying all the old elements into the new array. In the case of primitive elements,
the new array has copies of the old elements, so changes to the elements of one are
not reflected in the copy.

Java arrays do not override the Object.equals() method, which returns true only if the
argument is the same object. The java.util.Arrays utility class provides functions for
element-by-element equality testing and hash value.
*/
public static void copyCloneArrayExample() {

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

String[] copiedArray1 = new String[array1.length];


System.arraycopy(array1, 0, copiedArray1, 0, array1.length);

String[] clonedArray1 = (String[])array1.clone();


10

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

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

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

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

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

public static void useOfArraysClass() {

System.out.println();

String[] array1 = new String[5];


String[] array2 = new String[5];

//Use of Arrays.fill() Method


Arrays.fill(array1, "*");
Arrays.fill(array2, "-");

//Use of Arrays.equals() Method


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

// Use of Arrays.sort() method


11

int[] array3 = new int[10];


for (int i = 0; i < array3.length; i++) {
array3[i] = (int)(Math.random()*2 );
}

System.out.println(" Original Array3 -> ");


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

System.out.println(" Sorted Array3 -> ");


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

// Use of Arrays.binarySearch() method to search for an element in the Array


int index = Arrays.binarySearch(array3, 5);
if (index < 0) {
System.out.println("Could not locate the number 5.");
} else {
System.out.println("Found the number 5 at location: " + index);
}
System.out.println();
System.out.println("-----------------------------------------------");

public static void main(String[] args) {

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

Output

Array Declaration Example

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

Copying and Cloning of Arrays


12

Original Array: Array1 ->


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

originalArray3 == copiedArray3 : false


originalArray3.equals(copiedArray3) : false
Arrays.equals(originalArray3, copiedArray3) : true
originalArray3 == clonedArray3 : false
originalArray3.equals(clonedArray3) : false
Arrays.equals(originalArray3, clonedArray3) : true
-----------------------------------------------
Array1 Not Equal Array2

Original Array3 ->


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

Java Operators tutorial

Java Operators

They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or
ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear before
(prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its
arguments.

Java Operators fall into 8 different categories:

Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise,
compound assignment, conditional, and type.

Assignment Operators =

Arithmetic Operators - + * / % ++ --
Relational Operators > < >= <= == !=
Logical Operators && || & | ! ^
Bit wise Operator & | ^ << >> >>>
Compound Assignment Operators += -= *= /= %= <<=
>>= >>>=
Conditional Operator ?:
Type Operator (type) instanceof new

Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound
assignment, conditional, and type.

Assignment operators
13

The java assignment operator statement has the following syntax:

<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

public class AssignmentOperatorsDemo {


public AssignmentOperatorsDemo( ) {

// Assigning Primitive Values


int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is
overwritten.
k = j; // k gets the value 5.
System.out.println("j is : "+j);
System.out.println("k is : "+k);

// Assigning References
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
System.out.println("i1 is : "+i1);
System.out.println("i2 is : "+i2);
i1 = i2;
System.out.println("i1 is : "+i1);
System.out.println("i2 is : "+i2);

// Multiple Assignments
k = j = 10; // (k = (j = 10))
System.out.println("j is : "+j);
System.out.println("k is : "+k);

}
public static void main(String args[]){
new AssignmentOperatorsDemo();
}
}

Arithmetic operators

Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division,
modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program
is shown below that demonstrates the different arithmetic operators in java.

The binary operator + is overloaded in the sense that the operation performed is determined by the type
of the operands. When one of the operands is a String object, the other operand is implicitly converted to
its string representation and string concatenation is performed.

String message = 100 + "Messages"; //"100 Messages"

public class ArithmeticOperatorsDemo {


public ArithmeticOperatorsDemo( ) {
int x, y = 10, z = 5;
14

x = y + z;
System.out.println("+ operator resulted in "+x);
x = y - z;
System.out.println("- operator resulted in "+x);
x = y * z;
System.out.println("* operator resulted in "+x);
x = y / z;
System.out.println("/ operator resulted in "+x);
x = y % z;
System.out.println("% operator resulted in "+x);
x = y++;
System.out.println("Postfix ++ operator resulted in "+x);
x = ++z;
System.out.println("Prefix ++ operator resulted in "+x);
x = -y;
System.out.println("Unary operator resulted in "+x);

// Some examples of special Cases

int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is


Integer.MIN_VALUE.
int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is
Integer.MAX_VALUE.

System.out.println("tooBig becomes "+tooBig);


System.out.println("tooSmall becomes "+tooSmall);

System.out.println( 4.0 / 0.0); // Prints: Infinity


System.out.println(-4.0 / 0.0); // Prints:
-Infinity
System.out.println(0.0 / 0.0); // Prints: NaN

double d1 = 12 / 8; // result: 1 by integer division. d1 gets


the value 1.0.
double d2 = 12.0F / 8; // result: 1.5

System.out.println("d1 is "+d1);
System.out.println("d2 iss "+d2);

public static void main(String args[]){


new ArithmeticOperatorsDemo();
}
}

Relational operators

Relational operators in Java are used to compare 2 or more objects. Java provides six relational
operators: greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and
not equal (!=). All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a
boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that
of the assignment operators. An example program is shown below that demonstrates the different relational
operators in java.
15

public class RelationalOperatorsDemo {


public RelationalOperatorsDemo( ) {
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >= y));
System.out.println("x <= y : "+(x <= y));
System.out.println("x == y : "+(x == y));
System.out.println("x != y : "+(x != y));
}
public static void main(String args[]){
new RelationalOperatorsDemo();
}
}

Logical operators

Logical operators return a true or false value based on the state of the Variables. There are six logical, or
boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each
argument to a logical operator must be a boolean data type, and the result is always a boolean data type. An
example program is shown below that demonstrates the different Logical operators in java.

public class LogicalOperatorsDemo {


public LogicalOperatorsDemo( ) {
boolean x = true;
boolean y = false;
System.out.println("x & y : "+(x & y));
System.out.println("x && y : "+(x && y));
System.out.println("x | y : "+(x | y));
System.out.println("x || y: "+(x || y));
System.out.println("x ^ y : "+(x ^ y));
System.out.println("!x : "+(!x));
}
public static void main(String args[]){
new LogicalOperatorsDemo();
}
}

Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table
below.

x y !x x & y x | y x ^ y

x && y x || y

true true false true true false

true false false false true true

false true true false true true


16

false false true false false false

Bitwise operators

Java provides Bit wise operators to manipulate the contents of variables at the bit level. These variables
must be of numeric data type ( char, short, int, or long). Java provides seven bitwise operators. They are
AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An
example program is shown below that demonstrates the different Bit wise operators in java.

public class BitwiseOperatorsDemo {

public BitwiseOperatorsDemo( ) {
int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1
int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int z;
System.out.println("x & y : "+(x & y));
System.out.println("x | y : "+(x | y));
System.out.println("x ^ y : "+(x ^ y));
System.out.println("~x : "+(~x));
System.out.println("x << y : "+(x << y));
System.out.println("x >> y : "+(x >> y));
System.out.println("x >>> y : "+(x >>> y));
//There is no unsigned left shift operator
}
public static void main(String args[]){
new BitwiseOperatorsDemo();
}
}

The result of applying bitwise operators between two corresponding bits in the operands is shown in the
Table below.

A B ~A A & B A | B A ^ B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

/*
* The below program demonstrates bitwise operators keeping in mind
operator precedence
17

* Operator Precedence starting with the highest is -> |, ^, &


*/
public class BitwisePrecedenceEx {
public static void main (String[] args) {
int a = 1 | 2 ^ 3 & 5;
int b = ((1 | 2) ^ 3) & 5;
int c = 1 | (2 ^ (3 & 5));
System.out.print(a + "," + b + "," + c);
}
}
Output
3,0,3

Compound operators

The compound operators perform shortcuts in common programming operations. Java has eleven
compound assignment operators.
Syntax:

argument1 operator = argument2.

The above statement is the same as, argument1 = argument1 operator argument2. An example program is
shown below that demonstrates the different Compound operators in java.

public class CompoundOperatorsDemo {


public CompoundOperatorsDemo() {
int x = 0, y = 5;
x += 3;
System.out.println("x : "+x);
y *= x;
System.out.println("y : "+y);

/*Similarly other operators can be applied as shortcuts. Other


compound assignment operators include boolean logical
, bitwiseand shift operators*/
}
public static void main(String args[]){
new CompoundOperatorsDemo();
}
}

Conditional operators

The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The
operator evaluates the first argument and, if true, evaluates the second argument. If the first argument
evaluates to false, then the third argument is evaluated. The conditional operator is the expression
equivalent of the if-else statement. The conditional expression can be nested and the conditional
operator associates from right to left:

(a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

An example program is shown below that demonstrates the Ternary operator in java.
18

public class TernaryOperatorsDemo {


public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : "+z);
}
public static void main(String args[]){
new TernaryOperatorsDemo();
}
}

/*
* The following programs shows that when no explicit parenthesis is
used then the conditional operator
* evaluation is from right to left
*/

public class BooleanEx1 {


static String m1(boolean b){return b?"T":"F";}
public static void main(String [] args) {
boolean t1 = false?false:true?false:true?false:true;
boolean t2 = false?false:(true?false:(true?false:true));
boolean t3 = ((false?false:true)?false:true)?false:true;
System.out.println(m1(t1) + m1(t2) + m1(t3));
}
}

Output

FFT

Type conversion allows a value to be changed from one primitive data type to another. Conversion can
occur explicitly, as specified in the program, or implicitly, by Java itself. Java allows both type widening
and type narrowing conversions.

In java Conversions can occur by the following ways:

• Using a cast operator (explicit promotion)


• Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
• A value of one type is assigned to a variable of a different type (assignment promotion)

Operator Precedence

The order in which operators are applied is known as precedence. Operators with a higher precedence
are applied before operators with a lower precedence. The operator precedence order of Java is shown
below. Operators at the top of the table are applied before operators lower down in the table. If two
operators have the same precedence, they are applied in the order they appear in a statement. That is, from
left to right. You can use parentheses to override the default precedence.

postfix [] . () expr++ expr--


unary ++expr --expr +expr -expr ! ~
creation/caste new (type)expr
multiplicative */%
19

additive +-
shift << >> >>>
relational < <= > >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = "op="

Example

In an operation such as,

result = 4 + 5 * 3

First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that '*' takes
higher precedence than '+' according to chart shown above. This kind of precedence of one operator over
another applies to all the operators.
_______________________________________________________________________
_

Java Control Statements

Introduction to Control Statements

Control statements control the order of execution in a java program, based on data values and conditional
logic. There are three main categories of control flow statements;

• Selection statements: if, if-else and switch.

• Loop statements: while, do-while and for.

• Transfer statements: break, continue, return, try-catch-finally and assert.

We use control statements when we want to change the default sequential order of execution

Selection Statements

The If Statement

The if statement is a control statement that executes a block of code only if the specified expression is
true. If the value is false, then the if block is skipped and execution continues with the rest of the
program. You can either have a single statement or a block of code within an if statement. Note that the
conditional expression must be a Boolean expression.
20

The simple if statement has the following syntax:

if (<conditional expression>)
<statement action>

Below is an example that demonstrates conditional execution based on if statement condition.

public class IfStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20;
if(a > b)
System.out.println("a > b");
if(a < b)
System.out.println("b > a");
}

Output

b > a

The If-else Statement

The if/else statement is an extension of the if statement. If the statements in the if statement fails, the
statements in the else block are executed. You can either have a single statement or a block of code within
if-else blocks. Note that the conditional expression must be a Boolean expression.

The if-else statement has the following syntax:

if (<conditional expression>)
<statement action>
else
<statement action>

Below is an example that demonstrates conditional execution based on if else statement


condition.
public class IfElseStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20;
if(a > b){
System.out.println("a > b");
}else{
System.out.println("b > a");
}
}
}

Output

b>a
21

We can also have nested if-else statements. If none of the conditions are true, the block associated with
the last else clause is executed. If there is no last else clause, no actions are performed.

Below is an example that demonstrates conditional execution based on nested if else statement condition
to find the greatest of 3 numbers.

public class IfElseIfStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20, c = 30;
if(a > b && a > c){
System.out.println("a is the greatest");
}else if(b > c){
System.out.println("b is the greatest");
}else{
System.out.println("c is the greatest");
}
}
}

Output

b>a

Switch Statement

The switch statement, also called a case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements. The switch statement begins with a keyword,
followed by an expression that equates to a no long integral value. Following the controlling expression is a
code block that contains zero or more labeled cases. Each label must equate to an integer constant and each
must be unique. When the switch statement executes, it compares the value of the controlling expression to
the values of each case label. The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code block. If none of the case label
values match, then none of the codes within the switch statement code block will be executed. Java
includes a default label to use in cases where there are no matches. We can have a nested switch within a
case block of an outer switch.

Its general form is as follows:

switch (<non-long integral expression>) {


case label1: <statement1>
case label2: <statement2>
...
case labeln: <statementn>
default: <statement>
} // end switch

When executing a switch statement, the program falls through to the next case. Therefore, if you want to
exit in the middle of the switch statement code block, you must insert a break statement, which causes the
program to continue executing after the current code block.

Below is an example that demonstrates conditional execution using switch case statements.
22

public class SwitchCaseStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20, c = 30;
int status = -1;
if(a > b && a > c){
status = 1;
}else if(b > c){
status = 2;
}else{
status = 3;
}

switch(status){
case 1: System.out.println("a is the greatest");
break;
case 2: System.out.println("b is the greatest");
break;
case 3: System.out.println("c is the greatest");
break;
default: System.out.println("Cannot be determined");

}
}
}

Output

c is the greatest
______________________________________________________________________________________
Introduction to Access Modifiers

Introduction to Java Access Modifiers

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class
can control what information or data can be accessible by other classes using access modifiers. To take
advantage of encapsulation, you should minimize access whenever possible.

Java provides a number of access modifiers to help you set the level of access you want for classes as
well as the fields, methods and constructors in your classes. There are three specified and one default level
of access. A member has package or default accessibility when no accessibility modifier is specified

Access Modifiers

1. private
2. protected
3. default
4. public

public access modifier

Fields, methods and constructors declared public (least restrictive) within a public class are visible to any
class in the Java program, whether these classes are in the same package or in another package.
23

private access modifier

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot
be used for fields and methods within an interface. Fields, methods or constructors declared private are
strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A
standard design strategy is to make all fields private and provide public getter methods for them.

protected access modifier

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields
and methods within an interface. Fields, methods and constructors declared protected in a superclass can be
accessed only by subclasses in other packages. Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not a subclass of the protected member's class.

default access modifier

Java provides a default access which is used when no access modifier is present. Any class, field,
method or constructor that has no declared access modifier is accessible only by classes in the same
package. The default modifier is not used for fields and methods within an interface.

Below is a program to demonstrate the use of public, private, protected and default access
modifiers while accessing fields and methods. There are in total 3 classes created to explain the access
modifiers. The output of each of these java files depict the Java access modifiers.

The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file
contains the Base class and a subclass within the enclosing class that belongs to the same class as shown
below.

package pckage1;

class BaseClass {
public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier

public int getX() {


return x;
}
public void setX(int x) {
this.x = x;
}

private int getY() {


return y;
}

private void setY(int y) {


this.y = y;
}
protected int getZ() {
return z;
}
24

protected void setZ(int z) {


this.z = z;
}

int getA() {
return a;
}
void setA(int a) {
this.a = a;
}
}

public class SubclassInSamePackage extends BaseClass {


public static void main(String args[]){
BaseClass rr = new BaseClass();
rr.z = 0;
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : "+subClassObj.x);
subClassObj.setX(20);
System.out.println("Value of x is : "+subClassObj.x);

//Access Modifiers - Private


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private

/* System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/

//Access Modifiers - Protected


System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);

//Access Modifiers - Default


System.out.println("Value of x is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : "+subClassObj.a);

}
}

Output

Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20
25

The second class is SubClassInDifferentPackage.java which is present


in a different package then the first one. This java class extends
First class (SubclassInSamePackage.java).
import pckage1.*;
public class SubClassInDifferentPackage extends SubclassInSamePackage {

public int getZZZ(){


return z;
}

public static void main(String args[]){


SubClassInDifferentPackage subClassDiffObj = new
SubClassInDifferentPackage();
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : "+subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : "+subClassObj.x);

//Access Modifiers - Private


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private

/* System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/

//Access Modifiers - Protected


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.

/* System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/
System.out.println("Value of z is : "+subClassDiffObj.getZZZ());

//Access Modifiers - Default


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.
/*
System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/

}
}
Output

Value of x is : 10
Value of x is : 30
Value of z is : 10

The third class is ClassInDifferentPackage.java which is present in a


different package then the first one.
import pckage1.*;
26

public class ClassInDifferentPackage {


public static void main(String args[]){
SubclassInSamePackage subClassObj = new SubclassInSamePackage();
//Access Modifiers - Public
System.out.println("Value of x is : "+subClassObj.x);
subClassObj.setX(30);
System.out.println("Value of x is : "+subClassObj.x);

//Access Modifiers - Private


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are private

/* System.out.println("Value of y is : "+subClassObj.y);
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/

//Access Modifiers - Protected


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.

/* System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/

//Access Modifiers - Default


// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.

/* System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/

}
}

Output

Value of x is : 10
Value of x is : 30
______________________________________________________________________________________
Java Classes and Objects

Introduction to Java Classes

A class is nothing but a blueprint or a template for creating different objects which defines its properties
and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain
fields and methods to describe the behavior of an object. Methods are nothing but members of a class that
provide a service for an object or perform some business logic. Java fields and member functions names
are case sensitive. Current states of a class's corresponding object are stored in the object's instance
variables. Methods define the operations that can be performed on the object.

A class has the following general syntax:


27

<class modifiers> class <class name>


<extends clause> <implements clause>{

// Class body
<field declarations (Static and Non-Static)>
<method declarations (Static and Non-Static)>
<Inner class declarations>
<nested interface declarations>
<constructor declarations>
<Static initializer blocks>
}

Below is an example showing the Cube class that defines 3 fields


namely length, breadth and height. Also the class contains a member
function getVolume().

public class Cube {


int length;
int breadth;
int height;
public int getVolume( ) {
return ( length * breadth * height );
}
}

How do you reference a data member/function

This is accomplished by stating the name of the object reference, followed by a period (dot), followed by
the name of the member inside the object. ( objectReference.member ). You call a method for an object by
naming the object followed by a period (dot), followed by the name of the method and its argument list,
like this: objectName.methodName(arg1, arg2, arg3).

For example:

cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()

Class Variables – Static Fields

We use class variables also know as Static fields when we want to share characteristics across all
objects within a class. When you declare a field to be static, only a single instance of the associated variable
is created common to all the objects of that class. Hence when one object changes the value of a class
variable, it affects all objects of the class. We can access a class variable by using the name of the class, and
not necessarily using a reference to an individual object within the class. Static variables can be accessed
even though no objects of that class exist. It is declared using static keyword

Class Methods – Static Methods

Class methods, similar to Class variables can be invoked without having an instance of the class. Class
methods are often used to provide global functions for Java programs. For example, methods in the
java.lang.Math package are class methods. You cannot call non-static methods from inside a static
method
28

Instance Variables

Instance variables stores the state of the object. Each class would have its own copy of the variable.
Every object has a state that is determined by the values stored in the object. An object is said to have
changed its state when one or more data values stored in the object have been modified. When an object
responds to a message, it will usually perform an action, change its state etc. An object that has the ability
to store values is often said to have persistence.

Consider this simple Java program showing the use of static fields and static methods.

class Cube {
int length = 10;
int breadth = 10;
int height = 10;
public static int numOfCubes = 0; // static variable

public static int getNoOfCubes( ) {//static method


return numOfCubes;
}

public Cube() {
numOfCubes++; //
}
}

public class CubeStaticTest {


public static void main (String args[]) {

System.out.println("Number of Cube objects = " + Cube.numOfCubes);


System.out.println("Number of Cube objects = " +
Cube.getNoOfCubes());

}
}

Output

Number of Cube objects = 0


Number of Cube objects = 0

Final Variable, Methods and Classes


In Java we can mark fields, methods and classes as final. Once marked as final, these items cannot be
changed.

Variables defined in an interface are implicitly final. You can't change value of a final variable (is a
constant). A final class can't be extended i.e., final class may not be subclassed. This is done for security
reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations,
and makes thread safety a little easier to achieve. A final method can't be overridden when its class is
inherited. Any attempt to override or hide a final method will result in a compiler error.

Introduction to Java Objects


29

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

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

Creating variables of your class type is similar to creating variables of primitive data types, such as integer
or float. Each time you create an object, a new set of instance variables comes into existence which defines
the characteristics of that object. If you want to create an object of the class and have the reference variable
associated with this object, you must also allocate memory for the object by using the new operator. This
process is called instantiating an object or creating an object instance.

When you create a new object, you use the new operator to instantiate the object. The new operator
returns the location of the object which you assign to a reference type.

Below is an example showing the creation of Cube objects by using the new operator.

public class Cube {


int length = 10;
int breadth = 10;
int height = 10;
public int getVolume( ) {
return ( length * breadth * height );
}

public static void main(String[] args) {


Cube cubeObj; //Creates a Cube Reference
cubeObj = new Cube(); //Creates an Object of Cube
System.out.println("Volume of Cube is :
"+cubeObj.getVolume());
}
}

Method Overloading

Method overloading results when two or more methods in the same class have the same name but
different parameters. Methods with the same name must differ in their types or number of parameters. This
allows the compiler to match parameters and choose the correct method when a number of choices exist.
Changing just the return type is not enough to overload a method, and will be a compile-time error. They
must have a different signature.

When no method matching the input parameters is found, the compiler attempts to convert the input
parameters to types of greater precision. A match may then be found without error. At compile time, the
right implementation is chosen based on the signature of the method call

Below is an example of a class demonstrating Method Overloading

public class MethodOverloadDemo {

void sumOfParams() { // First Version


System.out.println("No parameters");
}
30

void sumOfParams(int a) { // Second Version


System.out.println("One parameter: " + a);
}
int sumOfParams(int a, int b) { // Third Version
System.out.println("Two parameters: " + a + " , " + b);
return a + b;
}
double sumOfParams( double a, double b) { // Fourth Version
System.out.println("Two double parameters: " + a + " , "
+ b);
return a + b;
}

public static void main(String args[]) {


MethodOverloadDemo moDemo = new MethodOverloadDemo();
int intResult;
double doubleResult;
moDemo.sumOfParams();
System.out.println();
moDemo.sumOfParams(2);
System.out.println();
intResult = moDemo.sumOfParams(10, 20);
System.out.println("Sum is " + intResult);
System.out.println();
doubleResult = moDemo.sumOfParams(1.1, 2.2);
System.out.println("Sum is " + doubleResult);
System.out.println();
}
}

Output

No parameters

One parameter: 2

Two parameters: 10 , 20
Sum is 30

Two double parameters: 1.1 , 2.2


Sum is 3.3000000000000003

Below is a code snippet to shows the interfaces that a Class Implements:

Class cls = java.lang.String.class;


Class[] intfs = cls.getInterfaces();
// [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable]

// The interfaces for a primitive type is an empty array


cls = int.class;
intfs = cls.getInterfaces(); // []

Below is a code snippet to show whether a Class Object Represents a Class or Interface:
31

Class cls = java.lang.String.class;


boolean isClass = !cls.isInterface(); // true

cls = java.lang.Cloneable.class;

isClass = !cls.isInterface(); // false


_______________________________________________________________________
Java Constructors

A constructor has the same name as the name of the class to which it belongs. Constructor's syntax
does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new
operator, the types must match those that are specified in the constructor definition. Java provides a default
constructor which takes no arguments and performs no special actions or initializations, when no explicit
constructors are provided. The only action taken by the implicit default constructor is to call the superclass
constructor using the super() call. Constructor arguments provide you with a way to provide parameters for
the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized
constructor).

public class Cube1 {


int length ;
int breadth ;
int height ;
public int getVolume( ) {
return ( length * breadth * height );
}

Cube1(){
length = 10;
breadth = 10;
height = 10;
}

Cube1(int l, int b, int h){


length = l;
breadth = b;
height = h;
}

public static void main(String[] args) {


Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);

System.out.println("Volume of Cube1 is :
"+cubeObj1.getVolume());
System.out.println("Volume of Cube2 is :
"+cubeObj2.getVolume());
}
}
32

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the
objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to
call the default constructor will be a compile time error if an explicit default constructor is not provided in
such a case.

Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the
same name as the class, their signatures are differentiated by their parameter lists. The above example
shows that the Cube1 constructor is overloaded one being the default constructor and the other being a
parameterized constructor.

It is possible to use this() construct, to implement local chaining of constructors in a java class. The
this() call in a constructor invokes the an other constructor with the corresponding parameter list within the
same class. Calling the default constructor to create a Cube object results in the second and third
parameterized constructors being called as well. Java requires that any this() call must occur as the first
statement in a constructor.

Below is an example of a cube class containing 3 constructors which demostrates the this() method in
Constructors context

public class Cube2 {


int length ;
int breadth ;
int height ;
public int getVolume( ) {
return ( length * breadth * height );
}

Cube2(){
this(10, 10);
System.out.println("Finished with Default Constructor");
}

Cube2(int l, int b){


this(l, b, 10);
System.out.println("Finished with Parameterized Constructor
having 2 params");
}

Cube2(int l, int b, int h){


length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor
having 3 params");
}

public static void main(String[] args) {


Cube2 cubeObj1, cubeObj2;
cubeObj1 = new Cube2();
cubeObj2 = new Cube2(10, 20, 30);
33

System.out.println("Volume of Cube1 is :
"+cubeObj1.getVolume());
System.out.println("Volume of Cube2 is :
"+cubeObj2.getVolume());
}
}

Output

Finished with Parameterized Constructor having 3 params


Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

Constructor Chaining

Java ensures that every constructor calls its superclass constructor. An implied super() is therefore
included in each constructor which does not include either the this() function or an explicit super() call as
its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first
statement of the constructor. The explicit super allows parameter values to be passed to the constructor of
its superclass and must have matching parameter types A super() call in the constructor of a subclass will
result in the call of the relevant constructor from the superclass, based on the signature of the call. This is
called constructor chaining.

Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {
int length ;
int breadth ;
int height ;
public int getVolume( ) {
return ( length * breadth * height );
}

Cube(){
this(10, 10);
System.out.println("Finished with Default Constructor of Cube");
}

Cube(int l, int b){


this(l, b, 10);
System.out.println("Finished with Parameterized Constructor
having 2 params of Cube");
}

Cube(int l, int b, int h){


length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor
having 3 params of Cube");
}
34

public class SpecialCube extends Cube{


int weight ;

SpecialCube(){
super();
weight = 10;
}

SpecialCube(int l, int b){


this(l, b, 10);
System.out.println("Finished with Parameterized Constructor
having 2 params of SpecialCube");
}

SpecialCube(int l, int b, int h){


super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor
having 3 params of SpecialCube");
}

public static void main(String[] args) {


SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1 is :
"+specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is :
"+specialObj1.weight);

System.out.println("Volume of SpecialCube2 is :
"+specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is :
"+specialObj2.weight);
}

Output

Finished with Parameterized Constructor having 3 params of SpecialCube


Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20

The super() construct as with this() construct: if used, must occur as the first statement in a constructor,
and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both
occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class,
the super() construct leads to chaining of subclass constructors to superclass constructors. if a constructor
has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor
in the superclass is inserted.
35

Note: If a class only defines non-default constructors, then its subclasses will not include an implicit
super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a
superclass constructor, using the super() construct with the right arguments to match the appropriate
constructor of the superclass.

Below is an example of a class demonstrating constructor chaining using explicit super() call.

class Cube {
int length ;
int breadth ;
int height ;
public int getVolume( ) {
return ( length * breadth * height );
}

Cube(int l, int b, int h){


length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor
having 3 params of Cube");
}
}

public class SpecialCube1 extends Cube{


int weight ;

SpecialCube1(){
super(10, 20, 30); //Will Give a Compilation Error
without this line
weight = 10;
}

public static void main(String[] args) {


SpecialCube1 specialObj1 = new SpecialCube1();
System.out.println("Volume of SpecialCube1 is :
"+specialObj1.getVolume());

}
}

Output

Finished with Parameterized Constructor having 3 params of Cube


Volume of SpecialCube1 is : 6000
______________________________________________________________________________________
Java Object Serialization

Introduction to Object Serialization

Java object serialization is used to persist Java objects to a file, database, network, process or any other
system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of
bytes can then be read at a later time, or in another environment, to recreate the original objects. Java does
36

not serialize or deserialize transient or static fields. Marking the field transient prevents the state from being
written to the stream and from being restored during deserialization. Java provides classes to support
writing objects to streams and restoring objects from streams. Only objects that support the
java.io.Serializable interface or the java.io.Externalizable interface can be written to streams.

public interface Serializable

• The Serializable interface has no methods or fields. (Marker Interface)


• Only objects of classes that implement java.io.Serializable interface can be serialized or
deserialized

Transient Fields and Serialization

The transient keyword is a modifier applied to instance variables in a class. It specifies that the
variable is not part of the persistent state of the object and thus never saved during serialization.

You can use the transient keyword to describe temporary variables, or variables that contain local
information, such as a process ID or a time lapse.

Input and Output Object Streams

ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for
serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput
interface for deserializing objects.

These high-level streams are each chained to a low-level stream, such as FileInputStream or
FileOutputStream. The low-level streams handle the bytes of data. The writeObject method saves the state
of the class by writing the individual fields to the ObjectOutputStream. The readObject method is used to
deserialize the object from the object input stream.

Case 1: Below is an example that demonstrates object Serialization into a File

PersonDetails.java is the bean class that implements the Serializable interface


import java.io.Serializable;
import java.util.Date;
import java.util.Calendar;
public class PersonDetails implements Serializable
{
private String name;
private int age;
private String sex;

public PersonDetails(String name, int age, String sex) {


this.name = name;
this.age = age;
this.sex = sex;
}

public int getAge() {


37

return age;
}

public void setAge(int age) {


this.age = age;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getSex() {


return sex;
}

public void setSex(String sex) {


this.sex = sex;
}

GetPersonDetails.java is the class that is used to Deserialize object from the File (person.txt).
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails
{
public static void main(String [] args) {
String filename = "person.txt";

List pDetails = null;


FileInputStream fis = null;
ObjectInputStream in = null;
try
{
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
pDetails = (ArrayList)in.readObject();
in.close();
}

catch(IOException ex) {
ex.printStackTrace();
}

catch(ClassNotFoundException ex){
ex.printStackTrace();
}
// print out the size
System.out.println("Person Details Size: " +
pDetails.size());
38

System.out.println();

}
}

PersonPersist.java is the class that is used to serialize object into the File (person.txt).
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class PersonPersist {
public static void main(String [] args){
String filename = "person.txt";

PersonDetails person1 = new PersonDetails("hemanth",10,


"Male");
PersonDetails person2 = new PersonDetails("bob",12, "Male");
PersonDetails person3 = new PersonDetails("Richa",10,
"Female");
List list = new ArrayList();
list.add(person1);
list.add(person2);
list.add(person3);

FileOutputStream fos = null;


ObjectOutputStream out = null;
try
{
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
System.out.println("Object Persisted");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}

Case 2: Below is an example that demonstrates object Serialization into the database

PersonDetails.java remains the same as shown above

GetPersonDetails.java remains the same as shown above

Create SerialTest Table

create table SerialTest(


name BLOB,
39

viewname VARCHAR2(30)
);

PersonPersist.java is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {

static String userid="scott", password = "tiger";


static String url = "jdbc:odbc:bob";
static int count = 0;
static Connection con = null;

public static void main(String [] args){

Connection con = getOracleJDBCConnection();


PersonDetails person1 = new PersonDetails("hemanth",10,
"Male");
PersonDetails person2 = new PersonDetails("bob",12,
"Male");
PersonDetails person3 = new PersonDetails("Richa",10,
"Female");

PreparedStatement ps;
try {
ps = con.prepareStatement(
"INSERT INTO SerialTest VALUES (?, ?)");

write(person1, ps);
ps.execute();
write(person2, ps);
ps.execute();
write(person3, ps);
ps.execute();
ps.close();

Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM
SerialTest");
while(rs.next()) {
Object obj = read(rs, "Name");
PersonDetails p = (PersonDetails)obj;

System.out.println(p.getName()+"\t"+p.getAge()+"\t"+p.getSex());
}
rs.close();
40

st.close();
}catch(Exception e){}

public static void write(Object obj, PreparedStatement ps)


throws SQLException, IOException {

ByteArrayOutputStream baos = new


ByteArrayOutputStream();
ObjectOutputStream oout = new
ObjectOutputStream(baos);
oout.writeObject(obj);
oout.close();

ps.setBytes(1, baos.toByteArray());
ps.setInt(2, ++count);
}

public static Object read(ResultSet rs, String column)


throws SQLException, IOException,
ClassNotFoundException {

byte[] buf = rs.getBytes(column);


if (buf != null) {
ObjectInputStream objectIn = new ObjectInputStream(
new ByteArrayInputStream(buf));
return objectIn.readObject();
}
return null;
}

public static Connection getOracleJDBCConnection(){

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException:
");
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);
} catch(SQLException ex) {
System.err.println("SQLException: " +
ex.getMessage());
}

return con;
}
}
41

Case 3: Below is an example that demonstrates object Serialization into the database
using Base 64 Encoder

PersonDetails.java remains the same as shown above

GetPersonDetails.java remains the same as shown above

Create SerialTest Table

create table SerialTest(


name BLOB,
viewname VARCHAR2(30)
);

PersonPersist.java is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class PersonPersist {

static String userid="scott", password = "tiger";


static String url = "jdbc:odbc:bob";
static int count = 0;
static Connection con = null;
static String s;

public static void main(String [] args){

Connection con = getOracleJDBCConnection();


PersonDetails person1 = new PersonDetails("hemanth",10,
"Male");
PersonDetails person2 = new PersonDetails("bob",12,
"Male");
PersonDetails person3 = new PersonDetails("Richa",10,
"Female");

PreparedStatement ps;
try {
ps = con.prepareStatement(
"INSERT INTO SerialTest VALUES (?, ?)");

write(person1, ps);
ps.execute();
write(person2, ps);
ps.execute();
write(person3, ps);
42

ps.execute();
ps.close();

Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM
SerialTest");
while(rs.next()) {
Object obj = read(rs, "Name");
PersonDetails p = (PersonDetails)obj;

System.out.println(p.getName()+"\t"+p.getAge()+"\t"+p.getSex());
}
rs.close();
st.close();
}catch(Exception e){}

public static void write(Object obj, PreparedStatement ps)


throws SQLException, IOException {

ByteArrayOutputStream baos = new


ByteArrayOutputStream();
ObjectOutputStream oout = new
ObjectOutputStream(baos);
oout.writeObject(obj);
oout.close();
byte[] buf = baos.toByteArray();
s = new sun.misc.BASE64Encoder().encode(buf);
ps.setString(1, s);
// ps.setBytes(1,
Base64.byteArrayToBase64(baos.toByteArray()));

ps.setBytes(1, baos.toByteArray());
ps.setInt(2, ++count);
}

public static Object read(ResultSet rs, String column)


throws SQLException, IOException,
ClassNotFoundException {

byte[] buf = new


sun.misc.BASE64Decoder().decodeBuffer(s);
// byte[] buf = Base64.base64ToByteArray(new
String(rs.getBytes(column)));

if (buf != null) {
ObjectInputStream objectIn = new ObjectInputStream(
new ByteArrayInputStream(buf));
Object obj = objectIn.readObject();
//Contains the object
PersonDetails p = (PersonDetails)obj;

System.out.println(p.getName()+"\t"+p.getAge()+"\t"+p.getSex());
}
return null;
43

public static Connection getOracleJDBCConnection(){

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException:
");
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
userid, password);
} catch(SQLException ex) {
System.err.println("SQLException: " +
ex.getMessage());
}

return con;
}
}

Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As
before the object to be serialized must implement the Serializable interface.

PersonDetails.java is the bean class that implements the Serializable interface


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ObjectSerializationExample{


public static void main(String args[]){
try{
Object object = new javax.swing.JButton("Submit");

// Serialize to a file namely "filename.dat"


ObjectOutput out = new ObjectOutputStream(new
FileOutputStream("filename.dat"));
out.writeObject(object);
out.close();

// Serialize to a byte array


ByteArrayOutputStream bos = new ByteArrayOutputStream()
;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object


byte[] buf = bos.toByteArray();
}
44

catch (Exception e){


e.printStackTrace();
}
}

}
______________________________________________________________________________________

Java Class Inheritance

Java Class Inheritance

Inheritance defines an is-a relationship is-a between a superclass and its subclasses. This means that an
object of a subclass can be used wherever an object of the superclass can be used. Java Inheritance
mechanism is used to build new classes from existing classes. . The inheritance relationship is transitive: if
class x extends class y, then a class z, which extends class x, will also inherit from class y.

For example a car class can inherit some properties from a General vehicle class. Here we find that the
base class is the vehicle class and the subclass is the more specific car class. A subclass must use the
extends clause to derive from a super class which must be written in the header of the subclass definition.
The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add
its own new behavior and properties. The java.lang.Object class is always at the top of any Java inheritance
hierarchy.

class Box{
double width;
double height;
double depth;

Box(){
}

Box(double w, double h, double d){


width = w;
height = h;
depth = d;
}

void getVolume(){
System.out.println("Volume is : "+width*height*depth);
}
}

public class MatchBox extends Box{


double weight;

MatchBox() {
}

MatchBox(double w, double h, double d, double m) {

super(w,h,d);
weight = m;
}
45

public static void main(String args[])


{
MatchBox mb1 = new MatchBox(10,10,10,10);

mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);

}
}
Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0

What is not possible using Inheritance

1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in
other packages, as these members are only accessible by their simple names in subclasses within
the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
4. A subclass can extend only one superclass

class Vehicle {
// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present
or not
protected String brand; // Brand of the car

// Static fields
private static int counter; // No of Vehicle objects created

// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}

// Instance methods
public void switchOn() {
accessories = true;
46

public void switchOff() {


accessories = false;
}

public boolean isPresent(){


return accessories;
}

private void getBrand() {


System.out.println("Vehicle Brand: " + brand);
}

// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}

class Car extends Vehicle {

private int carNo = 10;

public void printCarInfo() {


System.out.println("Car number: " + carNo);
System.out.println("No of Tyres: " + noOfTyres); //
Inherited.
// System.out.println("accessories: " + accessories); // Not
Inherited.
System.out.println("accessories: " + isPresent()); //
Inherited.
// System.out.println("Brand: " + getBrand()); // Not
Inherited.
System.out.println("Brand: " + brand); // Inherited.
// System.out.println("Counter: " + counter); // Not
Inherited.
getNoOfVehicles(); //
Inherited.
}
// ...
}

public class VehicleDetails { // (3)


public static void main(String[] args) {
new Car().printCarInfo();

}
}

Output

Constructor of the Super class called


Car number: 10
No of Tyres: 5
accessories: true
47

Brand: X
Number of Vehicles: 1

this and super keywords


Java has two keywords, this and super to help you explicitly name the field or method that you want.
Using this and super you have full control on whether to call a method or field present in the same class or
to call from the immediate superclass. This keyword is used as a reference to the current object which is an
instance of the current class. The keyword super also references the current object, but as an instance of the
current class's super class.

The this reference to the current object is useful in situations where a local variable hides, or shadows, a
field with the same name. If a method needs to pass the current object to another method, it can do so using
the this reference. Note that the this reference cannot be used in a static context, as static code is not
executed in the context of any object.

class Counter {
int i = 0;

Counter increment() {
i++;
return this;
}

void print() {
System.out.println("i = " + i);
}
}

public class CounterDemo extends Counter{


public static void main(String[] args) {
Counter x = new Counter();
x.increment().increment().increment().print();
}
}

Output

Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
______________________________________________________________________________________
Java Object Casting

Object Reference Type Casting

In java one object reference can be cast into another object reference. The cast can be to its own class
type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime
rules for casting in java. The casting of object references depends on the relationship of the classes involved
in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object,
because the Object class is a superclass of every Java class.

There can be 2 types of casting


48

· Upcasting
· Downcasting

When we cast a reference along the class hierarchy in a direction from the root class towards the
children or subclasses, it is a downcast.
When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it
is an upcast. We need not use a cast operator in this case.

The compile-time rules are there to catch attempted casts in cases that are simply not possible. This
happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class
relationship or a class-interface relationship)
At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is
being cast to.

Below is an example showing when a ClassCastException can occur during object


casting

//X is a supper class of Y and Z which are sibblings.

public class RunTimeCastDemo{


public static void main(String args[]){
X x = new X();
Y y = new Y();
Z z = new Z();

X xy = new Y(); // compiles ok (up the hierarchy)


X xz = new Z(); // compiles ok (up the hierarchy)
// Y yz = new Z(); incompatible type (siblings)

// Y y1 = new X(); X is not a Y


// Z z1 = new X(); X is not a Z

X x1 = y; // compiles ok (y is subclass of X)
X x2 = z; // compiles ok (z is subclass of X)

Y y1 = (Y) x; // compiles ok but produces runtime


error
Z z1 = (Z) x; // compiles ok but produces runtime
error
Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
// Y y3 = (Y) z; inconvertible types (siblings)
// Z z3 = (Z) y; inconvertible types (siblings)

Object o = z;
Object o1 = (Y)o; // compiles ok but produces runtime
error

Casting Object References: Implicit Casting using a Java Compiler


49

In general an implicit cast is done when an Object reference is assigned (cast) to:

• A reference variable whose type is the same as the class from which the object was instantiated.
An Object as Object is a super class of every Java Class.
• A reference variable whose type is a super class of the class from which the object was
instantiated.
• A reference variable whose type is an interface that is implemented by the class from which the
object was instantiated.
• A reference variable whose type is an interface that is implemented by a super class of the class
from which the object was instantiated.

Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the
automatic conversion of object references handled by the java compiler

interface Vehicle {
}
class Car implements Vehicle {
}

class Ford extends Car {


}

Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can
assign the Ford reference to the Car variable:
I.e. we can do the following

Example 1
c = f; //Ok Compiles fine

Where c = new Car();


And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are compatible (sub class -
super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.

Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation error

Where c = new Car();


And v is a Vehicle interface reference (Vehicle v)

The compiler automatically handles the conversion (assignment) since the types are compatible (class –
interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle
Interface. (Car is a Vehicle).

Casting Object References: Explicit Casting


50

Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a
particular scenario. The explicit cast is nothing but the name of the new “type” inside a pair of matched
parentheses. As before, we consider the same Car and Ford Class

class Car {
void carMethod(){
}
}

class Ford extends Car {


void fordMethod () {
}
}
We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input
parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is
a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of
object at run time.

public void breakingSystem (Car obj) {


obj.carMethod();
if (obj instanceof Ford)

((Ford)obj).fordMethod ();
}
To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced
by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that
fordMethod() cannot be found in the Car definition.

The following java shown illustrates the use of the cast operator with references.

Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of
Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend
some other class will automatically extends the Object by default. This code instantiates an object of the
class Ford and assigns the object's reference to a reference variable of type Car. This assignment is allowed
as Car is a superclass of Ford.
In order to use a reference of a class type to invoke a method, the method must be defined at or above
that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class
Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this
problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object
reference as done in the program.
Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException
at runtime, although compilation happens without any error.

class Car extends Object{


void carMethod() {
}
}

class HeavyVehicle extends Object{


51

class Ford extends Car {


void fordMethod () {
System.out.println("I am fordMethod defined in Class
Ford");
}
}

class Honda extends Car {


void fordMethod () {
System.out.println("I am fordMethod defined in Class
Ford");
}
}

public class ObjectCastingEx{


public static void main(
String[] args){
Car obj = new Ford();
// Following will result in compilation error
// obj.fordMethod(); //As the method fordMethod is undefined
for the Car Type
// Following will result in compilation error
// ((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in
the HeavyVehicle Type
// Following will result in compilation error

((Ford)obj).fordMethod();

//Following will compile and run


// Honda hondaObj = (Ford)obj; Cannot convert as they are
sibblings

}
}
One common casting that is performed when dealing with collections
is, you can cast an object reference into a String.
import java.util.Vector;

public class StringCastDemo{


public static void main(String args[]){
String username = "asdf";
String password = "qwer";
Vector v = new Vector();
v.add(username);
v.add(password);

// String u = v.elementAt(0); Cannot convert from object to


String
Object u = v.elementAt(0); //Cast not done
System.out.println("Username : " +u);
52

String uname = (String) v.elementAt(0); // cast allowed


String pass = (String) v.elementAt(1); // cast allowed

System.out.println();
System.out.println("Username : " +uname);
System.out.println("Password : " +pass);
}

Output

Username : asdf

Username : asdf
Password : qwer

instanceof Operator

The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a
specific class, or implements a specific interface. It returns true if an object is an instance of the class or if
the object implements the interface, otherwise it returns false.

Below is an example showing the use of instanceof operator

class Vehicle {
String name;
Vehicle() {
name = "Vehicle";
}
}
class HeavyVehicle extends Vehicle{
HeavyVehicle() {
name = "HeavyVehicle";
}
}
class Truck extends HeavyVehicle{
Truck() {
name = "Truck";
}
}
class LightVehicle extends Vehicle{
LightVehicle() {
name = "LightVehicle";
}
}

public class InstanceOfExample {


static boolean result;
static HeavyVehicle hV = new HeavyVehicle( );
static Truck T = new Truck( );
static HeavyVehicle hv2 = null;
public static void main( String[] args ) {
53

result = hV instanceof HeavyVehicle;


System.out.print("hV is an HeavyVehicle: " + result +
"\n");
result = T instanceof HeavyVehicle;
System.out.print("T is an HeavyVehicle: " + result +
"\n");
result = hV instanceof Truck;
System.out.print("hV is a Truck: " + result + "\n");
result = hv2 instanceof HeavyVehicle;
System.out.print("hv2 is an HeavyVehicle: " + result +
"\n");
hV = T; //Sucessful Cast form child to parent
T = (Truck)hV; //Sucessful Explicit Cast form parent to
child
}
}

Output

hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false
______________________________________________________________________________________
Abstract class and Interface

Abstract Class in java

Abstract classes are used to declare common characteristics of subclasses. An abstract class
cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class.
Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or
design for concrete subclasses down the inheritance tree.

Like any other class, an abstract class can contain fields that describe the characteristics and
methods that describe the actions that a class can perform. An abstract class can include methods that
contain no implementation. These are called abstract methods. The abstract method declaration must then
end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited,
the entire class must be declared abstract. Abstract methods are used to provide a template for the classes
that inherit the abstract methods.

Abstract classes cannot be instantiated; they must be subclassed, and actual implementations must
be provided for the abstract methods. Any implementation specified can, of course, be overridden by
additional subclasses. An object must have an implementation for all of its methods. You need to create a
subclass that provides an implementation for the abstract method.

A class abstract Vehicle might be specified as abstract to represent the general abstraction of a
vehicle, as creating instances of the class would not be meaningful.

abstract class Vehicle {


int numofGears;
String color;
abstract boolean hasDiskBrake( );
abstract int getNoofGears( );
}
54

Example of a shape class as an abstract class

abstract class Shape {


public String color;
public Shape( ) {
}

public void setColor( String c ){


color = c;
}

public String getColor( ) {


return color;
}

abstract public double area( );

We can also implement the generic shapes class as an abstract class so that we can draw lines,
circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more
fields and methods. The abstract class guarantees that each shape will have the same set of basic properties.
We declare this class abstract because there is no such thing as a generic shape. There can only be concrete
shapes such as squares, circles, triangles etc.

public class Point extends Shape {


static int x, y;
public Point( ) {
x = 0;
y = 0;
}

public double area( ) {


return 0;
}

public double perimeter( ) {


return 0;
}

public static void print( ){


System.out.println ( "point: " + x + "," + y );
}

public static void main(String args[]){


Point p = new Point();
p.print();
}

Output

point: 0, 0
55

Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract
methods of the Shape class must be implemented by the Point class.

The subclass must define an implementation for every abstract method of the abstract superclass,
or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic
Shape Abstract class.

A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the
sense, when a class extends an abstract class, it can’t extend any other class.

Java Interface

In Java, this multiple inheritance problem is solved with a powerful construct called interfaces.
Interface can be used to define a generic template and then one or more abstract classes to define partial
implementations of the interface. Interfaces just specify the method declaration (implicitly public and
abstract) and can only contain fields (which are implicitly public static final). Interface definition begins
with a keyword interface. An interface like that of an abstract class cannot be instantiated.

Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one
or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and
implement many interfaces.

If a class that implements an interface does not define all the methods of the interface, then it must
be declared abstract and the method definitions must be provided by the subclass that extends the abstract
class.

Example 1: Below is an example of a Shape interface

interface Shape {
public double area( );
public double volume( );
}

Below is a Point class that implements the Shape interface.

public class Point implements Shape {


static int x, y;
public Point( ) {
x = 0;
y = 0;
}

public double area( ) {


return 0;
}

public double volume( ) {


return 0;
}

public static void print( ){


System.out.println ( "point: " + x + "," + y );
}
56

public static void main(String args[]){


Point p = new Point();
p.print();
}

Similarly, other shape objects can be created by interface programming by implementing generic Shape
Interface.

Example 2: Below is a java interfaces program showing the power of interface programming in
java

Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class named
Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the
methods of the implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super
interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the
program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.

When we invoke the toString() method which is a method of an Object, there does not seem to be any
problem as every interface or class extends Object and any class can override the default toString() to suit
your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at
runtime. This is because B1 does not have any relationship with C1 except they are "siblings". You can't
cast siblings into one another.

When a given interface method is invoked on a given reference, the behavior that results will be
appropriate to the class from which that particular object was instantiated. This is runtime polymorphism
based on interfaces and overridden methods.

interface I1{
void methodI1(); //public static by default
}

interface I2 extends I1{


void methodI2(); //public static by default
}

class A1{
public String methodA1(){
String strA1 = "I am in methodC1 of class A1";
return strA1;
}

public String toString(){


return "toString() method of class A1";
}
}
class B1 extends A1 implements I2{
public void methodI1(){
System.out.println("I am in methodI1 of class B1");
}
57

public void methodI2(){


System.out.println("I am in methodI2 of class B1");
}
}

class C1 implements I2{


public void methodI1(){
System.out.println("I am in methodI1 of class C1");
}

public void methodI2(){


System.out.println("I am in methodI2 of class C1");
}
}

// Note that the class is declared as abstract as it does not


//satisfy the interface contract
abstract class D1 implements I2{
public void methodI1() {
}

//This class does not implement methodI2() hence declared


abstract.

}
public class InterFaceEx{
public static void main(String[] args){
I1 i1 = new B1();
i1.methodI1(); //OK as methodI1 is present in B1
// i1.methodI2(); Compilation error as methodI2 not present
in I1

// Casting to convert the type of the reference from type I1 to


type I2
((I2)i1).methodI2();

I2 i2 = new B1();
i2.methodI1(); //OK
i2.methodI2(); //OK

// Does not Compile as methodA1() not present in interface


reference I1
// String var = i1.methodA1();

//Hence I1 requires a cast to invoke methodA1

String var2 = ((A1)i1).methodA1();


System.out.println("var2 : "+var2);
String var3 = ((B1)i1).methodA1();
System.out.println("var3 : "+var3);
String var4 = i1.toString();
System.out.println("var4 : "+var4);
String var5 = i2.toString();
System.out.println("var5 : "+var5);

I1 i3 = new C1();
58

String var6 = i3.toString();


System.out.println("var6 : "+var6); //It prints the Object
toString() method

Object o1 = new B1();


// o1.methodI1(); does not compile as Object class does not
define methodI1()
//To solve the probelm we need to downcast o1 reference. We can do it
in the following 4 ways
((I1)o1).methodI1(); //1
((I2)o1).methodI1(); //2
((B1)o1).methodI1(); //3

/*
* B1 does not have any relationship with C1 except they are
"siblings".
* Well, you can't cast siblings into one another.
*/
// ((C1)o1).methodI1(); Produces a ClassCastException

}
}

Output

I am in methodI1 of class B1
I am in methodI2 of class B1
I am in methodI1 of class B1
I am in methodI2 of class B1
var2 : I am in methodC1 of class A1
var3 : I am in methodC1 of class A1
var4 : toString() method of class A1
var5 : toString() method of class A1
var6 : C1@190d11
I am in methodI1 of class B1
I am in methodI1 of class B1
I am in methodI1 of class B1

Polymorphism

Polymorphism means one name, many forms. There are 3 distinct forms of Java Polymorphism;

• Method overloading (Compile time polymorphism)


• Method overriding through inheritance (Run time polymorphism)
• Method overriding through the Java interface (Run time polymorphism)

Polymorphism allows a reference to denote objects of different types at different times during
execution. A super type reference exhibits polymorphic behavior, since it can denote objects of its subtypes.

interface Shape {
public double area( );
public double volume( );
59

class Cube implements Shape {


int x= 10;

public double area( ) {


return (6 * x * x);
}

public double volume( ) {


return (x * x * x);
}
}

class Circle implements Shape {


int radius = 10;

public double area( ) {


return (Math.PI * radius * radius);
}

public double volume( ) {


return 0;
}

public class PolymorphismTest{


public static void main(String args[]){
Shape[] s = {new Cube(), new Circle()};

for( int i = 0; i< s.length; i++){


System.out.println("The area and volume of
"+s[i].getClass()+
" is "+s[i].area()+" ,
"+s[i].volume());
}
}
}

Output

The area and volume of class Cube is 600.0 , 1000.0


The area and volume of class Circle is 314.1592653589793 , 0.0

The methods area() and volume() are overridden in the implementing classes. The invocation of the
both methods area and volume is determined based on run time polymorphism of the current object as
shown in the output.
______________________________________________________________________________________
Java Method Overriding

Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass,
following which the new method implementation in the subclass that is executed.
60

The new method definition must have the same method signature (i.e., method name and parameters) and
return type. Only parameter types and return type are chosen as criteria for matching method signature. So
if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it
still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen
it. The new method definition can only specify all or none, or a subset of the exception classes (including
their subclasses) specified in the throws clause of the overridden method in the super class

A program to explain the different concepts of Java Method Overridding

class CustomException extends Exception{

class SuperClassWithDifferentMethods{

protected int field1 = 10;


protected static int field2 = 20;

public void method1() {

System.out.println("SuperClassWithDifferentMethods.method1()");
}

public final void method2(){

System.out.println("SuperClassWithDifferentMethods.method2()");
}

private void method3() {

System.out.println("SuperClassWithDifferentMethods.method3()");
}

private final void method4(){

System.out.println("SuperClassWithDifferentMethods.method4()");
}

public static void method5() {

System.out.println("SuperClassWithDifferentMethods.method5()");
}

public void method6() throws Exception {

System.out.println("SuperClassWithDifferentMethods.method6()");
}

private void method7(){

System.out.println("SuperClassWithDifferentMethods.method7()");
}

private void method8(int x){

System.out.println("SuperClassWithDifferentMethods.method8()");
61

public static void method9() {

System.out.println("SuperClassWithDifferentMethods.method9()");
}
}

class OverridingClass extends SuperClassWithDifferentMethods {

public int field1 = 30;


public static int field2 = 40;

public void method1() {


System.out.println("OverridingClass.method1()");
}

//We can't override a public final method


/* public final void method2(){
System.out.println("OverridingClass.method2()");
}*/

private void method3(){


System.out.println("OverridingClass.method3()");
}

private final void method4(){


System.out.println("OverridingClass.method4()");
}

public static void method5() {


System.out.println("OverridingClass.method5()");
}

public void method6() throws CustomException{


System.out.println("OverridingClass.method6()");
}

public void method7(){

System.out.println("OverridingClass.method7()");
}

public void method8(final int x){


System.out.println("OverridingClass.method8()");
}

//A static method cannot be overridden to be non-static


instance method
/*public void method9() {
System.out.println("OverridingClass.method9()");
}*/

public class MethodOverridingDemo {


62

public static void main(String[] args) {


OverridingClass oc1 = new OverridingClass();
SuperClassWithDifferentMethods sc3 = new OverridingClass();
oc1.method1();
oc1.method2();

// Since its private, the below 2 methods are not visible


/* oc1.method3();
oc1.method4();*/

oc1.method5();
try {
oc1.method6();
} catch (CustomException e) {
e.printStackTrace();
}
oc1.method7();
oc1.method8(100);
System.out.println("oc1.field1 : "+oc1.field1);
System.out.println("oc1.field2 : "+oc1.field2);
System.out.println("sc3.field1 : "+sc3.field1);
System.out.println("sc3.field2 : "+sc3.field2);
sc3.method5();

OverridingClass overClass = new OverridingClass();


SuperClassWithDifferentMethods supClass =
(SuperClassWithDifferentMethods)overClass;
supClass.method5();
supClass.method1();

}
}
Output
OverridingClass.method1()
SuperClassWithDifferentMethods.method2()
OverridingClass.method5()
OverridingClass.method6()
OverridingClass.method7()
OverridingClass.method8()
oc1.field1 : 30
oc1.field2 : 40
sc3.field1 : 10
sc3.field2 : 20
SuperClassWithDifferentMethods.method5()
SuperClassWithDifferentMethods.method5()
OverridingClass.method1()

The new method definitions in the subclass OverridingClass have the same signature and the same
return type as the methods in the superclass SuperClassWithDifferentMethods. The new overridden
method6 definition specifies a subset of the exceptions (CustomException). The new overridden method7
definition also widens the accessibility to public from private. The overriding method8 also declares the
parameter to be final, which is not a part of the method signature and Method Overriding holds good. A
static method cannot be overridden to be non-static instance method as shown in the overridden method
declaration of method9. A static method is class-specific and not part of any object, while overriding
63

methods are invoked on behalf of objects of the subclass. There are no such restrictions on the fields, as for
fields only the field names matter. A final method cannot be overridden, an attempt to which will result in a
compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a
subclass cannot override it.

A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. A
subclass cannot override fields of the superclass, but it can hide them. Code in the subclass can use the
keyword super to access members, including hidden fields.

The following distinction between invoking instance methods on an object and accessing fields of an
object must be noted. When an instance method is invoked on an object using a reference, it is the class of
the current object denoted by the reference, not the type of the reference, that determines which method
implementation will be executed. When a field of an object is accessed using a reference, it is the type of
the reference, not the class of the current object denoted by the reference, that determines which field will
actually be accessed. This is demonstrated in the above program.
______________________________________________________________________________________
Java toString() Method

Java toString() Method

The java toString() method is used when we need a string representation of an object. It is defined in
java.lang.Object is toString. This method can be overridden to customize the String representation of the
Object. Below is a program showing the use of the Object's Default toString() method.

class PointCoordinates {
private int x, y;

public PointCoordinates(int x, int y) {


this.x = x;
this.y = y;
}

public int getX() {


return x;
}

public int getY() {


return y;
}
}

public class ToStringDemo {


public static void main(String args[]) {
PointCoordinates point = new PointCoordinates(10, 10);

// using the Default Object.toString() Method


System.out.println("Object toString() method : "+point);

// implicitly call toString() on object as part of string


concatenation
String s = point + " testing";
System.out.println(s);

}
64

When you run the ToStringDemo program, the output is:

Object toString() method : PointCoordinates@119c082


PointCoordinates@119c082 testing

In the above example when we try printing PointCoordinates object, it internally calls the Object’s
toString() method as we have not overridden the java toString() method. Since out example has no toString
method, the default one in java.lang.Object is used.

What does the default toString method actually return as a string value? The format of the default
toString method of the Object is as shown below.

Class Name, “@", and the hex version of the object's hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting the memory address of the
object into an integer.

Below is an example shown of the same program by Overriding the default Object toString() method.
The toString() method must be descriptive and should generally cover all the contents of the object.Each
field in the toString() method must cantain descriptive Labels.

class PointCoordinates {
private int x, y;

public PointCoordinates(int x, int y) {


this.x = x;
this.y = y;
}

public int getX() {


return x;
}

public int getY() {


return y;
}
//Custom toString() Method.
public String toString() {
return "X=" + x + " " + "Y=" + y;
}

public class ToStringDemo2 {


public static void main(String args[]) {
PointCoordinates point = new PointCoordinates(10, 10);

// using the Over ridden Object.toString() Method


System.out.println(point);

String s = point + " testing";


System.out.println(s);
65

}
}

When you run the ToStringDemo2 program, the output is:

X=10 Y=10
X=10 Y=10 testing
______________________________________________________________________________________
Java Exception Handling

Exceptions in Java

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at
runtime. They could be file not found exception, unable to get connection exception and so on. On such
conditions java throws an exception object. Exceptions are basically Java objects. A Large Java Project can
never escape a java error exception.

Javaexception handling is used to handle error conditions in a program systematically by taking


the necessary action. Exception handlers can be written to catch a specific exception such as Number
Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions
not specifically handled within a Java program are caught by the Java run time environment

An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable
class. Java exceptions are raised with the throw keyword and handled within a catch block.

A Program Showing How the JVM throws an Exception at runtime

public class DivideException {

public static void main(String[] args) {


division(100,4); // Line 1
division(100,0); // Line 2
System.out.println("Exit main().");
}

public static void division(int totalSum, int totalNumber) {


System.out.println("Computing Division.");
int average = totalSum/totalNumber;
System.out.println("Average : "+ average);
}
}

An ArithmeticException is thrown at runtime when Line 11 is executed


because integer division by 0 is an illegal operation. The “Exit main()” message is never
reached in the main method

Output

Computing Division.
java.lang.ArithmeticException: / by zero
66

Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)
Exception in thread "main"

Exception Classes
Throwable Class

The Throwable class provides a String variable that can be set by the subclasses to provide a detail
message that provides more information of the exception occurred. All classes of throwables define a one-
parameter constructor that takes a string as the detail message.

The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace()
method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a
short description of the exception. For more information on what is printed when the following messages
are invoked, please refer the java docs.

Syntax

String getMessage()

void printStackTrace()

String toString()

Class Exception

The class Exception represents exceptions that a program faces due to abnormal or special conditions
during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time
Exceptions).

Class RuntimeException

Runtime exceptions represent programming errors that manifest at runtime. For example
ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the
java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business
logic programming errors.

Class Error

Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc.
Errors are direct subclass of Throwable class.

Checked and Unchecked Exceptions

ACheckedexceptionis an Exception or a subclass of Exception excluding classRuntimeException


and its subclasses. Making an exception checked forcesprogrammers to deal with the exception that may be
thrown. Example: Arithmeticexception. When a checked exception occurs in a method, the method must
eithercatch the exception and take the appropriate action, or pass the exception on toits caller
67

Uncheckedexceptionsare RuntimeException and any of its subclasses. Class Error andits


subclasses also are unchecked. With an unchecked exception, however, thecompiler doesn't force the
programmers to either catch the
exception ordeclare it in a throws clause. In fact, the programmers may not even know thatthe exception
could be thrown. Example: ArrayIndexOutOfBounds Exception. Theyare either irrecoverable (Errors) and
the program should not attempt to dealwith them, or they are logical programming errors. (Runtime
Exceptions). Checkedexceptions must be caught at compile time. Runtime exceptions do not need to
be.Errors often cannot be.

Exception Statement Syntax

Exceptions are handled using a try-catch-finally construct, which has the Syntax

try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}

try Block

The java code that you think may produce an exception is placed within a try block for a suitable catch
block to handle the error. If no exception occurs the execution proceeds with the finally block else it will
look for the matching catch block to handle the error. Again if the matching catch handler is not found
execution proceeds with the finally block and the default exception handler throws an exception.. If an
exception is generated within the try block, the remaining statements in the try block are not executed.

catch Block

Exceptions thrown during execution of the try block can be caught and handled in a catch block. On
exit from a catch block, normal execution continues and the finally block is executed (Though the catch
block throws an exception).

finally Block

A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up,
closing connections etc. If the finally clock executes a control transfer statement such as a return or a break
statement, then this control statement determines how the execution will proceed regardless of any return or
control statement present in the try or catch. The following program illustrates the scenario.

public class DivideException2 {

public static void main(String[] args) {


int result = division(100,0); // Line 2
System.out.println("result : "+result);
}

public static int division(int totalSum, int totalNumber) {


68

int quotient = -1;


System.out.println("Computing Division.");
try{
quotient = totalSum/totalNumber;

}
catch(Exception e){
System.out.println("Exception : "+ e.getMessage());
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes.
Exception Occurred");
return quotient;
}

}
return quotient;
}
}

Output

Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1

Below is a program showing the Normal Execution of the Program. Please note that no
NullPointerException is generated as was expected by most people

class NoException {
public static void main (String[] args) {
String s = null;
System.out.print(s);
}
}

Output

null (And not NullPointerException)


______________________________________________________________________________________
Java Singleton Design Pattern

Singleton
69

Java has several design patterns Singleton Pattern being the most commonly used design pattern.
Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This
design pattern proposes that at any time there can only be one instance of a singleton (object) created by the
JVM.

The Singleton class’s default constructor is made private, which prevents the direct instantiation of the
object by others (Other Classes). A static modifier is applied to the instance method that returns the
singleton object as it then makes this method a class level method that can be accessed without creating an
object.

One such scenario where it might prove useful is when we develop the Java Help Module in a project.
Java Help is an extensible, platform-independent help system that enables authors and developers to
incorporate online help into applications. Since at any time we can do only with one main Help object and
use the same object in different screens, Singleton Pattern suits best for its implementation.

A singleton pattern can also be used to create a Connection Pool. If programmers create a new
connection object in every java class that requires it, then its clear waste of resources. In this scenario by
using a singleton connection class we can maintain a single connection object which can be used
throughout the Java application.

Implementing the Singleton Pattern


To implement this design pattern we need to consider the following 4 steps:

Step 1: Provide a default Private constructor


public class SingletonObjectDemo
{
//Note that the constructor is private
private SingletonObjectDemo ()
{
// Optional Code
}
}

Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo{
private static SingletonObject singletonObject;

//Note that the constructor is private


private SingletonObjectDemo (){
// Optional Code
}

public static SingletonObjectDemo getSingletonObject(){


if (singletonObject == null){
singletonObject = new SingletonObjectDemo ();
}
return singletonObject;

}
70

We write a public static getter or access method to get the instance of the Singleton Object at runtime.
First time the object is created inside this method as it is null. Subsequent calls to this method returns the
same object created as the object is globally declared (private) and the hence the same referenced object is
returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.


public static synchronized SingletonObjectDemo getSingletonObject()

It could happen that the access method may be called twice from 2 different classes at the same time and
hence more than one singleton object being created. This could violate singleton pattern principle. In order
to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add
the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning.

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can
be done as shown below

SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();

This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the
Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {


throw new CloneNotSupportedException();
}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the
4 steps mentioned above.

class SingletonClass{

private static SingletonClass singletonObject;

/** A private Constructor prevents any other class from


instantiating. */
private SingletonClass(){
// Optional Code
}

public static synchronized SingletonClass getSingletonObject()


{
if (singletonObject == null){
singletonObject = new SingletonClass();
}
return singletonObject;
}

public Object clone()throws CloneNotSupportedException


{
throw new CloneNotSupportedException();
}

}
71

public class SingletonObjectDemo{


public static void main(String args[]){
// SingletonClass obj = new SingletonClass(); Compilation
error not allowed

//create the Singleton Object..


SingletonClass obj =
SingletonClass.getSingletonObject();

// Your Business Logic


System.out.println("Singleton object obtained");

}
}

Another approach to using Singleton pattern

We don't need to do a lazy initialization of the instance object or to check for null in the get method. We can
also make the singleton class final to avoid sub classing of singletons that may cause other problems.

public class SingletonClass {


private static SingletonClass ourInstance = new
SingletonClass();
public static SingletonClass getInstance() {
return singletonObj; }
private SingletonClass() {
}
}

In Summary, the job of the Singleton class is to enforce the existence of a maximum of one
object of the same type at any given time. Depending on your implementation, your Singleton class
and all of its data might be garbage collected. Hence we must ensure that at any point there must be
a live reference to the Singleton class when the application is running.
______________________________________________________________________________________
Java Threads Tutorial

Introduction to Threads

Multithreading refers to two or more tasks executing concurrently within a single program. A
thread is an independent path of execution within a program. Many threads can run concurrently within a
program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can
have many threads, and these threads can run concurrently, either asynchronously or synchronously.

Multithreading has several advantages over Multiprocessing such as;

• Threads are lightweight compared to processes


• Threads share the same address space and therefore can share both data and code
• Context switching between threads is usually less expensive than between processes
• Cost of thread intercommunication is relatively low that that of process
intercommunication
• Threads allow different tasks to be performed concurrently.
72

Thread Creation

There are two ways to create thread in java;

• Implement the Runnable interface (java.lang.Runnable)


• By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface

The Runnable Interface Signature

public interface Runnable {


void run();
}
One way to create a thread in java is to implement the Runnable Interface and then
instantiate an object of the class. We need to override the run() method into our class which is the only
method that needs to be implemented. The run() method contains the logic of the thread.

The procedure for creating threads based on the Runnable interface is as follows:

1. A class implements the Runnable interface, providing the run() method that will be executed
by the thread. An object of this class is a Runnable object.

2. An object of Thread class is created by passing a Runnable object as argument to the Thread
constructor. The Thread object now has a Runnable object that implements the run() method.

3. The start() method is invoked on the Thread object created in the previous step. The start()
method returns immediately after a thread has been spawned.

4. The thread ends when the run() method ends, either by normal completion or by throwing an
uncaught exception.

Below is a program that illustrates instantiation and running of threads using the runnable interface
instead of extending the Thread class. To start the thread you need to invoke the start() method on your
object.

class RunnableThread implements Runnable{

Thread runner;
public RunnableThread() {
}

public RunnableThread(String threadName) {


runner = new Thread(this, threadName); // (1) Create a new
thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the
thread.
}

public void run(){


//Display info about this particular thread
73

System.out.println(Thread.currentThread());
}

public class RunnableExample{

public static void main(String[] args){

Thread thread1 = new Thread(new


RunnableThread(),"thread1");
Thread thread2 = new Thread(new
RunnableThread(),"thread2");
RunnableThread thread3 = new RunnableThread("thread3");

//Start the threads


thread1.start();
thread2.start();
try{
//delay for one second
Thread.currentThread().sleep(1000);
}catch(InterruptedException e){}

//Display info about the main thread


System.out.println(Thread.currentThread());

Output

thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private

This approach of creating a thread by implementing the Runnable Interface must be used whenever the
class being used to instantiate the thread object is required to extend some other class.

Extending Thread Class


The procedure for creating threads based on extending the Thread is as follows:

1. A class extending the Thread class overrides the run() method from the Thread class to define
the code executed by the thread.

2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread,
using the super() call.

3. The start() method inherited from the Thread class is invoked on the object of the class to
make the thread eligible for running.
74

Below is a program that illustrates instantiation and running of threads by extending the Thread class
instead of implementing the Runnable interface. To start the thread you need to invoke the start() method
on your object.

class XThread extends Thread{

XThread(){

XThread(String threadName){
super(threadName); // Initialize
thread.
System.out.println(this);
start();
}

public void run(){


//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample{


public static void main(String[] args){

Thread thread1 = new Thread(new XThread(),"thread1");


Thread thread2 = new Thread(new XThread(),"thread2");

// The below 2 threads are assigned default names


Thread thread3 = new XThread();
Thread thread4 = new XThread();

Thread thread5 = new XThread("thread5");

//Start the threads


thread1.start();
thread2.start();
thread3.start();
thread4.start();

try{
//The sleep() method is invoked on the main thread to cause a one
second delay.
Thread.currentThread().sleep(1000);
}catch(InterruptedException e){}

//Display info about the main thread


System.out.println(Thread.currentThread());

}
}

Output
75

Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]

When creating threads, there are two reasons why implementing the Runnable interface may be
preferable to extending the Thread class:

• Extending the Thread class means that the subclass cannot extend any other class,
whereas a class implementing the Runnable interface has this option.
• A class might only be interested in being runnable, and therefore, inheriting the full
overhead of the Thread class would be excessive.

An example of an anonymous class below shows how to create a thread and start it:

( new Thread() {
public void run() {
for(;;) System.out.println("Stop the world!");
}
}

).start();
______________________________________________________________________________________
Java StringBuffer

StringBuffer Class

StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and
character string of a StringBuffer can be changed dynamically. String buffers are preferred when heavy
modification of character strings is involved (appending, inserting, deleting, modifying etc). Strings can be
obtained from string buffers. Since the StringBuffer class does not override the equals() method from the
Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in
String Buffer manipulations

Creation of StringBuffer's
StringBuffer Constructors

StringBuffer() //Default Constructor with 16 characters set


StringBuffer(String s) //String to String Buffer
StringBuffer(int initialCapacity) //StringBuffer’s with initial Capacity

public class StringBufferDemo {


public static void main(String[] args) {

// Examples of Creation of Strings


StringBuffer strBuf1 = new StringBuffer("Bob");
76

StringBuffer strBuf2 = new StringBuffer(100); //With capacity


100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity
16

System.out.println("strBuf1 : "+strBuf1);
System.out.println("strBuf2 capacity : "+strBuf2.capacity());
System.out.println("strBuf3 capacity : "+strBuf3.capacity());
}
}

Output

strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16

StringBuffer Functions

The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity()
Returns the current capacity of the String buffer.

2. length()
Returns the length (character count) of this string buffer.

3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the
index argument, is returned.

4. setCharAt(int index, char ch)


The character at the specified index of this string buffer is set to ch

5. toString()
Converts to a string representing the data in this string buffer

6. insert(int offset, char c)


Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded 'insert' methods which can be used based on the
application need.

7. delete(int start, int end)


Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str)


Replaces the characters in a substring of this StringBuffer with characters in the specified String.

9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str)


Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded 'append' methods which can be used based on
the application need.
77

11. setLength(int newLength)


Sets the length of this String buffer.

public class StringBufferFunctionsDemo {


public static void main(String[] args) {

// Examples of Creation of Strings


StringBuffer strBuf1 = new StringBuffer("Bobby");
StringBuffer strBuf2 = new StringBuffer(100); //With capacity
100
StringBuffer strBuf3 = new StringBuffer(); //Default Capacity
16

System.out.println("strBuf1 : "+strBuf1);
System.out.println("strBuf1 capacity : "+strBuf1.capacity());
System.out.println("strBuf2 capacity : "+strBuf2.capacity());
System.out.println("strBuf3 capacity : "+strBuf3.capacity());

System.out.println("strBuf1 length : "+strBuf1.length());


System.out.println("strBuf1 charAt 2 : "+strBuf1.charAt(2));
// A StringIndexOutOfBoundsException is thrown if the index is not
valid.
strBuf1.setCharAt(1, 't');

System.out.println("strBuf1 after setCharAt 1 to t is :


"+strBuf1);
System.out.println("strBuf1 toString() is :
"+strBuf1.toString());
strBuf3.append("beginner-java-tutorial");
System.out.println("strBuf3 when appended with a String :
"+strBuf3.toString());
strBuf3.insert(1, 'c');
System.out.println("strBuf3 when c is inserted at 1 :
"+strBuf3.toString());
strBuf3.delete(1, 'c');
System.out.println("strBuf3 when c is deleted at 1 :
"+strBuf3.toString());
strBuf3.reverse();
System.out.println("Reversed strBuf3 : "+strBuf3);
strBuf2.setLength(5);
strBuf2.append("jdbc-tutorial");
System.out.println("strBuf2 : "+strBuf2);

// We can clear a StringBuffer using the following line


strBuf2.setLength(0);
System.out.println("strBuf2 when cleared using setLength(0):
"+strBuf2);

}
}

Output

strBuf1 : Bobby
strBuf1 capacity : 21
78

strBuf2 capacity : 100


strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :
______________________________________________________________________________________
Java String Comparison

Compare String objects to determine Equality

String comparison can be done in many ways as shown below. Depending on the type of comparison you
need, each of them is used.

== Operator
equals method
compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables
point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false.
Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only
compares the references the 2 Strings are pointing to. The following Program would print “The strings are
unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision1 {


public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob");
String name3 = "Bob";
// 1st case
if (name1 == name2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1 == name3) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}

Comparing using the equals Method


79

The equals method is used when we need to compare the content of the text present in the String objects.
This method returns true when two String objects hold the same content (i.e. the same values). The
following Program would print “The strings are unequal” In the first case and “The strings are equal” in the
second case.

public class StringComparision2 {


public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob1");
String name3 = "Bob";
// 1st case
if (name1.equals(name2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1.equals(name3)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}

Comparing using the compareTo Method

The compareTo method is used when we need to determine the order of Strings lexicographically. It
compares char values similar to the equals method. The compareTo method returns a negative integer if the
first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It
returns a positive integer if the first String object follows the second string. The following Program would
print “name2 follows name1” In the first case and “name1 follows name3” in the second case.

public class StringComparision3 {


public static void main(String[] args) {
String name1 = "bob";
String name2 = new String("cob");
String name3 = "Bob";
// 1st case
if (name1.compareTo(name2) == 0){
System.out.println("The strings are equal.");
} else if(name1.compareTo(name2) < 0){
System.out.println("name2 follows name1");
}else{
System.out.println("name1 follows name2");
}
// 2nd case. Comparing Ascii Uppercase will be smaller
then Lower Case
if (name1.compareTo(name3) == 0){
System.out.println("The strings are equal.");
} else if(name1.compareTo(name3) < 0){
System.out.println("name3 follows name1");
}else{
System.out.println("name1 follows name3");
80

}
}

}
______________________________________________________________________
Java Date Utility

Java Date API

java.util.
Class Date

java.lang.Object
extended by java.util.Date

All Implemented Interfaces:


Cloneable, Comparable, Serializable

Direct Known Subclasses:


Date, Time, Timestamp

public class Date extends Object


implements Serializable, Cloneable, Comparable

The class Date represents a specific instant in time, with millisecond precision.

Java Date Source Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {

/* Add Day/Month/Year to a Date


add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/
public static final String DATE_FORMAT = "dd-MM-yyyy";
//See Java DOCS for different date formats
// public static final String DATE_FORMAT = "yyyy-MM-dd";

public static void addToDate(){


System.out.println("1. Add to a Date Operation\n");
SimpleDateFormat sdf = new
SimpleDateFormat(DATE_FORMAT);
81

//Gets a calendar using the default time zone and


locale.
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
// System.out.println("Todays date in Calendar Format :
"+c1);
System.out.println("c1.getTime() : "+c1.getTime());
System.out.println("c1.get(Calendar.YEAR): "
+ c1.get(Calendar.YEAR));

System.out.println("Todays date in Date Format : "+d1);


c1.set(1999,0 ,20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) :
"+c1.getTime());
c1.add(Calendar.DATE,20);
System.out.println("Date + 20 days is : "
+
sdf.format(c1.getTime()));
System.out.println();

System.out.println("-------------------------------------");
}

/*Substract Day/Month/Year to a Date

roll() is used to substract values to a Calendar object.


You specify which Calendar field is to be affected by the
operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.


roll() does the same thing except you specify if you want to roll up
(add 1)
or roll down (substract 1) to the specified Calendar field. The
operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in
the same
year while add() substract the YEAR field for the correct result. Hence
add()
is preferred even for subtraction by using a negative element.

*/

public static void subToDate(){


System.out.println("2. Subtract to a date Operation\n");

SimpleDateFormat sdf = new


SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20);
System.out.println("Date is : " +
sdf.format(c1.getTime()));

// roll down, substract 1 month


c1.roll(Calendar.MONTH, false);
82

System.out.println("Date roll down 1 month : "


+
sdf.format(c1.getTime()));

c1.set(1999, 0 , 20);
System.out.println("Date is : " +
sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : "
+
sdf.format(c1.getTime()));
System.out.println();

System.out.println("-------------------------------------");
}

public static void daysBetween2Dates(){


System.out.println("3. No of Days between 2 dates\n");
Calendar c1 = Calendar.getInstance(); //new
GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new
GregorianCalendar();
c1.set(1999, 0 , 20);
c2.set(1999, 0 , 22);
System.out.println("Days Between "+c1.getTime()+" and "
+ c2.getTime()+" is");
System.out.println((c2.getTime().getTime() -

c1.getTime().getTime())/(24*3600*1000));
System.out.println();

System.out.println("-------------------------------------");
}

public static void daysInMonth() {


System.out.println("4. No of Days in a month for a given
date\n");
Calendar c1 = Calendar.getInstance(); //new
GregorianCalendar();
c1.set(1999, 6 , 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int [] daysInMonths =
{31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println("Days in "+month+"th month
for year "+year+" is "+
daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();

System.out.println("-------------------------------------");
}

public static void validateAGivenDate() {


System.out.println("5. Validate a given date\n");
83

String dt = "20011223";
String invalidDt = "20031315";
String dateformat = "yyyyMMdd";
Date dt1=null , dt2=null;
try {
SimpleDateFormat sdf = new
SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println("Date is ok = " + dt1 + "(" +
dt + ")");
}
catch (ParseException e) {
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e) {
System.out.println("Invalid date");
}
System.out.println();

System.out.println("-------------------------------------");
}

public static void compare2Dates(){


System.out.println("6. Comparision of 2 dates\n");
SimpleDateFormat fm = new SimpleDateFormat("dd-MM-
yyyy");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.set(2000, 02, 15);


c2.set(2001, 02, 15);

System.out.print(fm.format(c1.getTime())+" is ");
if(c1.before(c2)){
System.out.println("less than "
+fm.format(c2.getTime()));
}else if(c1.after(c2)){
System.out.println("greater than "
+fm.format(c2.getTime()));
}else if(c1.equals(c2)){
System.out.println("is equal to "
+fm.format(c2.getTime()));
}
System.out.println();

System.out.println("-------------------------------------");
}

public static void getDayofTheDate() {


System.out.println("7. Get the day for a given date\n");
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat("EEEE");
try {
day = f.format(d1);
84

}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("The day for "+d1+" is "+day);
System.out.println();

System.out.println("-------------------------------------");
}

//Utility Method to find whether an Year is a Leap year or Not


public static boolean isLeapYear(int year){
if((year%100 != 0) || (year%400 == 0)){
return true;
}
return false;
}

public static void main(String args[]){


addToDate(); //Add day, month or year to a date field.
subToDate(); //Subtract day, month or year to a date
field.
daysBetween2Dates();
//The "right" way would be to compute the Julian day number of
//both dates and then do the subtraction.
daysInMonth();//Find the number of days in a month for a
date
validateAGivenDate();//Check whether the date format is
proper
compare2Dates(); //Compare 2 dates
getDayofTheDate();
}

Output

1. Add to a Date Operation

c1.getTime() : Sat Mar 31 10:47:54 IST 2007


c1.get(Calendar.YEAR): 2007
Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007
c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999
Date + 20 days is : 09-02-1999

-------------------------------------------------------
2. Subtract to a date Operation

Date is : 20-01-1999
Date roll down 1 month : 20-12-1999
Date is : 20-01-1999
Date minus 1 month : 20-12-1998

-------------------------------------------------------
3. No of Days between 2 dates
85

Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is
2

-------------------------------------------------------
4. No of Days in a month for a given date

Days in 6th month for year 1999 is 31

-------------------------------------------------------
5. Validate a given date

Unparseable date: "20031315"

-------------------------------------------------------
6. Comparision of 2 dates

15-03-2000 is less than 15-03-2001

-------------------------------------------------------
7. Get the day for a given date

The day for Sat Mar 31 10:47:54 IST 2007 is Saturday

-------------------------------------------------------
What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.


______________________________________________________________________________________
Java Swing Tutorial | Swing Examples

This site contains brief tutorials for java swing programming along with java swing examples and source
code.

Java Swing Introduction Tutorial

What is Java Swing ?

• A part of The Java Foundation Classes


• Swing consists of
Look and feel
Accessibility
Java 2D (Java 2 onwards)
Drag and Drop, etc
• Compiling & running programs

‘javac <program.java>’ && ‘java <program>’


Or JCreator / IDE
• if you do not explicitly add a GUI component to a container, the GUI component will not be
displayed when the container appears on the screen.
86

Swing, which is an extension library to the AWT, includes new and improved components that enhance
the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as
Servlets and Applets. It employs a model/view design architecture. Swing being 100% Java code makes it
more portable and more flexible than AWT.

Swing Model/view design: The "view part" of the MV design is implemented with a component object
and the UI object. The "model part" of the MV design is implemented by a model object and a change
listener object.

Swing is built on top of AWT. Swing is written entirely in Java, using AWT's lightweight component
support. In particular, unlike AWT, the architecture of Swing components makes it easy to customize both
their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add
Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton
and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You
could subclass the existing Swing UI, model, or change listener classes without having to reinvent the
entire implementation. Swing also has the ability to replace these objects on-the-fly.

• 100% Java implementation of components


• Pluggable Look & Feel
• Lightweight components

• Uses MVC Architecture

Model represents the data


View as a visual representation of the data
Controller takes input and translates it to changes in data

• Three parts

Component set (subclasses of JComponent)


Support classes
Interfaces

In Swing, classes that represent GUI components have names beginning with the letter J. Some
examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces
in Swing — twice as many as in AWT.

Java Swing class hierarchy

The class JComponent, descended directly from Container, is the root class for most of Swing's user
interface components.

Swing contains components that you'll use to build a GUI. I am listing you some of the commonly used
Swing components that are used in Java swing programs. To learn and understand these swing programs,
AWT Programming knowledge is not required.

Java Swing Examples

Below is a java swing code for the traditional Hello World program.
87

Basically, the idea behind this Hello World program is to learn how to create a java program, compile
and run it. To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or
you can use an IDE like Eclipse.

import javax.swing.JFrame;
import javax.swing.JLabel;

//import statements

//Check if window closes automatically. Otherwise add suitable code


public class HelloWorldFrame extends JFrame{

public static void main(String args[]){


new HelloWorldFrame();
}

HelloWorldFrame(){
JLabel jlbHelloWorld = new JLabel("Hello World");
add(jlbHelloWorld);
this.setSize(100, 100);
// pack();
setVisible(true);
}
}

Output

Note: Below are some links to java swing tutorials that forms a helping hand to get started with java
programming swing.

• JPanel is Swing's version of the AWT class Panel and uses the same default layout, FlowLayout.
JPanel is descended directly from JComponent.
• JFrame is Swing's version of Frame and is descended directly from that class. The components
added to the frame are referred to as its contents; these are managed by the contentPane. To add a
component to a JFrame, we must use its contentPane instead.
• JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified ,
maximized and layered.
• JWindow is Swing's version of Window and is descended directly from that class. Like Window,
it uses BorderLayout by default.
• JDialog is Swing's version of Dialog and is descended directly from that class. Like Dialog, it
uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy
including a contentPane, and it allows layered and glass panes. All dialogs are modal, which
means the current thread is blocked until user interaction with it has been completed. JDialog class
is intended as the basis for creating custom dialogs; however, some of the most common dialogs
are provided through static methods in the class JOptionPane.
• JLabel, descended from JComponent, is used to create text labels.
• The abstract class AbstractButton extends class JComponent and provides a foundation for a
family of button classes, including JButton.
• JTextField allows editing of a single line of text. New features include the ability to justify the
text left, right, or center, and to set the text's font.
• JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each
character entered can be replaced by an echo character. This allows confidential input for
passwords, for example. By default, the echo character is the asterisk, *.
88

• JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with
class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or
never have either the vertical or horizontal scrollbar;
• JButton is a component the user clicks to trigger a specific action.
• JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio
buttons can be associated as a group in which only one button at a time can be selected.
• JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and
it also displays its current state.
• JComboBox is like a drop down box. You can click a drop-down arrow and select an option from
a list. For example, when the component has focus, pressing a key that corresponds to the first
character in some entry's name selects that entry. A vertical scrollbar is used for longer lists.
• JList provides a scrollable set of items from which one or more may be selected. JList can be
populated from an Array or Vector. JList does not support scrolling directly, instead, the list must
be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined
border. JList actions are handled using ListSelectionListener.
• JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text
and an image.
• JToolbar contains a number of components whose type is usually some kind of button which can
also include separators to group related components within the toolbar.
• FlowLayout when used arranges swing components from left to right until there's no more space
available. Then it begins a new row below it and moves from left to right again. Each component
in a FlowLayout gets as much space as it needs and no more.
• BorderLayout places swing components in the North, South, East, West and center of a container.
You can add horizontal and vertical gaps between the areas.
• GridLayout is a layout manager that lays out a container's components in a rectangular grid. The
container is divided into equal-sized rectangles, and one component is placed in each rectangle.
• GridBagLayout is a layout manager that lays out a container's components in a grid of cells with
each component occupying one or more cells, called its display area. The display area aligns
components vertically and horizontally, without requiring that the components be of the same size.
• JMenubar can contain several JMenu's. Each of the JMenu's can contain a series of JMenuItem 's
that you can select. Swing provides support for pull-down and popup menus.
• Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many
items in a popup menu that exceeds the screen visible height.

Java Swing Projects

Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java
program source code.

Java Swing Address Book demonstrates how to create a simple free address book program using java
swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames,
JTextFields and Layout Manager (GridBagLayout).
__________________________________________________________________________
JDBC Tutorial

JDBC Introduction

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database
applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements
to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic
SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because
Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to
89

enable remote database access. You will learn how to create a table, insert values into it, query the table,
retrieve results, and update the table with the help of a JDBC Program example.

Although JDBC was designed specifically to provide a Java interface to relational databases, you may
find that you need to write Java code to access non-relational databases as well. This site teaches you
database programming with jdbc and java using a oracle Database

JDBC Architecture

Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change
database engines without changing database code.

JDBC Basics - Java Database Connectivity Steps

Before you can create a java jdbc connection to the database, you must first import the java.sql package.

1. Loading a database driver,

In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the
Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can
connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver
therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName(String
ClassName) method is "Class". Class is a class in java.lang package.

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other
driver
}
catch(Exception x){
System.out.println( "Unable to load the driver class!" );
}
2. Creating a oracle jdbc Connection

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.
DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC
drivers that are installed on the system. Its getConnection() method is used to establish a connection to a
database. It uses a username, password, and a jdbc url to establish a connection to the database and returns
a connection object. A jdbc Connection represents a session/connection with a specific database. Within the
context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can
have one or more connections with a single database, or it can have many connections with different
databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It
also contains methods to deal with transactions.

JDBC URL Syntax:: jdbc: <subprotocol>: <subname>


• Each driver has its own subprotocol
• Each subprotocol has its own syntax for the source

Example: For example, we're using the jdbc odbc subprotocol, so the DriverManager knows to use the
sun.jdbc.odbc.JdbcOdbcDriver.

try{
90

Connection dbConnection = DriverManager.getConnection(url,


"loginName", "Password")
}
catch( SQLException x ){
System.out.println( "Couldn't get connection!" );
}

3. Creating a jdbc Statement object,

Once a connection is obtained we can interact with the database. Connection interface defines methods
for interacting with the database via the established connection. To execute SQL statements, you need to
instantiate a Statement object from your connection object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.

Three kinds of Statements

Statement: Execute simple sql queries without parameters.


Statement createStatement()
Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements.

Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call
statements.

4. Executing a SQL statement with the Statement object, and returning a java ResultSet.

Statement interface defines methods that are used to interact with database via the execution of SQL
statements. The Statement class has three methods for executing statements: executeQuery(),
executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For
statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a
table, alter a table, or drop a table are all examples of DDL statements and are executed with the method
executeUpdate. execute() executes an SQL statement that is written as String object.

ResultSet provides access to a table of data generated by executing a Statement. The table rows are
retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method
is used to successively step through the rows of the tabular results.

ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.

Test JDBC Driver Installation


import javax.swing.JOptionPane;

public class TestJDBCDriverInstallation_Oracle {


91

public static void main(String[] args) {


StringBuffer output = new StringBuffer();
output.append("Testing oracle jdbc driver installation
\n");
try {
String className =
"sun.jdbc.odbc.JdbcOdbcDriver";
Class driverObject =
Class.forName(className);
output.append("Driver :
"+driverObject+"\n");
output.append("JDBC Driver Installation
Successful");
JOptionPane.showMessageDialog(null,
output);
} catch (Exception e) {
output = new StringBuffer();
output.append("JDBC Driver Installation
FAILED\n");
// JDBC Driver installation Failed
JOptionPane.showMessageDialog(null, output);
System.out.println("Failed: JDBC Driver Error: " +
e.getMessage());
}
}
}

Test JDBC Connection, JDBC Driver Name and Version

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCDriverInformation {


static String userid="scott", password = "tiger";
static String url = "jdbc:odbc:bob";
static Connection con = null;
public static void main(String[] args) throws Exception {
Connection con = getOracleJDBCConnection();
if(con!= null){
System.out.println("Got Connection.");
DatabaseMetaData meta = con.getMetaData();
System.out.println("Driver Name :
"+meta.getDriverName());
System.out.println("Driver Version :
"+meta.getDriverVersion());

}else{
System.out.println("Could not Get Connection");
}
}
92

public static Connection getOracleJDBCConnection(){

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,userid,
password);
} catch(SQLException ex) {
System.err.println("SQLException: " +
ex.getMessage());
}

return con;
}

}
_______________________________________________________________________

Interview questions on Java

What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means
passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any
platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?
93

public- main(..) is the first method called by java environment when a program is executed so it has to
accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this
method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for
string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in
the same memory location. It is possible for two String objects to have the same value, but located in
different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is
provided by the Object class and can be overridden. The default implementation returns true only if the
object is compared with itself, which is equivalent to the equality operator == being used to compare
aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects,
value equality means that they contain the same character sequence. For the Wrapper classes, value equality
means that the primitive values are equal.

public class EqualsTest{

public static void main(String[] args){


String s1 = "abc";
String s2 = s1;
String s5 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
// if we remove the brackets around "s1 == s5' it gives a different result.
System.out.println("== comparison : " +(s1 == s5));
System.out.println("== comparison : " +(s1 == s2));
System.out.println("Using equals method : " +s1.equals(s2));
System.out.println("== comparison : " +s3 == s4);
94

System.out.println("Using equals method : " +s3.equals(s4));


}
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main
method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own
implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent,
can be downloaded to a browser at runtime, and does not require any Oracle software on the client side.
This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP
port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final
keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant


o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not
be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the
compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method
95

can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used
in exception handling and will be executed whether or not an exception is thrown. For example, closing of
open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful
capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to
tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to
following reasons:
* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString);

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should
occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop
should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political,
or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.


96

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows
well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation
guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not
work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in
the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used
as a general category for different types of actions. The specific action is determined by the exact nature of
the situation.

Polymorphism exists in three distinct forms in Java:


• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the
object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting


97

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down
the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords
are for allowing privileges to parts of a program such as functions and variables. These are:
• Public: accessible to all classes
• Protected: accessible to the classes within the same package and any subclasses.
• Private: accessible only to the class to which they belong
• Default: accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

What is the difference between static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each
object will share a common copy of the static variables i.e. there is only one copy per class, no matter how
many objects are created from it. Class variables or static variables are declared with the static keyword in a
class. These are declared outside a class and stored in static memory. Class variables are mostly used for
98

constants. Static variables are always called by the class name. This variable is created when the program
starts and gets destroyed when the programs stops. The scope of the class variable is same an instance
variable. Its initial value is same as instance variable and gets a default value when its not initialized
corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than
any object of the class and doesn't apply to an object or even require that any objects of the class have been
instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static
methods are attached to a class, not an object. A static method in a superclass can be shadowed by another
static method in a subclass, as long as the original method was not declared final. However, you can't
override a static method with a non-static method. In other words, you can't change a static method into an
instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the
&& operator is a short cut operator. When an expression involving the && operator is evaluated, the first
operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the
first operand evaluates to false, the evaluation of the second operand is skipped.

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

What is the difference between declaring a variable and defining a variable?

In declaration we only mention the type of the variable and its name without initializing it. Defining means
declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String
s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object
reference itself is passed by value and so both the original reference and parameter copy both refer to the
same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a
single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be
encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a
protective wrapper that prevents code and data from being arbitrarily accessed by other code defined
outside the wrapper.

What do you understand by a variable?

Variable is a named memory location that can be easily referred in the program. The variable is used to hold
the data and it can be changed during the course of the execution of the program.
99

What do you understand by numeric promotion?

The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that
integral and floating-point operations may take place. In the numerical promotion process the byte, char,
and short values are converted to int values. The int values are also converted to long values, if necessary.
The long and float values are converted to double values, as required.

What do you understand by casting in java language? What are the types of casting?

The process of converting one data type to another is called Casting. There are two types of casting in Java;
these are implicit casting and explicit casting.

What is the first argument of the String array in main method?

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by
default is the program name. If we do not provide any arguments on the command line, then the String
array of main method will be empty but not null.

How can one prove that the array is not null but empty?

Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have
thrown a NullPointerException on attempting to print array.length.

Can an application have multiple classes having main method?

Yes. While starting the application we mention the class name to be run. The JVM will look for the main
method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple
classes having main method.

Can I have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is already defined in the class.

Вам также может понравиться