JavaBy TajendarAroraFinal PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 198

Core JAVA

(Handouts)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 1


Modules Of The Course
1.  Fundamentals of OOPS 4

2.  An overview of Java 7

 Setting up Environment
 Path and Class Path in JAVA
3.  First java program 18

4.  Data Types, variables, and Arrays 23

5.  Operators 33

6.  Decision making & looping – Control 41


Statements
7.  Classes & Methods 52

8.  Inheritance 60

9  Understanding STATIC 73

10  Final Keyword 76

11.  Abstract Class 80

12.  Inner class 86

13.  Wrapper Classes 89

14.  Packages and Object Class 92

15.  String Handling 100

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 2


16.  Exception Handling 109

17.  Multithreading 113

18.  APPLET Programming 119

19.  JAVA IO 126

20.  Java reflection 145

21.  Java Collection framework 153


22.  Java RegX 169

23  Generics 175

24.  Internationalization and Localization 180


in Java

25.  Serialization 185

26  Advanced Topics 189

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 3


Chapter-1
Fundamentals of OOPS

OOPs allow us to decompose a problem into a number of entities called


Objects and then build data and functions (known as methods in java).
The combination of data and methods make up an object.

 Object - Oriented Programming is an approach that provides a way of


modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of
such modules on demand.
(This means that an object is considered to be a partitioned area of computer
memory that stores data and a set of operations that can access the data.
Since the memory partitions are independent, the objects can be used in a
variety of different programs without modifications.)

 Java is an object - oriented language. It enables us not only to


organize our program code into logical units called objects but
also to take advantage of encapsulation, inheritance, and
polymorphism.

Basic concepts of Object-oriented Programming

1. Objects & Classes

 Objects are the basic runtime entities in an object- oriented system.


They may represent a person, a place or any item that the program may
handle.

(An object takes up space in the memory and has an associated address,
like structure in C.)

 A lass a e thought of as a data t pe a d a o je t as a aria le


of that data type. Classes are user-defined data types and behave like
the built-in types of a programming language.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 4


(A class is thus a collection of objects of similar type. For example, mango,
apple and orange are members of the class fruit.)

If fruit has been defined as a class, then the statement


Fruit mango*
will create an object mango belonging to the class fruit.

2. Data Abstraction & Encapsulation

 The wrapping up of data and methods into a single unit (called class) is
known as Encapsulation.

(The data is not accessible to the outside world and only those methods, which
are wrapped in the class, can access it)

One way to think about Encapsulation is as a protective wrapper that prevents


the code and data from being arbitrarily accessed by other code defined
outside the wrapper. Access to the code and data inside the wrapper is tightly
controlled through a well - defined interface.
Abstraction refers to the act of representing essential features without
including the background details or explanations.

(Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and methods that operate on these
attributes.)

3.Inheritance

 Inheritance is the process by which objects of one class acquire the


properties of objects of another class. Inheritance supports the concept
of hierarchical classification.

(The principle behind this sort of division is that each derived class shares
common characteristics with the class from which it is derived)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 5


4.Polymorphism

 Polymorphism is another important OOP concept. Polymorphism means


the ability to take more than one form.

(For example, consider the operation of addition. For two numbers, the
operation will generate a sum. If the operands are strings, then the operation
would produce a third string by concatenation.)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 6


Chapter-2
An Overview of Java

Java is high level programming language introduced by Sun Microsystems in


June 1995. Java is an object oriented language built upon C & C++, It derived its
object oriented features from C++.

The Java language has undergone several changes since JDK 1.0 (1996) and
now JSE 8 is latest.
*jdk- Java Development Kit
*JSE- Java Standard Ediiton
JAVA Versions
 JDK Alpha and Beta
 JDK 1.0
 JDK 1.1
 J2SE 1.2
 J2SE 1.3
 J2SE 1.4
 J2SE 5.0
 Java SE 6
 Java SE 7
 Java SE 8

Why Java?

 Object-oriented
 Platform independent
 Built-in support for multi-threading, socket communication and
memory management
 Supports Web based applications (Applet, Servlets and JSP)
 Vast library of predefined objects and operations
 Secure

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 7


JAVA’“ MAGIC: the Byte Code

Usually a computer language is either compiled or interpreted. Java combines


both these approaches thus making Java a two-stage system.

(First, java compiler translates source code into what is known as bytecode
instructions. Bytecodes are not machine instructions and therefore, in the
second stage, Java interpreter generates machine code that can be directly
executed by the machine that is running the Java program.)

Bytecode is a highly optimized set of instructions designed to be executed by


the Java run-time system, which is called the Java Virtual Machine (JVM). That
is, in its standard form, the JVM is an interpreter for bytecode.

(However, the fact that a Java program is executed by the JVM helps solves the
major problems associated with downloading programs over the internet. That
means , JVM is an interpreter for bytecode.)

Translating a Java Program into bytecode helps makes it much easier to run a
program in a wide variety of environments.

THE REASON IS STRAIGHT FORWARD: only the JVM needs to be implemented


for each platform.

Once the run- time package exists for a given system, any java program can
run on it.

(The fact that a java program is interpreted also helps to make it secure.
Because the execution of every program is under the control of the JVM, the
JVM can contain the program and prevent it from generating side effects
outside of the system.)

Java Features

 Compiled and Interpreted


 Platform- Independent and Portable
 Object- oriented

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 8


 Robust and Secure
 Distributed
 Multithreaded and Interactive
 Simple small and familiar

Platform Independent and Portable- the most significant contribution of java


over other languages is its portability. Java programs can be easily moved from
one computer system to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will not force
any changes in Java programs.

Java ensures portability in two ways. First, Java compiler generates bytecode
instructions that can be implemented on any machine. Secondly, the sizes of
the primitive data types are machine independent.

Different editions of Java


 J2SE(Java Platform, Standard Edition)
Also known as Core Java, this is the most basic and standard version of
Java
 J2EE(Java Platform, Enterprise Edition)

The Enterprise version of Java has a much larger usage of Java, like
development of web services, networking, server side scripting and other
various web based applications. J2EE uses many components of J2SE, as well
as, has a e features of it s o like Servlets, JavaBeans, Java Message
Services, adding a whole new functionalities to the language.J2EE uses HTML,
C““, Ja a“ ript et ., so as to reate e pages a d e ser i es. It s also o e
of the most widely accepted web development standard.
 J2ME(Java Platform, Micro Edition)

This version of Java is mainly concentrated for the applications running on


embedded systems, mobiles.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 9


 JavaFX is another such edition of Java technology, which is now merged
with J2SE 8.It is mainly used, to create rich GUI (Graphical User
Interface) in Java apps.

 PersonalJava was another edition, which was not deployed much, as its
function was fulfilled by further versions of J2ME. Made to support
World Wide Web (and Java applets) and consumer electronics.

Environment Setup for JAVA


Understand Path and Classpath in Java

Path Variable

Path variable is set for providing path for all java tools like java, javac, javap,
javah, jar, appletviewer which are use in java programming. These all tools are
available in bin folders so we set path upto bin folders.

Classpath Variable

Classpath variable is set for providing path for predefined java classes which
is used in our application. All classes are available in lib/rt.jar so we set
classpath upto lib/rt.jar.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 10


JDK Folder Hierarchy

Why set path ?


The following programming error is general for all java programmers when
they compile any java program.
Javac is a tool which is available in bin folder so you must set the PATH upto
bin folder. In a binfolder all tools are available like javap, javah, jar, javac,
java, appletviewer etc. These all tools are used for different-different
purpose.
'javac' is not recognized as an internal or external command, operable
program or batch file.
When you get this type of error, then your operating system cannot find the
java compiler (javac).
To solve this error you need to set the PATH variable.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 11


set the path and classpath
Go on my computer icon and right click, after that click on properties option.

Now click on advance setting

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 12


Click on advance

Click on Advance variables

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 13


Click on new button which is below the first box.

Now one dilog box is appear, now ignore this but do not close.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 14


Now open my computer open c:/ > Programs Files > java > java1.6.0 > bin copy this path

Now come back on previous open dilogbox and write variable


name 'path' and for variable value paste all copied path upto bin folder. Put
.; at the end. It (.) select all the tools from bin folder.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 15


Now open my computer open c:/ > Programs Files > java > java1.6.0 > jre >
lib > rt.jar copy this path

Note: rt.jar is available in lib folder this jar files contains all classes of jdk.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 16


Now again come back on Environment variable dilogbox and click on new.
now one box is open and write path variable as 'classpath' and for variable
value paste all copied path upto rt.jar. Put .; at the end. It (.) select all the
classes from lib folder.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 17


Chapter-3
First Java Program

The best way to learn a new language is to write a few simple example
programs. We begin with a program that prints a line of text as output.

 SIMPLE JAVA PROGRAM


class SampleOne
{
public static void main(String args[])
{
“ ste .out.pri tl Ja a is etter tha C++. ;
}
}

Entering the program:

The first thing that you must learn about the java is that the name you give to a
source file is very important. For example, the name of the source file should
be SampleOne.java. In java, a source file is officially called compilation unit.
The java compiler requires that a source file use the .java filename extension.

As you can see by looking at the program, the name of the class defined by the
program is also SampleOne. This is not co-incidence.

In java, all code must de reside inside a class. By convention, the name of that
class should match the name of the file that holds the program.
You should also make sure that the capitalization of the filename matches the
class name. However, this convention makes it easier to maintain and organize
your programs.

Class Declaration:
The first line
Class SampleOne

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 18


Declares a class, which is an object oriented construct. class is a keyword and
declares that a new class definition follows. SampleOne is a Java identifier that
specifies the name of the class to be defined.

Opening Brace:
E er lass defi itio i ja a egi s ith a ope i g ra e { and ends with a
at hi g losi g ra e } .

The main Line:

The third line


public static void main(String args[])
defines a method named main. Conceptually, this is similar to the main()
function in C. Every java application program must include the main()method.
This is the starting point for the interpreter to begin the execution of the
program.
A java application can have any number of classes but only one of them must
include a main method to initiate the execution.
(# Note that Java applets will not use the main method at all.)
This line contains a number of keywords, public, static and void.

Public:
The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.

Static:
It declares this method as one that belongs to the entire class and not a part of
any objects of the class. The main must always be declared as static since the
interpreter uses this method before any objects are created.

Void:
The type modifier void states that the main method does not return any value.
The Output file:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 19


“ ste .out.pri tl Ja a is etter tha C++ ;
This is similar to the printf() statement of C. Since Java is a true object-
oriented language, every method must be part of an object. The println
method is a member of the out object, which is a static data member of
System class.
This line prints the string
Java is better than C++.

Compiling the Program:


To compile the SampleOne program, execute the compiler, javac,specifying
the name of the source file on the command line, as shown here:

C : \>javac SampleOne.java

The javac compiler creates a file called SampleOne.class that contains the
bytecode version of the program. As discussed earlier, the java bytecode is the
intermediate representation of your program that contains instructions the
Java interpreter will execute. Thus, the output of javac is not code that can be
directly executed.
To actually run the program, you must use the Java interpreter, called
java. To do so, pass the class name SampleOne as a command-line argument,
as shown here:

C : \>java SampleOne

When the program is run, the following output is displayed:

Ja a is etter tha C++

 Second Short program

Perhaps no other concept is more fundamental to a programming language


than that of a variable. As we probably know, avariableis a named memory

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 20


location that may be assigned a value by your program. The value of a variable
may be changed during the execution of the program.

class Example2
{
public static void main(String args[])
{
int num;
num = 100;
“ ste .out.pri tl this is u : + u ;
num=num * 2;
“ ste .out.pri t the alue of u * is ;
System.out.println(num);
}
}

When you run this program, you will see the following output:
This is num : 100
The value of num * 2 is 200

The first new line in the program is shown here:


int num;

This line declares an integer variable called num. Java requires that variables
be declared before they are used.

In the program, the line


num = 100;
assigns to num the value 100. In java, the assignment operator is a single
equal sign.

C. 2. Java Tokens

Most statements contain expressions, which describe the actions carried out
on data. Small individual units in a program are known as tokens. The
compiler recognizes them for building up expressions and statements.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 21


Java programs are a collection of whitespace, identifiers, comments, literals,
operators, separators, and keywords.

Whitespace – Java is a free - from language. This means that you do not need
to follow any special indentation rules. In java, whitespace is a space,tab, or
newline.

Identifiers –Identifiers are used for class names, method names, and variable
names. An identifier may be descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollar – sign characters. Again , Java is
case- sensitive, (so VALUE is a different identifier than Value ).

Some examples of valid identifiers are:


AvgTemp count a4 $test
Invalid variable names include:
2count high – temp Not/ok

Literals - A constant value in java is created by using a literal representation


of it.
. X This is a test
The first literal is integer, the next is floating- point value, the third is a
character constant, and the last is string.
A literal can be used anywhere a value of its type is allowed.

Separators – In java, there are few characters that are used as separators.
The ost o o l used separator i ja a is the se i olo , it is used to
terminate statements.

Keywords – There are 49 keywords currently defined in the java language.


These keywords combined with the syntax of the operators and separators,
from the definition of the java language.
abstract continue goto
package default if this

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 22


Chapter-4
Data Types, Variables And Arrays

A programming language is designed to process certain kinds of data consisting


of numbers, characters and strings and to provide useful output known as
information.

The task of processing data is accomplished by executing a sequence of


instructions constituting a program. These instructions are formed using
certain symbols and words according to some rigid rules known as syntax rules.
Like any other language, java has its own vocabulary and grammar.

Data Types
Every variable in java has a data type. Data types specify the size and type of
values that can be stored. Java language is rich in its data types. The variety of
data types available allows the programmer to select the type appropriate to
the needs of the application.

Java defines eight simple types of data: byte, short, int, long, char, float,
double, and Boolean.
These can be put in four groups:
 Integer: this group includes byte, short, int, and long, which are for
whole valued signed numbers.
 Floating point numbers: this group includes float, and double,
which represent numbers with fractional precision.
 Character: this group includes char, which represents symbols in a
character set, like letters and numbers.
 Boolean: this group includes Boolean, which is a special type for
representing true/false values.

Integer types:
Integer types can hold whole numbers such as 123,-96, 578. The size of the
values that can be stored depends on the integer data type we choose. Java
supports four types of integers: byte, short, int, and long. Java does not

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 23


support the concept of unsigned types and therefore all java values are signed
meaning they can be positive or negative.

Name width(bits) size


long 64 8 bytes
int 32 4 bytes
short 16 2 bytes
byte 8 1 byte

Floating- point types:


Integer types can hold only whole numbers and therefore we use another type
known as floating point type to hold numbers containing fractional parts.
There are two kinds of floating point storage in java:
The float type values are single - precision numbers while the double type
represents double – precision numbers.
Name size width(in bits)
Float 4 bytes 32
Double 8 bytes 64

Here is a short program that uses double variables to compute the area of a
circle
// compute the area of a circle.
Class Area
{
public static void main(String args[])
{
double pi,r,a;
r=10.8;
pi=3.1416;
a=pi*r*r;
“ ste .out.pri tl Area of ir le is + a );
}
}

Character type:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 24


In order to store character constants in memory, java provides a character
data type assumes a size of 2 bytes but, basically , it can hold only a single
character.
Boolean type:
Boolean type is used when we want to test a particular condition during the
execution of the program. There are only two values that a Boolean type can
take: true or false. Boolean type is denoted by the keyword Boolean and uses
only one bit of storage.

Variables
The variable is the basic unit of storage in a java program. A variable is defined
by the combination of an identifier, a type, and an optional initializer.

Declaring a variable
In java, all variables must be declared before they can be used. The basic form
of a variable declaration is shown here.
type aria le , aria le ……….. aria le N:

Declaration does three things:


1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration ( in the program ) decides the scope of the
variable.

A variable must be declared before it is used in the program. A variable can be


used to store a value of any data type. That is, the name has nothing to do with
the type.
Variables are separated by commas. A declaration statement must end with a
semicolon.
Some valid declarations are:
int count;
float x,y;
double pi;

Giving Values to Variables


A variable must be given a value after it has been declared but before it is used
in an expression. This can be achieved in two ways:
1. By using an assignment statement

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 25


2. By using a read statement

1. Assignment Statement
A simple method of giving value to a variable is through the assignment
statement as follows:
type variableName = value;
Examples:
int finalValue = 100;
char es = ;
double total = 75.36;
The process of giving initial values to variables is known as the initialization.
The ones that are not initialized are automatically set to zero.

2. Read statement
We may also give the values to variables interactively through the keyboard
using the readLine() method .
The readLine() method ( which is invoked using an object of the class
DataInputStream ) reads the input from the keyboard as a string which is then
converted to the corresponding data type.

Arrays
An array is a group of like- typed variables that are referred to by a
common name. Arrays of any type can be created and may have one
or more dimensions.
A specific element in an array is accessed by its index.
(# if you are familiar with C/C++ , be careful. Arrays in java work differently than they do in
those language.)
 One - dimensional Arrays
A one – dimensional array is, essentially ,a list of like – typed variables. To
create an array, you first must create an array variable of the desired type.
The general form of one – dimensional array declaration is:
type var-name[ ];
Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for
the array determines what type of data the array will hold. For example, the
following declares an array named month_days ith the t pe arra of i t :
int month_days[ ] ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 26


Although this declaration establishes the fact that month_days is an array
variable, no array actually exists.
In fact, the value of month_days is set to null, which represents an array with
no value. To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days.

new is a special operator that allocates memory. The general form of new as
it applies to one – dimensional array appears as follows:

array- var = new type[size];

Here, type specifies the type of data being allocated, size specifies the number
of elements in the array, and array-var is the array variable that is linked to
the array. That is, to use new to allocate an array, you must specify the
number of elements to allocate.

month_days = new int[12];

After this statement executes, month_days will refer to an array of 12


integers.
Putting together all the pieces, here is a program that creates an array of the
number of days in each month.
// demonstrate a one dimensional array.
class Array
{
public static void main(String args[])
{
int month_days [ ] ;
month_days = new int [12];
month_days [0] = 31;
month_days [1] = 28;
month_days [2] = 30;
month_days [3] = 31;
month_days [4] = 30;
month_days [5] = 31;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 27


month_days [6] = 30;
month_days [7] = 31;
month_days [8] = 30;
month_days [9] = 31;
month_days [10] = 30;
month_days [11] = 31;
“ ste .out.pri tl April has + o th_da s [ ]+ da s ;
}
}

After execution: When you run this program, it prints the number of days in
April. Java array indexes start with zero, so the number of days in April is
month_days[3] or 30.

 It is possible to combine the declaration of the array variable with the


allocation of the array itself, as shown here:

int month_days [ ] = new int [12];

Here is one more example that uses a one – dimensional array. It finds the
average of a set of numbers.

// Average an array of values.

class Average
{
public static void main(String args[ ])
{
double nums [ ]= { 10.1, 11.2, 12.3, 13.4, 14.5 };
double result = 0;
int i ;

for( i=0; i < 5; i++)


result = result + num [i] ;

“ ste .out.pri tl A erage is + result / ;


}
}
 Multi – dimensional Array

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 28


In java, multi – dimensional arrays are actually arrays of arrays. To declare a
multidimensional array variable, specify each additional index using another
set of square brackets.

The following declares a two – dimensional array variable called twoD.


int twoD [ ] [ ] = new int [4] [5] ;
this allocates a 4 by 5 array and assigns it to twoD.
Left index [4] = row , right index [5] = column
The following program numbers each element in the array from left to right,
top to bottom, and then displays these values:

// demonstrate a two- dimensional array.


class TwoDArray
{
public static void main(String args[ ])
{
int twoD [ ] [ ]= new int [4] [5];
int i , j , k = 0;

for ( i = 0 ; i < 4 ; i ++)


for ( j = 0; j <5 ; j ++)
{
twoD [i] [j]= k;

for ( i = 0 ; i < 4 ; i ++)


{
for ( j = 0; j <5 ; j ++)
“ ste .out.pri t t oD [i] [j] + ;
System.out.println() ;
}
}
}

This program generates the following output:


0 1 2 3 4
5 6 7 8 9

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 29


10 11 12 13 14
15 16 17 18 19

# when you allocate memory for a multidimensional array, you need only
specify the memory for the first ( left most ) dimension. You can allocate the
remaining dimensions separately. For example, this following code allocates
for the first dimension of twoD when it is declared. It allocates the second
dimension manually.

int twoD [ ] [ ] = new int [4] [ ] ;


twoD [0] = new int [5] ;
twoD [1] = new int [5] ;
twoD [2] = new int [5] ;
twoD [3] = new int [5] ;

 The following program creates a two- dimensional array in which the


sizes of the second dimension are unequal.

// Manually allocate differing size second dimensions.

Class TwoDAgain
{
public static void main (String args[ ])
{
int twoD [ ] [ ] = new int [4] [ ] ;
twoD [0] = new int [1] ;
twoD [1] = new int [2] ;
twoD [2] = new int [3] ;
twoD [3] = new int [4] ;

int i , j , k = 0 ;

for ( i = 0 ; i< 4 ; i ++)


for ( j =0; j < i +1 ; j++)
{
twoD [i] [j] = k ;
k ++ ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 30


}

for ( i = 0 ; i <4 ; i ++ )
{
for ( j = 0; j< i + 1 ; j ++)
“ ste .out.pri t t oD [i] [j] + ;
System.out.println() ;
}
}
}

This program generates the following output :


0
1 2
3 4 5
6 7 8 9

 Alternative Array Declaration Syntax:


There is a second form that may be used to declare an array :
type [ ] var – name ;
Here, the square brackets follow the type specifier , and not the name of the
array variable. For example, the following two declarations are equivalent:

int a1 [ ] = new int [3] ;


int a2 [ ] = new int [3] ;

The following declarations are equivalent:


char twod1 [ ] [ ] = new char [3] [4] ;
char [ ] [ ] twod2 = new char [3] [4] ;

This alternative declaration form is included as a convenience, and is also


useful when specifying an array as a return type for a method.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 31


For Each Loop in Array
Since JDK 1.5 introduced a new for loop known as foreach loop or
enhanced for loop, which enables you to traverse the complete array
sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList)
{ System.out.println(element);
}}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 32


Chapter-5
Operators

Java provides a rich operator environment. Most of its operators can be


divided into the following groups:
1. Arithmetic
2. Bitwise
3. Relational

Java also defines some additional operators that handle certain special
situations.

Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way
that they are used in algebra. The following table lists the arithmetic operators:

Operator Result
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

1) The Basic Arithmetic Operators: the basic arithmetic operations –


addition, subtraction, multiplication, and division, all behave as you
would except for all numeric types.

The following simple example program demonstrates the arithmetic


operators.
// Demonstrates the basic arithmetic operations
class BasicMath

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 33


{
public static void main (String args [ ])
{
//arithmetic using integers
“ ste .out.pri tl I teger Arith eti ;
int a = 1 + 1 ;
int b = a* 3 ;
int c = b/ 4 ;
int d = c – a ;
int e = -d ;
“ ste .out.pri tl a = + a ;
“ ste .out.pri tl = + ;
“ ste .out.pri tl = + ;
“ ste .out.pri tl d = + d ;
}
}

When you run this program , you will see the output:
Integer Arithmetic
a = 2
b = 6
c =1
d = -1
e =1

2) The Modulus Operator: the modulus operator, % returns the


remainder of a divisionoperation. It can be applied to floating – point
types as well as integer types.
// demonstrate the % operator
class Modulus
{
public static void main( String args[ ])
{
int x = 42 ;
double y = 42.25 ;

“ ste .out.pri tl od = + % ;
“ ste .out.pri tl od = + % ;
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 34


}

When you run this program you will get the following output :
x mod10 = 2
y mod 10 = 2.25

3) Arithmetic Assignment Operators: Java provides special operators


that can be used to combine an arithmetic operation with an
assignment.

For example, this statement:


a = a + 4;
In java , you can rewrite this statement as shown here,
a += 4 ;

This version uses the += assignment operator. Both statements perform


thesame action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as a %= 2 ;
In this case, the %= obtains the remainder of a/2 and puts that result back
into a.
Here is a sample program several assignment operations.
// demonstrate several assignment operators
class OpEquals
{
public static void main (String args [ ])
{
int a = 1 ;
int b = 2 ;
int c = 3 ;
a += 5 ;
b *=4 ;
c += a*b ;
c %= 6 ;
“ ste .out.pri tl a = + a ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 35


“ ste .out.pri tl = + ;
“ ste .out.pri tl = + ;
}
}
The output of this program is shown below,
a=6;
b=8;
c=3;

4) Increment and Decrement: The ++ and -- are ja a s i re e t a d


decrement operators.
The increment operator increases its operand by one. The decrement
operator decreases its operand by one.
For example,
x = x + 1 ; can be rewritten like this by use of the increment operator. x ++ ;
similarly, this statement ,
x = x – 1 ; is equivalent to x -- ;
These operators are unique in that they can appear both in postfix form,
where they follow the operand , and in prefix form, where they precede the
operand.
x = 42 ;
y = ++ x ;
In this case, y is set to 43 as you would expect, because the increment occurs
before x is assigned to y.
Thus, the line y = ++x ; is the equivalent to these two statements:
x=x+1;
y=x;
however, when written like this,
x =42 ;
y = x++ ;
The value will be 42 for y, i.e. y= 42. Of course, in both cases x is set to 43.
Here,
The line y =x ++; is the equivalent of these statements:
y=x;
x = x +1 ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 36


The following program demonstrates the increment operator.
// demonstrate ++
class IncDec
{
public static void main(String args [ ])
{
int a = 1 ;
int b = 2 ;
int c ;
int d ;
c = ++ b ;
d= a ++ ;
c ++;
“ ste .out.pri tl a = +a ;
“ ste .out.pri tl = + ;
“ ste .out.pri tl = + ;
Syste .out.pri tl d = +d ;
}
}
The output of this program follows:
a=2
b=3
c=4
d=1

Bitwise Operators
Java defines several bitwise operators which can be applied to the integer
types, long, int, short, char, and byte. These operators act upon the
i di idual s its of their opera ds. The are su arized i the follo i g ta le:

Operator Result
~ Bitwise unary NOT
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
>> shift right
>>> shift right zero fill

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 37


<< shift left
>>= shift right assignment
>>>= shift right zero fill assignment
<<= shift left assignment

1) The left shift


The left shift operator, << , shifts all of the bits in a value to the left of a
specified number of times. It has this general form:
Value << num
Here, num specifies the number of positions to the left- shift the value in
value. That is, the <<moves all of the bits in the specified value to the left by
the number of bit positions specified by num.For each shift left, the high –
order bit is shifted out, and a zero is brought in on the right.
2) The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times. Its general form is shown here:
value >>num
Here, num specifies the number of positions to the right - shift the value in
value. That is, the >>moves all of the bits in the specified value to the right by
the number of bit positions specified by num.

3) Bitwise Operator Assignments

All of the binary bitwise operators have a shorthand form similar to that of the
algebraic operators, which combines the assignment with the bitwise
operation.
For example, the following two statements, which shift the value in a right by
four bits, are equivalent.
a = a >> 4;
a >>= 4;

Relational Operators

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 38


The relational operators determine the relationship that one operand has to
the other. Specifically, they determine equality and ordering.

The relational operators are


== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The outcome of these operations is a boolean value.
int a = 4;
int b = 1;
boolean c = a < b;
In this case, the result of a<b (which is false) is stored in c.
If you are coming from a C/C++ background, please note the following. In
C/C++,
These types of statements are very common:
int d;
// ...
if(!d) ... // Valid in C/C++
if(d) ... // but not in Java.
In Java--- d should be true /false

Assignment Operator

The assignment operator is the single equal sign, =. The assignment operator
works in Java much as it does in any other computer language.
var = expression;
Here, the type of var must be compatible with the type of expression. Others
are +=,-=,*=,/=,%=.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 39


The ? Operator
Java includes a special ternary (three-way) operator that can replace certain
types ofif-then-else statements. This operator is the ?, and it works in Java
much like it doesin C, C++, and C#. It can seem somewhat confusing at first, but
the ? can be used veryeffectively once mastered.

Syntax

expression1 ? expression2 : expression3

for example
int age=18;
“tri g sg=age>= ? Adult : Not Adult ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 40


Chapter-6
Decision Making & Looping

CONTROL STATEMENTS

A programming language uses control statements to cause the flow of


execution to advance and branch on changes to the state of a program.
Java program control statements can be put into the following categories:
selection, iteration, and jump.

(Selection statements allow your program to choose different paths of


execution based upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more
statements.
Jump statements allow your program to execute in a non-linear fashion.)

A java program is a set of statements, which are normally executed


sequentially in the order in which they appear. However, in practice, we have a
number of situations, where we may have to change the order of execution of
statements based on certain conditions. (This involves a kind of decision making to
see whether a particular condition has occurred or not and then direct the computer to
execute certain statements accordingly).

When a program breaks the sequential flow and jumps to another part of the
code, it is known as branching. When the branching is based on a particular
condition, it is known as conditional branching. If branching takes place
without any decision , it is known as unconditional branching.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 41


JAVA `S SELECTION STATEMENTS

Java supports two selection statements : if and switch. These statements allow
ou to o trol the flo of our progra s e e utio ased upo o ditio s
known only during run time.

if
The if statement can be used to route program execution through two
different paths.
Here is the general form of the if statement:
if (condition) statement1 ;
else statement2 ;

The if works like this : if the condition is true, then statement 1 is executed.
Otherwise , statement 2 (if it exists) is executed.

int a , b ;
//
if (a < b ) a =0;
b =0;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero.
 There is a program that counts the even and odd numbers in a list of
u ers usi g the if…else state e t. Nu er is a arra aria le
containing all the numbers and number.length gives the number of
elements in the array.
 // e peri e ti g ith if…else state e t

class IfelseTest
{
public static void main (String args[ ] )
{
int number [ ] = { 50 , 65 , 56, 71, 81 } ;
int even = 0, odd = 0 ;
for ( int i= 0 ; i < number.length; i ++)
{

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 42


if ( ( number[i] % 2) == 0 ) // decide even or odd
{
even += 1 ; // counting even numbers
}
else
{
Odd + = 1 ; // counting odd numbers
}
}
“ ste .out.pri tl E e u ers : + e e + odd u ers : +odd ;
}}

Output is :
Even number : 2 odd number : 3

Nested ifs

A nested if is an if statement that is the target of another if or else. Nested ifs


are very common in programming. When you nest ifs, the main thing to
remember is that an else statement always refers to the nearest if statement
that is within the same block as the else and that is not already associated with
an else.

Here is an example:

if ( i == 10 )
{
if ( j < 20 )
a = b;
if ( k > 100 ) // this if is
c=d;
else a = c ; // associated with this else
}
else a = d; // this else refers to if ( i == 10 )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 43


As the comments indicate, the final else is not associated with if ( j < 20),
because it is not in the same block ( even though it is the nearest if without an
else ).Rather, the final else is associated with if ( i == 10). The inner else refers
to if (k > 100), because it is the closest if within the same block.

The if-else-if ladder

A common programming construct that is based upon a sequence of nested ifs


is the if-else-if ladder. It looks like this,

if ( condition )
statement;
else if ( condition )
statement;
else if ( condition )
statement ;
. ..
..
..
else
statement ;

The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed , and the rest of the ladder is bypassed.

If none of the conditions is true, then the final else statement will be executed.

The final else acts as a default condition; that is, if all other conditional tests
fail, then the last else statement is performed. If there is no final else and all
other conditions are false, then no action will take place.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 44


Switch

The switch statement is ja a s ulti a ra h state e t. It pro ides a eas


way to dispatch execution to different parts of your code based on the value of
an expression.
As such, it often provides a better alternative than a large series of if-else-if
statements.

Here is the general form of a switch statement:

switch (expression)
{
case value 1:
// statement sequence
break;
case value 2:
// statement sequence
break;
.
.
Case value N:
// statement sequence
break;
default:
// default statement sequence }

The expression must be type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the
expression. Each case value must be a unique literal (that is, it must be a
constant, not a variable). Duplicate case values are not allowed.

The switch statement works like this: the value of the expression is compared
with each of the literal values in the case statements. If a match is found, the
code sequence following that case statement is executed. If none of the

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 45


constants matches the value of the expression, then the default statement is
executed.

The break statement is used inside the switch to terminate a statement


sequence. When a break statement is encountered, execution branches to the
first line of code that follows the entire switch statement. This has the effect of
jumping out of the switch.
Here is a example that uses a switch statement:
// A simple example of the switch.
class SampleSwitch
{
public static void main(String args [ ] )
{
for ( int i = 0 ; i < 6 ; i ++ )
switch(i)
{
case 0 :
“yste .out.pri tl i is zero . ;
break ;
case 1 :
“yste .out.pri tl i is o e . ;
break;
case 2 :
“yste .out.pri tl i is t o . ;
break;
case 3 :
“yste .out.pri tl i is three . ;
break;
default :
“yste .out.pri tl i is greater tha );
}
} }
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 46


i is greater than 3.

Note:-Java 1.7 onwards switch supports string expression.

The while Statement


Ja a s iteratio state e ts are for, hile, do- while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly
executes the same set of instructions until a termination condition is met.

The while loop is ja a s ost fu da e tal looping statement. It repeats a


statement or block while its controlling expression is true.

Here is its general form:

while ( condition )
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition
becomes false, control passes to the next line of code immediately following
the loop.
Since the while loop evaluates its conditional expression at the top of the loop,
the body of the loop will not execute even once if the condition is false to
begin with.
Here is a while loop that counts down from 10, printing exactly ten lines of
ti k :
// demonstrate the while loop.
class While
{
public static void main ( String args [ ] )
{
int n = 10 ;
while ( n < 0 )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 47


{
“yste .out.pri tl ti k + ;
n-- ;
}
}}

When you run this program :

tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

do – while
As you just saw, if the conditional expression controlling a while loop is initially
false, then the body of the loop will not be executed at all.

However, it is desirable to execute the body of a while loop at least once, even
if the conditional expression is false to begin with. The do – while loop always
executes its body at least once, because its conditional expression is at the
bottom of the loop.

Its general form: do {


// body of loop;
} while ( condition )

Each iteration of the do – while loop first executes the body of the loop and
then evaluates the conditional expression. If this expression is true, the loop

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 48


will repeat. Otherwise, the loop terminates. As ith all of ja a s loops,
condition , must be a Boolean expression.

for loop
Here is the general form of the for statement :
for ( initialization ; condition ; iteration )
{
//body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows.

 When the loop first starts, the initialization portion of the loop is
executed. Generally, this is an expression that sets the value of the loop
control variable, which acts as a counter that controls the loop.

Next, condition is evaluated. This must be a Boolean expression. It


usually tests the loop control variable against a target value. If this
expression is true, then the body of the loop is executed.

 Again, next is the iteration portion of the loop is executed. This is usually
an expression that increments or decrements the loop control variable.

Here is the ersio of the ti k progra that uses a for loop.


// demonstrate the for loop
class ForTick
{
public static void main ( String args [ ] )
{
int n ;
for ( n = 10 ; n> 0; n—)
“yste .out.pri tl ti k + ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 49


}
}

Nested Loops

(Loop inside a loop) Java allows loops to be nested. That is, one loopmay be
inside another. For example, here is a program that nests for loops:

// Loops may be nested.

class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<5; i++) {
for(j=1; j<i; j++)
{
System.out.println(j);
}
}
}}

Jump Statements
break
The break statement has three uses.
1. It terminates a statement sequence in a switch statement.
2. It can be used to exit a loop.
3. It a e used as a i ilized for of goto.

1.) Break with Switch as been discussed under switch section.

2.) Break with for loop


class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if(i == 5) break; // terminate loop if i is 5

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 50


System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
Output---1 2 3 4 Loop Complete
}

3.) Break with goto -------syntaxBreak label;


class Break {
public static void main(String args[]) {
int x=10;
first: {
System.out.println("Before the break.");
if(x==10) break first; // break out to first block
System.out.println("This won't execute");
}
}

Continue Statement
Continue statement cause loop to bypass the current level

class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
if (i == 5) continue;
System.out.print(i + " ");
}
}
}

Output:- 1 2 3 4 6 7 8 9

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 51


Chapter-7
Classes & Methods

The class is at the core of java. It is the logical construct upon which the entire
java language is built because it defines the shape and nature of an object.

Perhaps the most important thing to understand about a class is that it defines
a new data type. (Once defined, this new type can be used to create objects of that type.
)

Defining a class

When you define a class, you declare its exact form and nature. You do this by
specifying the data that it contains and the code that operates on that data.

A class is a user-defined data type with a template that serves to define its
properties. O e the lass t pe has ee defi ed, e a reate aria les of
that type using declarations that are similar to the basic type declarations. In
java, these variables are termed as instances of classes, which are the actual
objects.

A class is declared by use of the class keyword. Classes can get much more
complex.
The general form is:
class classname
{
Type instance-variable1 ;
Type instance-variable2 ;
//
Type methodname 1 (parameter list)
{
// body of method
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 52


Type methodname 2 (parameter list)
{
// body of method
}
}

FIELD DECLARATION
Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are
created whenever an object of the class is instantiated.

Example;
class Rectangle
{
int length ;
int width ;
}

The class Rectangle contains two integer type instance variables. It is allowed
to declare them in one line as
int length , width ;

METHOD DECLARATION

A class with only data fields (and without methods that operate on that data)
has no life. The objects created by such a class cannot respond to any
messages. We must add methods that are necessary for manipulating the data
contained in the class.

Methods are declared inside the body of the class but immediately after the
declaration of instance variables.

The general form of method declaration is:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 53


type methodname (parameter- list)
{
method body
}

Methods declaration has four basic parts:

1. The name of the method (method name)


(The method name is a valid identifier)

2. The type of the value the method returns (type)


(The type specifies the type of value the method would return. This
could be a simple data type such as int as well as any class type. It could
even be void type, if the method does not return any value. )

3. A list of parameters (parameter - list)


(The parameter list is always enclosed in parenthesis. This list contains
variable names and types of all the values we want to give to the
method as input. In case, where no input data are required, the
declaration must retain the empty parentheses. )

4. The body of the method


(The body actually describes the operations to be performed on the
data.)

Examples:
( int m , float x , float y ) // three parameters
( ) // empty list
 Let us consider the Rectangle class again and add a method getData( )
to it.

class Rectangle
{
int length ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 54


int width ;
void getData ( int x , int y ) // method declaration
{
length = x ;
width = y ;
}
}

 Note that the method has a return type of void because it does not
return any value.We pass two integer values to the method which are
then assigned to the instance variables length and width. The getData
method is basically added to provide values to the instance variables.

CREATING OBJECTS

As pointed out earlier, an object in java is essentially a block of memory that


contains space to store all the instance variables. Creating an object is also
referred to as instantiating an object.

Objects in java are created using the new operator. The new operator creates
an object of the specified class and returns a reference to that object.

Here is an example of creating an object of type Rectangle.

Rectangle rect1 ; // declare the object


rect1 = new Rectangle ( ) ; // instantiate the object

The first statement declares a variable to hold the object reference and the
second one actually assigns the object reference to the variable. The variable
rect1 is now an object of the Rectangle class.

Both statements can be combined into one as shown below :


Rectangle rect1 = new Rectangle ( ) ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 55


The method Rectangle ( ) is the default constructor of the class. We can create
any number of objects of Rectangle.
Example :
Rectangle rect1 = new Rectangle ( ) ;
Rectangle rect2 = new Rectangle ( ) ;
Temporary Object can be
Rect3 = new Rectangle ( ) ;

ACCESSING CLASS MEMBERS

class Rectangle
{
int length , width ; // declaration of variables
void getData ( int x , int y ) // definition of method
{
length = x ;
width = y ;
}
int rectArea ( ) // definition of another method
{
int area = length * width ;
return ( area ) ;
}
}
class RectArea // class with main method
{
public static void main ( String args [ ] )
{
int area1, area 2 ;
Rectangle rect1 = new Rectangle ( ) ; // creating objects
Rectangle rect2 = new Rectangle ( ) ;
Rect1.length = 15 ; // accessing variables
Rect1.width = 10 ;
area1 = rect1.length * rect1.width ; // accessing methods
rect2.getData ( 20,12 ) ;
area2 = rect2.rectArea ( ) ;
“yste .out.pri tl Area = + area ;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 56


“yste .out.pri tl Area = + area ;
}
}

Constructors
We know that all objects that are created must be given initial values. Java
supports a special type of method, called a constructor, that enables an object
to itself when it is created.

Constructors have the same name as the class itself. Secondly, they do not
specify a return type, not even void. This is because they return the instance of
the class itself.
We can now replace the getData method by a constructor method as shown
below:

There are two types of Constructor

Default Constructor
Parameterized constructor

class Car {
String name ; String model;
Car( ) //Default Constructor
{ name =""; model=""; }
}

Each time a new object is created at least one constructor will be invoked.
Car c = new Car() //Default constructor invoked
Car c = new Car(name); //Parameterized constructor invoked
Constructor Overloading

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 57


Like methods, a constructor can also be overloaded. Overloaded constructors
are differentiated on the basis of their type of parameters or number of
parameters.

class Rectangle
{
int length ;
int width ;
Rectangle () // Default constructor
{
length = 0 ;
width = 0 ;
}

Rectangle ( int x , int y ) // Parameterized constructor


{
length = x ;
width = y ;
}
int rectArea ( )
{
return ( length * width ) ;
}
public static void main(String args[])
{
Rectangle obj=new Rectangle()/ / Call default constructor
Rectangle obj1=new Rectangle(12,10)/ / Call default constructor
“yste .out.pri tl Area First…. +o j.re tArea ;
“yste .out.pri tl Area “e o d…. +o j .re tArea ;

}
}
Output:
Area First 0
Area Second 120
Finalize method
JAVA Does t ha e destructor.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 58


It is possible to define a method that will be called just before an object's final
destruction by the garbage collector. This method is called finalize( ), and it can
be used to ensure that an object terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by
that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java
runtime calls that method whenever it is about to recycle an object of that
class.
Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.

The finalize( ) method has this general form:


protected void finalize( ) { // finalization code here } Here, the keyword
protected is a specifier that prevents access to finalize( ) by code defined
outside its class.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 59


Chapter-8
Inheritance (IS –A Relationship)
Reusability is yet another aspect of OOP paradigm. It is always nice if we could
reuse something that already exists rather than creating the same all over
again. Java classes can be reused in several ways. The mechanism of deriving a
new class from an old one is called inheritance. The old class is known as the
base class or super class or parent class and the new one is called sub class or
derived class or child class.

Inheritance represents the IS-A relationship, also known as parent-


child relationship.
Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications. Using inheritance,
you can create a general class that defines traits common to a set of related
items. This class can then be inherited by other, more specific classes, each
adding those things that are unique to it.
The inheritance allows subclasses to inherit all the variables and methods of
their parent classes. Inheritance may take different forms:
 Single inheritance
(only one super class)
 Multiple inheritance
(several superclasses)
 Hierarchical inheritance
(one superclass many subclasses )
 Multilevel inheritance
(derived from a derived class)

Multiple inheritance is not supported in java through class.(Interface


used for this purpose)To reduce the complexity and simplify the
language, multiple inheritance is not supported in java.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 60


(Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and
B classes have same method and you call it from child class object, there will be ambiguity to call
method of A or B class.)

In the terminology of java, a class that is inherited is called a superclass. The


class that does the inheriting is called subclass.

Defining a Subclass

Class subclassname extends superclassname{


}

The keyword extends signifies that the properties of the superclassname are
extended to the subclassname. The subclass will now contain its own variables
and methods as well those of the superclass.

Here is an program that illustrates the concept of single inheritance:


// application of single inheritance
class Room
{
int length ;
int breadth ;
Room (int x, int y) // constructor
{
length = x ;
breadth = y ;
}
int area ( ) // method declaration
{
return ( length * breadth )
}
}
class Bedroom extends Room
{
int height ;
BedRoom ( int x , int y, int z )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 61


{
Super ( x , y )
height = z ;
}
int volume ( )
{
return ( length * breadth * height ) ;
}
}
..
..
class InherTest
{
public static void main( String args [ ] )
{
BedRoom room1 =new BedRoom ( 14, 12, 10 ) ;
int area1 = room1.area ( ) ; //superclass method
int volume1 = room1.volume ( ) ; // baseclass method
“yste .out.pri tl Area = + area ;
“yste .out.pri tl Volu e = + olu e ;
}
}

The output of program is :


Area1 = 168
Volume1 = 1680

The program defines a class Room and extends it to another class BedRoom.
Note that the class BedRoom defines its own data members and methods. The
subclass BedRoom now includes three instance variables, namely , length,
breadth and height and two methods ,area and volume.

Finally, the object room1 of the subclass BedRoom calls the method area
defined in the super class as well as the method volume defined in the subclass
itself.

Constructor call in Inheritance(Default)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 62


When ever we create object of sub class it will call default constructor of super
class first.

Example

C
Here is we create object of C class it will go to B and B will move to A for
default constructor call.
class AA
{
public AA()
{
System.out.println("AA Class...");
}}
class BB extends AA
{
public BB()
{
System.out.println("BB Class");
}}
public class InherCons {
public static void main(String[] args) {
BB obj=new BB();
}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 63


Output
AAClass
BBClass

Super Keyword

You can use super in a subclass to refer to its immediate superclass.


Whenever you create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.

Usage of java super Keyword

 super is used to refer immediate parent class instance variable.


 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.

1.) super is used to refer immediate parent class instance variable.

class Vehicle{
int gears=6;
}
class Bike extends Vehicle{
int gears=5;
void display(){
System.out.println(gears);
//will print gears of Bike
//super.gears will show gears of Vehicle
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 64


}

2.) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as
given below:
class MySup
{
public MySup(int x) {
System.out.println("The square from super.."+(x*x));
}
}
class MySub extends MySup
{
public MySub(int y) {
super(y);
System.out.println("The cube from sub.."+(y*y*y));
}
}
public class InherSuper {
public static void main(String[] args) {
MySub obj=new MySub(6);
}
}

Note:
super() is added in each class constructor automatically by compiler. It call
default constructor of class.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 65


3.) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should
be used in case subclass contains the same method as parent class .
class Student{
void message(){System.out.println("welcome");}
}
class BTechStudent extends Student{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
BTechStudent s=new BTechStudent();
s.display();
}
}

this keyword

this is a reference variable that refers to the current object. It is a keyword in


java language represents current class object

Usage of this keyword

this keyword can be used to refer current class instance variable.


this() can be used to invoke current class constructor.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 66


this keyword can be used to invoke current class method (implicitly) which can
be used to differentiate variable of class and formal parameters of method or
constructor.

Whenever the formal parameter and data member of the class are similar and
JVM gets an ambiguity (no clarity between formal parameter and data
members of the class).
class Employee
{
int id; String name;
Employee(int id,String name)
{
this.id = id;
this.name = name; }
void show()
{ System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry"); e1.show();
}
}

this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if you have many constructors in
the class and want to reuse that constructor.
class Student{
int id;
String name;
Student(){System.out.println("default constructor is invoked");}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 67


Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student e1 = new “tude t , Raju" ;
e1.display();
}
}

The this keyword can be used to invoke current class method (implicitly).

You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword
while invoking the method

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
} }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 68


Overriding Methods

We have seen that a method defined in a superclass is inherited by its subclass


and is used by the objects created by the subclass. Method inheritance enables
us to define and use methods repeatedly in subclasses without having to
define the methods again in subclass.

However, there may be occasions when we want an object to respond to the


same method but have different behavior when that method is called.

That means, we should override the method defined in the superclass. This is
possible by defining a method in the subclass that has the same name, same
arguments and same return type as a method in the superclass.Then , when
that method is called , the method defined in the subclass is invoked and
executed instead of the one in the superclass. This is known as overriding.

Here is the example illustrating the concept of overriding. The method


display( ) is overridden.

class Super
{
int x ;
Super ( int x )
{
this.x = x ;
}
void display ( ) // method defined
{
“ ste .out.pri tl “uper = + ;
}
}
….
..
.
class Sub extends Super
{

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 69


inty ;

sub ( int x, int y )

super (x) ;

this.y = y ;

void display ( ) // method defined again

“ ste .out.pri tl “uper = + );

“ ste .out.pri tl “u = + ;

classOverrideTest

public static void main ( String args [ ])

Sub s1 = new Sub ( 100, 200 ) ;

s1. display ( ) ;

Output of program:

Super x = 100

Sub y = 200

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 70


Dynamic Binding( Run time Polymorhism)
Dynamic binding is the process of connecting a function (procedure call) to a
specific method (sequence of code) at run time. This means that function to be
executed by a method remains unknown until run-time. Dynamic binding is
also referred to as run-time binding or late binding. Method overriding is a
good example of dynamic binding.

The opposite of dynamic binding is static binding. Unlike dynamic binding,


static binding occurs during compilation. It is sometimes referred to as early
binding because the binding occurs before the application runs. A good
example of static binding is method overloading. Another key difference
between the two binding types is that static binding utilizes class information
for binding while dynamic binding utilizes objects to resolve binding. The time
at which binding occurs affects the overall performance of the program. If the binding occurs earlier,
safety and efficiency increases while flexibility decreases.

When type of the object is determined at run-time, it is known as dynamic


binding.

Example of dynamic binding

class Animal{

void eat(){System.out.println("animal is eating...");}

class Dog extends Animal{

void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Animal a=new Dog();

a.eat(); } }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 71


Aggregation (HAS-A Relationship)

If a class have an entity reference, it is known as Aggregation. Aggregation


represents HAS-A relationship.
Consider a situation, Employee object contains many information such as id,
name, emailId etc. It contains one more object named address, which contains
its own information such as city, state, country, zipcode etc. as given below.
class Employee{

int id;

String name;

Address address;//Address is a class

...

In such case, Employee has an entity reference address, so relationship is


Employee HAS-A address.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 72


Chapter-9
UNDERSTANDING STATIC

The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class. The
static keyword belongs to the class than instance of the class.

The static can be:


 variable (also known as class variable)
 method (also known as class method)
 block
 nested class

STATIC VARIABLE

Static variable are class level variable, for the static variable JVM allocate single
memory space which shared by all objects.

class Counter{
static int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
} }

Output:
1
2
3

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 73


STATIC METHOD

If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.

A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.

class mstatic
{
public static void d()
{
System.out.println("Static call.");
}
public static void main(String args[])
{
d();//direct call
}
}
Output: Static call.

STATIC BLOCK

This block gets executed when the class is loaded in the memory. Static block is
mostly used for changing the default values of static variables.
A class can have multiple Static blocks, which will execute in the same
sequence in which they have been written into the program.
public class SecondStatic {
static

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 74


{
System.out.println("This is static block");
}
public static void main(String args[])
{
“ ste .out.pri tl The ai Calli g.. ;
}
}
Output:-
This is static block
The main Calling..

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 75


Chapter – 10
FINAL Keyword
The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
1. variable
2. method
3. class

FINAL VARIABLES AND METHODS

All methods and variables can be overridden by default in subclasses. If we


wish to prevent the subclasses from overridding the members of the
superclass, we can declare them as final using the keyword final as a modifier.

Example:
final int SIZE =100 ;
final void showstatus ( ) ………..

Making a method final ensures that the functionality defined in this method
will never be altered in any way.

Similarly, the value of a final variable can never be changed. Final variables,
behave like class variables and they do not take any space on individual objects
of the class.

Example Final Variable

class Demo{
final int MAX_VALUE=99;
void myMethod(){
MAX_VALUE=101;
}
public static void main(String args[]){

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 76


Demo obj=new Demo();
obj.myMethod();
}
}

Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assigned

We got a compilation error in the above program because we tried to change


the value of a fi al aria le MAX_VALUE .

Example Final Method

class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
void demo(){
System.out.println("ABC Class Method");
}

public static void main(String args[]){


ABC obj= new ABC();
obj.demo();
}
}

The above program would throw a compilation error, however we can use the
parent class final method in sub class without any issues. Lets have a look at
this code: This program would run fine as we are not overriding the final

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 77


method. That shows that final methods are inherited but they are not eligible
for overriding.

FINAL CLASSES
Sometimes we may like to prevent a class being further subclasses for security
reasons. A class that cannot be subclassed is called a final class. This is
achieved in java using the keyword final as follows:

final lass A lass {…………….}


final lass B lass e te ds “o e lass{………………..}
Any attempt to inherit these classes will cause an error and the compiler will
not allow it.
Declaring a class final prevents any unwanted extensions to the class. It also
allows the compiler to perform some optimizations when a method of a final
class is invoked.
Example Final Class
final class XYZ{
}
class ABC extends XYZ{
void demo(){
System.out.println("My Method");
}
public static void main(String args[]){
ABC obj= new ABC();
obj.demo();
}
}
Output:
The type ABC cannot subclass the final class XYZ
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 78


5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters
cannot be changed.
8) It is a good practice to name final variable in all CAPS.

9) final, finally and finalize are three different terms. finally is used in exception
handling and finalize is a method that is called by JVM during garbage
collection.

InstanceOf Operator
The java instanceof operator is used to test whether the object is an instance
of the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator because it


compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false.

Example

class Simple{

public static void main(String args[]){

Simple s=new Simple();

System.out.println(s instanceof Simple);//true

Output:

true

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 79


Chapter-11
ABSTRACT METHODS AND CLASSES

A class that is declared with abstract keyword, is known as abstract class in


java. It can have abstract and non-abstract methods (method with body).

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in


java. It needs to be extended and its method (abstract methods) implemented.
It cannot be instantiated. Sometimes you will want to create a super class that
only defines a generalized form that will be shared by all of its subclasses,
leaving it to each subclass to fill in the details.

Example (Syntax)
abstract class <classname>
{
……………….
}
We cannot create object of this class.
abstract class Bike{
public void Hello()
{
System.out.println("Hello Bike");
}
}
public class AbstractFirst
{
public static void main(String args[]){
// Bike obj = new Bike(); // It will show compiler Error if we will create object
}
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 80


Abstract method

A method that is declared as abstract and does not have implementation is


known as abstract method. Any subclass of an abstract class must either
implement all of the abstract methods in the super class, or be itself declared
abstract.(Else it will generate error..)

Here is a simple example of a class with an abstract method, followed by a


class

abstract class Bike{


abstract void run();
}

class Honda4 extends Bike{


void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run(); } }

Interface

Using the keyword i terfa e, ou a full a stra t a lass i terfa e fro its
implementation. That is, using interface, you can specify what a class must do,
but not how it does it. Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are declared without any body.
I pra ti e, this ea s that ou a defi e i terfa es hi h do t ake
assumptions about how they are implemented. Once it is defined, any number
of classes can implement an interface. Also, one class can implement any
number of interfaces.

To implement an interface, a class must create the complete set of methods


defined by the interface. However, each class is free to determine the details
of its own implementation.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 81


Declaring Interface
Defining an Interface

An interface is defined much like a class. This is the general form of an


interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value; }

Example
interface inf {
void hello();
}

Once an interface has been defined, one or more classes can


implement that interface.
To implement an interface, include the implements clause in a class definition,
and then create the methods defined by the interface.
access class classname implements interface {
// class-body }

Declaring Interface
Interface inf
{ public void hello();
}

class Client implements inf{


// Implements inf interface
public void hello() {
System.out.println("callback called ");}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 82


You can declare variables as object references that use an interface rather than
a class type. Any instance of any class that implements the declared interface
can be referred to by such a variable.

class TestIface {
public static void main(String args[]) {
inf c = new Client();
c.hello();
}
}
Variables can be declared inside of interface declarations. They are implicitly
final and static, meaning they cannot be changed by the implementing class.
They must also be initialized with a constant value. All methods and variables
are implicitly public if the interface, itself, is declared as public.

Example--
interface inf {
void hello();
}
class infImpl implements inf
{
public void hello()
{
System.out.println("Infimpl Hello");
}}
public class MyInterfaceOne implements inf
{
public void hello() {
System.out.println("Hello Implementation");
}
public static void main(String[] args) {
inf obj=new MyInterfaceOne(); //created reference of interface

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 83


obj.hello();
inf obj1=new infImpl();
obj1.hello();
}
}
Implementing Multiple Interface
class can implement more than one interface by using ,(comma) operator.
Now class have to provide implementation of all methods else class will
become abstract.
interface inf1
{
public void x();
}
interface inf2
{
public void y();
}
class Test implements inf1,inf2
{
……………………………………………..
}
Extending Interface
One interface can extends other interface as well.Now class have to provide
implementation of all methods of child interface, else class will become
abstract.
interface inf1
{
public void x();
}
interface inf2 extends inf1
{
public void y();
}
class Test implements inf2

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 84


{
……………………………………………..}
Difference between Abstract class and Interface
Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be
instantiated.
But there are many differences between abstract class and interface that are
given below.
Abstract class Interface

1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, Interface has only static and final
non-final, static and non-static variables.
variables.

4) Abstract class can have static Interface can't have static methods, main
methods, main method and method or constructor.
constructor.

5) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

6) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 85


Chapter-12
Inner Class
Inner classes are defined inside the body of another class (known as outer
class). These classes can have access modifier or even can be marked
as abstract and final. Inner classes have special relationship with outer class
instances. This relationship allows them to have access to outer class members
including private members too.

Inner classes can be defined in four different following ways as mentioned


below:
1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class
(Here below we cover 1st and 4th type)

Inner class
An inner class is declared inside the curly braces of another enclosing class.
Inner class is coded inside a Top level class as shown below:-

class MyOuterClassDemo {
private int myVar= 1;

// inner class definition


class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Value of myVar is :" + myVar);
}
} // close inner class definition
} // close Top level class definition

Inner class acts as a member of the enclosing class and can have any access
modifiers: abstract, final, public, protected, private, static.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 86


Inner class can access all members of the outer class including those marked
private as shown in the above example where inner class is accessing the
private variable "myVar" of outer class.

Instantiating an inner class

To instantiate an instance of inner class, there should be a live instance of


outer class. An inner class instance can be created only from an outer class
instance. An inner class shares a special relationship with an instance of the
enclosing class.
Instantiating an inner class from within code in outer class:

class MyOuterClassDemo {
private int x= 1;
public void innerInstance()
{
MyInnerClassDemo inner = new MyInnerClassDemo();
inner. seeOuter();
}
public static void main(String args[]){
MyOuterClassDemo obj = new MyOuterClassDemo();
obj.innerInstance();
}
// inner class definition
class MyInnerClassDemo {
public void seeOuter () {
System.out.println("Outer Value of x is :" + x);
}
} // close inner class definition
} // close Top level class definition

Output:
Outer Value of x is :1

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 87


Instantiating an inner class from outside the outer class Instance Code:

The public static void main code in the above example can be replaced with
this one. It will also give the same output.

public static void main(String args[]){


MyOuterClassDemo.MyInnerClassDemo inner = new
MyOuterClassDemo().new MyInnerClassDemo();
inner. seeOuter();
}

Static Nested Classes

A static nested classes are the inner classes marked with static modifier.
Because this is static in nature so this type of inner class does t share any
special kind of relationship with an instance of outer class.A static nested class
cannot access non static members of outer class.
Example:
class Outer{
static class Nested{}
}
A static nested class can be instantiated like this:
Example:-
class Outer{// outer class
static class Nested{}// static nested class
}

class Demo{
public static void main(String[] args){ // use both class names
Outer.Nested n= new Outer.Nested();
}
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 88


Chapter 13
Wrapper Classes

Wrapper class in java are the Object representation of eight primitive types in
java. All the wrapper classes in java are immutable and final. Java 5 auto boxing
and unboxing allows easy conversion between primitive types and their
corresponding wrapper classes in java programs.

Below table shows the primitive types and their wrapper class in java.

Primitive type Wrapper class Constructor Arguments


byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float float, double or String
double Double double or String
char Character Char
boolean Boolean boolean or String

Why do we need wrapper classes?

It s a s art de isio to keep pri iti e t pes a d Wrapper lasses separate to


keep things simple. We need wrapper classes when we need a type that will fit
in the Object world programming like Collection classes. We use primitive
types when we want things to be simple

The most common methods of the Integer wrapper class are summarized in
below table.

Method Purpose
parseInt(s) returns a signed decimal integer value equivalent to
string s
toString(i) returns a new String object representing the integer i
byteValue() returns the value of this Integer as a byte
doubleValue() returns the value of this Integer as an double

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 89


floatValue() returns the value of this Integer as a float
intValue() returns the value of this Integer as an int
shortValue() returns the value of this Integer as a short
longValue() returns the value of this Integer as a long
int compareTo(int i) Compares the numerical value of the invoking object
with that of i. Returns 0 if the values are equal. Returns a negative value if the
invoking object has a lower value. Returns a positive value if the invoking
object has a greater value.
static int compare(int num1, int num2) Compares the values of num1 and
num2. Returns 0 if the values are equal. Returns a negative value if num1 is
less than num2. Returns a positive value if num1 is greater than num2.
boolean equals(Object intObj) Returns true if the invoking Integer object is
equivalent to intObj. Otherwise, it returns false.

Example of Wrapper class

public class WrapperDemo {


public static void main (String args[]){
Integer intObj1 = new Integer (25);
Integer intObj2 = new Integer ("25");
Integer intObj3= new Integer (35);
//compareTo demo
System.out.println("Comparing using compareTo Obj1 and Obj2: " + intO
bj1.compareTo(intObj2));
System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj
1.compareTo(intObj3));
//Equals demo
System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.eq
uals(intObj2));
System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.eq
uals(intObj3));
Float f1 = new Float("2.25f");
Float f2 = new Float("20.43f");
Float f3 = new Float(2.25f);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 90


System.out.println("Comparing using compare f1 and f2: " +Float.compare
(f1,f2));
System.out.println("Comparing using compare f1 and f3: " +Float.compare
(f1,f3));
//Addition of Integer with Float
Float f = intObj1.floatValue() + f1;
System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f )
;
}
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 91


Chapter-14
Packages in JAVA
A java package is a group of similar types of classes, interfaces and sub-
packages. Using package it becomes easier to locate the related classes.
Advantages of Packages
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Types of Packages
User-defined-package
Java package created by user to categorized classes and interface
Built-in Package
Existing Java package for example java.lang, java.util etc.

Creating a package
Creating a package in java is quite easy. Simply include a package command
followed by name of the package as the first statement in java source file.
package mypack;
public class student
{ ...statement; }
For example the .class for any classes you to define to be part
of mypack package must be stored in a directory called mypack.
If you declare a method by using the default scope, any method can use it as
long as it resides in the same package. In addition, if you create a class that

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 92


inherits from the class containing the method, the subclass can use the
method as long as it resides in the same package.
Using a Package
import keyword is used to import built-in and user-defined packages into your
java source file. So that your class can refer to a class that is in another package
by directly using its name.
There are three ways to access the package from outside the package.
1.) import all the classes from the particular package
import package.*;
2.) import the only class you want to use.
import package.classname;
3.) fully qualified name.
1.) import all the classes from the particular package:
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
Example of package that import the packagename.*
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
Same way I can have other classes as well.
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

2.) import the only class you want to use:


import package.classname;
If you import package.classname then only declared class of this package will
be accessible.
package pack;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 93


public class A{
public void msg(){System.out.println("Hello");}
}
Same way I can have other classes as well.
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
3.) fully qualified name:
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface. It is generally
used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
class B{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name obj.msg(); }
}
Object Class
The Object class sits, in the java.lang package at the top of the class hierarchy
tree in the Java development environment. The Object class is the parent class
of all the classes in java by default.
Every class in the Java system is a descendent (direct or indirect) of
the Object class.
The Object class defines the basic state and behaviour that all objects must
have, such as the ability to compare oneself to another object, to convert to a

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 94


string, to wait on a condition variable, to notify other objects that a condition
variable has changed, and to return the object's class.
Methods of Object class
public boolean equals(Object obj)-compares the given object to this object.
public int hashCode()-returns the hashcode number for this object.
public final void wait()- causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes notify() or notifyAll()
method).
public final void notify()-wakes up single thread, waiting on this object's
monitor.
public final void notifyAll()-wakes up all the threads, waiting on this object's
monitor.
public final Class getClass()-returns the class object of this object. The Class can
further be used to get the metadata of this class.
public String toString()-returns the string representation of this object.
protected void finalize()- is invoked by the garbage collector before object is
being garbage collected.
protected Object clone() -returns the exact copy (clone) of this object.
toString Method
There are many scenarios where we want to represent any object as a
string, toString() method will help us.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method
on the object. So overriding the toString() method, returns the desired output,
it can be the state of an object etc. depends on your implementation.
Example
package com.myobject;
class Student{
int rollno;
String city;
Student(int rollno, String city){
this.rollno=rollno;
this.city=city;
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 95


public String toString(){//overriding the toString() method
return rollno+" "+city;
}
}
public class MyObjectString {
public static void main(String[] args) {
Student s1=new Student(101,"Mumbai");
Student s2=new Student(102,"Delhi");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
} }
Equals Method
The java.lang.Object.equals(Object obj) indicates whether some other object is
"equal to" this one.
The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null reference
values x and y, this method returns true if and only if x and y refer to the same
object (x == y has the value true).
Declaration
public boolean equals(Object obj)Parameters
obj -- the reference object with which to compare.
This method returns true if this object is the same as the obj
argument; falseotherwise.
Example
class ObjectDemo {
public ObjectDemo() {
// get an integer, which is an object
Integer x = new Integer(50);
// get a float, which is an object as well
Float y = new Float(50f);
// check if these are equal,which is
// false since they are different class
System.out.println("" + x.equals(y));
// check if x is equal with another int 50

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 96


System.out.println("" + x.equals(50));
}
}
public class MyEquals {
public static void main(String[] args) {
ObjectDemo obj=new ObjectDemo();
} }
getClass Method
The java.lang.Object.getClass() method returns the runtime class of an object.
That Class object is the object that is locked by static synchronized methods of
the represented class.
Declaration
public final Class getClass()Parameters
Return Value
This method returns the object of type Class that
represents the runtime class of the object.
class MCAStudent{
int rollno;
String city;
MCAStudent(int rollno, String city){
this.rollno=rollno;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+city;
} }
public class MyGetClass {
public static void main(String[] args) {
MCAStudent m=new MCAStudent(111,"Delhi");
System.out.println(m.getClass()); //getting class information
}
}
Clone Method
The clone() method is defined in the Object class.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 97


The object cloning is a way to create exact copy of an object. For this purpose,
clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create.
Why use clone() method ?
The clone() method saves the extra processing task for creating the exact copy
of an object. If we perform it by using the new keyword, it will take a lot of
processing to be performed that is why we use object cloning.

class Student18 implements Cloneable{


int rollno;
String name;
Student18(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
}
public class MyClone {
public static void main(String[] args) {
try{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c){}
}
}

hashCode Method
public native int hashCode();

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 98


It indicates that hashCode is the native implementation which provides the
memory address to a certain extent. However it is possible to override
the hashCode method in your implementation class. equals() This particular
method is used to make equal comparison between two objects.
1) If two objects are equal by equals() method then there hashcode returned
by hashCode() method must be same.
2) Whenever hashCode() method is invoked on the same object more than
once within single execution of application, hashCode() must return same
integer provided no information or fields used in equals and hashcode is
modified. This integer is not required to be same during multiple execution of
application though.

3) If two objects are not equals by equals() method it is not require that there
hash ode ust e differe t. Though it s al a s good pra ti e to retur
different hashCode for unequal object. Different hashCode for distinct object
can improve performance of hashmap or hashtable by reducing collision.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 99


Chapter 15
String Handling

String Handling

String Handling provides a lot of concepts that can be performed on a string


such as concatenation of string, comparison of string, find sub string etc.

Character

It is an identifier enclosed within single quotes (' ').


Example: 'A', '$', 'p'

String:

String is a sequence of characters enclosed within double quotes (" ") is known
as String.
Example: "Java Programming".

In java programming to store the character data we have a fundamental data


type called char. Similarly to store the string data and to perform various
operations on String data, we have three predefined classes they are:

String

StringBuffer

StringBuilder

Creating a String

There are two ways to create a String in Java

String literal

Using new keyword

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 100


String literal

In java, Strings can be created like this: Assigning a String literal to a String
instance:

String str1 = "Welcome";

String str2 = "Welcome";

The problem with this approach: As I stated in the beginning that String is an
object in Java. However we have not created any string object using new
keyword above. The compiler does that task for us it creates a string object
ha i g the stri g literal that e ha e pro ided, i this ase it is Wel o e
and assigns it to the provided string instances.

But if the object already exist in the memory it does not create a new Object
rather it assigns the same old object to the new instance, that means even
though we have two string instances above(str1 and str2) compiler only
created on string o je t ha i g the alue Wel o e a d assig ed the sa e
to both the instances. For example there are 10 string instances that have
same value, it means that in memory there is only one object having the value
and all the 10 string instances would be pointing to the same object.

What if we want to have two different object with the same string? For that
we would need to create strings using new keyword.

Using New Keyword

As we saw above that when we tried to assign the same string object to two
different literals, compiler only created one object and made both of the
literals to point the same object. To overcome that approach we can create
strings like this:

String str1 = new String("Welcome");

String str2 = new String("Welcome");

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 101


In this case compiler would create two different object in memory having the
same text.

Main functions of String

1.Length()

length(): This method is used to get the number of character of any string.

Example

class StringHandling

public static void main(String arg[])

int l;

String s=new String("Java");

l=s.length();

System.out.println("Length: "+l);

Output – Length 4

2.charAt()

This method is used to get the character at a given index value.

Example

class StringHandling

public static void main(String arg[])

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 102


{

char c;

String s=new String("Java");

c=s.charAt(2);

System.out.println("Character: "+c);

Output

Character: v

3.toCharArray( )

If you want to convert all the characters in a String object into a character
array, the easiest way is to call toCharArray( ). It returns an array of characters
for the entire string. It has this

general form:

char[ ] toCharArray( )

String Comparison

The String class includes several methods that compare strings or substrings
within strings

equals( ) and equalsIgnoreCase( )

To compare two strings for equality, use equals( ).

It has this general form:

boolean equals(Object str)

Here, str is the String object being compared with the invoking String object. It returns

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 103


true if the strings contain the same characters in the same order, and false
otherwise.

The comparison is case-sensitive.

To perform a comparison that ignores case differences, call equalsIgnoreCase(


).

When it compares two strings, it considers A-Z to be the same as a-z.

It has this general form:

boolean equalsIgnoreCase(String str)

Here, str is the String object being compared with the invoking String object. It,
too, returns true if the strings contain the same characters in the same order,
and false otherwise.

Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):

// Demonstrate equals() and equalsIgnoreCase().

class equalsDemo {

public static void main(String args[]) {

String s1 = "Hello";

String s2 = "Hello";

String s4 = "HELLO";

System.out.println(s1.equals(s2)); // true

System.out.println(s1.equalsIgnoreCase(s4)); //true

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 104


4.toUpperCase()

toUpperCase(): This method is use to convert lower case string into upper case.

Example

class StringHandling

public static void main(String arg[])

String s="Java";

System.out.println("String: "+s.toUpperCase());

Output

String: JAVA

5. toLowerCase()

toLowerCase(): This method is used to convert lower case string into upper
case.

Example

class StringHandling

public static void main(String arg[])

String s="JAVA";

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 105


System.out.println("String: "+s.toLowerCase());

Output

String: java

6.concat()

concat(): This method is used to combined two string.

Example

class StringHandling

public static void main(String arg[])

String s1="RAJ";

String s2="Raddy";

System.out.println("Combined String: "+s1.concat(s2));

Output

Combined String: RAJRaddy

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 106


7.compareTo()

compareTo(): This method is used to compare two strings by taking unicode


values, It return 0 if the string are same otherwise return +ve or -ve integer
values.

Example

class StringHandling

public static void main(String arg[])

String s1="Anil";

String s2="Raddy";

int i;

i=s1.compareTo(s2);

if(i==0)

System.out.println("Strings are same");

else

System.out.println("Strings are not same");

}}

Output

Strings are not same

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 107


8.compareToIgnoreCase()

compareToIgnoreCase(): This method is case insensitive method, which is used


to compare two strings similar to compareTo().

Example

class StringHandling

public static void main(String arg[])

String s1="raj";

String s2="RAJ";

int i;

i=s1.compareToIgnoreCase(s2);

if(i==0)

System.out.println("Strings are same");

else

System.out.println("Strings are not same");

}}}

Output

Strings are same

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 108


9.startsWith()

startsWith(): This method return true if string is start with given another string,
otherwise it returns false.

Example

class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.startsWith("Java"));
}
}

Output
true

10.endsWith()

endsWith(): This method return true if string is end with given another string,
otherwise it returns false.

Example

class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.endsWith("language"));
}
}

Output
true

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 109


11.subString()

subString(): This method is used to get the part of given string.

Example

class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}

Output

programming language

Example

class StringHandling
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}

Output

prog

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 110


12.trim()

trim(): This method remove space which are available before starting of string
and after ending of string.

Example

class StringHandling
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}}

Output

Java is programming language

13.split()

split(): This method is used to divide the given string into number of parts
based on delimiter (special symbols like @ space , ).

Example

class StringHandling
{
public static void main(String arg[])
{
String s="[email protected]";
String[] s1=s.split("@"); // divide string based on @
for(String c:s1) // foreach loop
{ System.out.println(c);
}}}
Output
contact

@myway.com

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 111


14.replace()

replace(): This method is used to return a duplicate string by replacing old


character with new character.

Note: In this method data of original string will never be modify.

Example

class StringHandling

public static void main(String arg[])

String s1="java";

String s2=s1.replace('j', 'k');

System.out.println(s2);

}}

Output

kava

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 112


Chapter-16

Exception Handling
An Exception can be anything which interrupts the normal flow of the
program. When an exception occurs program processing gets terminated and
does t o ti ue further. I su h ases e get a s ste ge erated error
message. The good thing about exceptions is that they can be handled.

Reasons for Exceptions

There can be several reasons for an exception. For example, following


situations can cause an exception – Opening a non-existing file, Network
connection problem, Operands being manipulated are out of prescribed
ranges, class file missing which was supposed to be loaded and so on.

Difference between error and exception

Errors indicate serious problems and abnormal conditions that most


applications should not try to handle. Error defines problems that are not
expected to be caught under normal circumstances by our program. For
example memory error, hardware error, JVM error etc.

Exceptions are conditions within the code. A developer can handle such
conditions and take necessary corrective actions.

Few examples –

DivideByZero exception

NullPointerException

ArithmeticException

ArrayIndexOutOfBoundsException

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 113


Advantages of Exception Handling

Exception handling allows us to control the normal flow of the program by


using exception handling in program.

It throws an exception whenever a calling method encounters an error


providing that the calling method takes care of that error.

It also gives us the scope of organizing and differentiating between different


error types using a separate block of codes. This is done with the help of try-
catch blocks.

Why to handle exception?

If an exception is raised, which has not been handled by programmer then


program execution can get terminated and system prints a non user friendly
error message.

Java Exception Handling Keywords

There are 5 keywords used in java exception handling.

try

catch

finally

throw

throws

Java try block

Java try block is used to enclose the code that might throw an exception. It
must be used within the method.

Java try block must be followed by either catch or finally block.

Java catch block

Java catch block is used to handle the Exception. It must be used after the try
block only.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 114


You can use multiple catch block with a single try.

public class Testtrycatch2{

public static void main(String args[]){

try{

int data=50/0;

}catch(ArithmeticException e){System.out.println(e);}

System.out.println("rest of the code...");

Java Multi catch block


If you have to perform different tasks at the occurrence of different
Exceptions, use java multi catch block.

Let's see a simple example of java multi-catch block.

public class TestMultipleCatchBlock{

public static void main(String args[]){

try{

int a[]=new int[5];

a[5]=30/0;

catch(ArithmeticException e){System.out.println("task1 is completed");}

catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 compl


eted");}

catch(Exception e){System.out.println("common task completed");}

System.out.println("rest of the code..."); } }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 115


Java finally block

Java finally block is a block that is used to execute important code such as
closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword.


The throw keyword is mainly used to throw custom exception. We will see
custom exceptions later.

The syntax of java throw keyword is given below.

throw exception;

throw new IOException("sorry device error);

java throw keyword example

In this example, we have created the validate method that takes integer value
as a parameter. If the age is less than 18, we are throwing the
ArithmeticException otherwise print a message welcome to vote.

public class TestThrow1{

static void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

public static void main(String args[]){

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 116


validate(13);

System.out.println("rest of the code...");

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an


information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained

Java throws example

Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.

import java.io.IOException;

class Testthrows1{

void m()throws IOException{

throw new IOException("device error");//checked exception

void n()throws IOException{

m();

void p(){

try{

n();

}catch(Exception e){System.out.println("exception handled");}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 117


}

public static void main(String args[]){

Testthrows1 obj=new Testthrows1();

obj.p();

System.out.println("normal flow...");

Difference between throw and throws in Java

There are many differences between throw and throws keywords. A list of
differences between throw and throws are given below:

No. Throw Throws

1) Java throw keyword is used to Java throws keyword is used to


explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be


propagated using throw only. propagated with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.

5) You cannot throw multiple You can declare multiple exceptions


exceptions. e.g.
public void method()throws
IOException,SQLException.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 118


Chapter-17
Multithreading in Java

Multithreading in java is a process of executing multiple threads


simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve multitasking.

What is Thread in java ?

A thread is a lightweight sub process, a smallest unit of processing. It is a


separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn't


affect other threads. It shares a common memory area.

The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:

New

Runnable

Running

Non-Runnable (Blocked)

Terminated

How to create thread

There are two ways to create a thread:

By extending Thread class

By implementing Runnable interface.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 119


Thread class:

Thread class provide constructors and methods to create and perform


operations on a thread.Thread class extends Object class and implements
Runnable interface.

Commonly used Constructors of Thread class:


 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)
Commonly used methods of Thread class:
1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the
run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified
number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently
executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15.public void suspend(): is used to suspend the thread(depricated).
16.public void resume(): is used to resume the suspended
thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or
user thread.
20.public void interrupt(): interrupts the thread.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 120


21.public boolean isInterrupted(): tests if the thread has been
interrupted.
22.public static boolean interrupted(): tests if the current thread has
been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have
only one method named run().
1. public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
 A new thread starts(with new call stack).
 The thread moves from New state to the Runnable state.
 When the thread gets a chance to execute, its target run() method
will run.
1)By extending Thread class:

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Output:thread is running...

Who makes your class object as thread object?

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 121


Thread class constructor allocates a new thread object.When you create object
of Multi class,your class constructor is invoked(provided by Compiler) from
where Thread class constructor is invoked(by super() as first statement).So
your Multi class object is thread object now.

2)By implementing the Runnable interface:

class Multi3 implements Runnable{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

t1.start();

Output: thread is running...

If you are not extending the Thread class,your class object would not be
treated as a thread object.So you need to explicitely create Thread class
object.We are passing the object of your class that implements Runnable so
that your class run() method may execute

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified
amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 122


public static void sleep(long miliseconds)throws InterruptedException

public static void sleep(long miliseconds, int nanos)throws


InterruptedException

Example of sleep method in java

class TestSleepMethod1 extends Thread

public void run()

for(int i=1;i<5;i++)

Try

Thread.sleep(500);

catch(InterruptedException e)

System.out.println(e);}

System.out.println(i);

public static void main(String args[])

TestSleepMethod1 t1=new TestSleepMethod1();

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 123


TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();

t2.start(); } }

Output:

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1


and 10. In most cases, thread schedular schedules the threads according to
their priority (known as preemptive scheduling). But it is not guaranteed
because it depends on JVM specification that which scheduling it chooses.

3 constants defiend in Thread class:

public static int MIN_PRIORITY

public static int NORM_PRIORITY

public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY


is 1 and the value of MAX_PRIORITY is 10.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 124


Example of priority of a Thread:

class TestMultiPriority1 extends Thread{

public void run(){

System.out.println("running thread name is:"+Thread.currentThread().getNa


me());

System.out.println("running thread priority is:"+Thread.currentThread().getP


riority());

public static void main(String args[]){

TestMultiPriority1 m1=new TestMultiPriority1();

TestMultiPriority1 m2=new TestMultiPriority1();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start(); } }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 125


Chapter 18
GUI Programming in JAVA

There are two sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that
enhances the AWT, was introduced as part of Java Foundation Classes
(JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D,
Accessibility, Internationalization, and Pluggable Look-and-Feel Support
APIs. JFC was an add-on to JDK 1.1 but has been integrated into core Java
since JDK 1.2.
3. AWT contains large number of classes and methods that allows you to
create and manage windows GUI application.
AWT Hierarchy

Component class is at the top of AWT hierarchy. Component is an abstract


class that encapsulates all attribute of visual component.
Container is a component in AWT that contains another component like
button, text field, tables etc.

Container is a subclass of component class. Container class keeps track of


components that are added to another component.
Panel class is concrete sub class of Container. Panel does not contain title bar,
menu bar or border.

Window class creates a top level window. Window does not have borders and
menubar.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 126


Frame is a sub class of Window and have resizing canvas. It is a container that
contain several different components like button, title bar, textfield, label etc.
In Java, most of the AWT applications are created using Frame window.

AWT Container

AWT Controls

Frame
Frame is a container, it is java based GUI program. The class Frame is a top
level window with border and title. It will run with help of main function.

Frame class has two main constructors:


Frame
Frame(Title)
There are two main Function of frame:
setSize(int, int);
setVisible(true);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 127


We can create Frame by using constructor in your class or we also extends
Frame class as well but use setSize and setVisible.

Methods of Frame Class

void setIconImage(Image image)


Sets the image to be displayed as the icon for this window.
void setMenuBar(MenuBar mb)
Sets the menu bar for this frame to the specified menu bar.
void setResizable(boolean resizable)
Sets whether this frame is resizable by the user.
void setVisible(boolean state)
Sets the visible state of this frame.
void setTitle(String title)
Sets the title for this frame to the specified string.

Example
import java.awt.*;
public class MyFrame {
public static void main(String[] args) {
Frame f;
f=new Frame("First Frame");
f.setSize(300,300);
f.setVisible(true);
}
}

Method 2
import java.awt.*;
public class MyFrameOne extends Frame{
public MyFrameOne() {
setTitle("My");
setBackground(Color.RED);
setSize(300,300);
setVisible(true);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 128


}
public static void main(String[] args) {
MyFrameOne obj=new MyFrameOne();
}
}
Java Applet

Applet is a special type of program that is embedded in the webpage to


generate the dynamic content. It runs inside the browser and works at client
side.

Lifecycle of Java Applet

Applet is initialized.

Applet is started.

Applet is painted.

Applet is stopped.

Applet is destroyed.

Lifecycle methods for Applet

The java.applet.Applet class 4 life cycle methods and java.awt.Component class


provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4


life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 129


java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc
etc.

How to run an Applet?

There are two ways to run an applet

By html file.

By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome",150,150);

} }

Note: class must be public because its object is created by Java Plugin
software that resides on the browser.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 130


myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains


applet tag in comment and compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is for testing purpose only.

//First.java

import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){

g.drawString("welcome to applet",150,150);

} }

/*

<applet code="First.class" width="300" height="300">

</applet>

*/

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java

c:\>appletviewer First.java

Advantage of Applet

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 131


There are many advantages of applet. They are as follows:

It works at client side so less response time.

Secured

It can be executed by browsers running under many plateforms, including


Linux, Windows, Mac Os etc.

Displaying Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:

public abstract void drawString(String str, int x, int y): is used to draw the
specified string.

public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.

public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.

public abstract void drawOval(int x, int y, int width, int height): is used to
draw oval with the specified width and height.

public abstract void fillOval(int x, int y, int width, int height): is used to fill
oval with the default color and specified width and height.

public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).

public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.

public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 132


public abstract void setColor(Color c): is used to set the graphics current color
to the specified color.

public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.

Example

import java.applet.Applet;

import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){

g.setColor(Color.red);

g.drawString("Welcome",50, 50);

g.drawLine(20,30,20,300);

g.drawRect(70,100,30,30);

g.fillRect(170,100,30,30);

g.drawOval(70,200,30,30);

g.setColor(Color.pink);

g.fillOval(170,200,30,30);

g.drawArc(90,150,30,30,30,270);

g.fillArc(270,150,30,30,0,180);

} }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 133


AWT Controls

The AWT supports the following types of controls:

Labels

Buttons

Check boxes

Choice lists

Lists

TextField

TextArea

To include a control in a window, you must add it to the window. To do this,


you must first create an instance of the desired control and then add it to a
window by calling add( ), which is defined by Container.

Component add(Component compObj)

Here, compObj is an instance of the control that you want to add. A reference
to compObj is returned. Once a control has been added, it will automatically
be visible whenever its parent window is displayed.

Sometimes you will want to remove a control from a window when the control
is no longer needed. To do this, call remove( ). This method is also defined by
Container.

Label

The easiest control to use is a label. A label is an object of type Label, and it
contains a string, which it displays. Labels are passive controls that do not
support any interaction with the user. Label defines the following constructors:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 134


Label( )

Label(String str)

You can set or change the text in a label by using the setText( ) method. You
can obtain the current label by calling getText( ).

void setText(String str)

String getText( )

For setText( ), str specifies the new label. For getText( ), the current label is
returned.

Button

The most widely used control is the push button. A push button is a
component that contains a label and that generates an event when it is
pressed. Push buttons are objects of type Button. Button defines these two
constructors:

Button( )

Button(String str)

The first version creates an empty button. The second creates a button that
contains str as a label.

After a button has been created, you can set its label by calling setLabel. You
can retrieve its label by calling getLabel.

void setLabel(String str)

String getLabel( )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 135


Here, str becomes the new label for the button.

Checkbox

A check box is a control that is used to turn an option on or off. It consists of a


small box that can either contain a check mark or not. There is a label
associated with each check box that describes what option the box represents.
You change the state of a check box by clicking on it. Check boxes can be used
individually or as part of a group. Checkboxes are objects of the Checkbox
class.

Checkbox supports these constructors:

Checkbox( )

Checkbox(String str)

Checkbox(String str, boolean on)

Checkbox(String str, boolean on, CheckboxGroup cbGroup)

Checkbox(String str, CheckboxGroup cbGroup, boolean on)

Other functions are

boolean getState( )

void setState(boolean on)

String getLabel( )

void setLabel(String str)

Choice

The Choice class is used to create a pop-up list of items from which the user
may choose. Thus, a Choice control is a form of menu.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 136


Choice only defines the default constructor, which creates an empty list.To add
a selection to the list, call add( ).

void add(String name)

Here, name is the name of the item being added.

To determine which item is currently selected, you may call either


getSelectedItem( ) or getSelectedIndex( ).

The other functions are

These methods are shown here:

int getItemCount( )

void select(int index)

void select(String name)

TextField

The TextField class implements a single-line text-entry area, usually called an


edit control.

Text fields allow the user to enter strings and to edit the text using the arrow
keys, cut and paste keys, and mouse selections. TextField is a subclass of
TextComponent. TextField defines the following constructors:

TextField( )

TextField(int numChars)

TextField(String str)

TextField(String str, int numChars)

The other functions are....

String getText( )

void setText(String str)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 137


TextArea

Sometimes a single line of text input is not enough for a given task. To handle
these situations, the AWT includes a simple multiline editor called TextArea.

TextArea( )

TextArea(int numLines, int numChars)

TextArea(String str)

TextArea(String str, int numLines, int numChars)

TextArea(String str, int numLines, int numChars, int sBars)

Here, numLines specifies the height, in lines, of the text area, and numChars
specifies its width, in characters. Initial text can be specified by str. In the fifth
form you can specify the scroll bars that you want the control to have. sBars
must be one of these values:

SCROLLBARS_BOTH , SCROLLBARS_NONE

SCROLLBARS_HORIZONTAL_ONLY

SCROLLBARS_VERTICAL_ONLY

It also supports the getText( ), setText( ),getSelectedText( ), select( ), isEditable(


), and setEditable( ) methods

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 138


AWT Layout
The Layout Managers are used to arrange components in a particular manner.
Layout Manager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:

java.awt.FlowLayout

java.awt.BorderLayout

java.awt.GridLayout

java.awt.CardLayout

The layout manager is set by the setLayout( ) method. If no call to setLayout( )


is made, then the default layout manager is used.

1.FlowLayout

The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.

Fields of FlowLayout class:

public static final int LEFT

public static fioutnal int RIGHT

public static final int CENTER

Constructors of FlowLayout class:

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 139


FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.

FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

2.BorderLayout

The BorderLayout class implements a common layout style for top-level


windows. It has four narrow, fixed-width components at the edges and one
large area in the center. The four sides are referred to as north, south, east,
and west. The middle area is called the center.

BorderLayout defines the following constants that specify the regions:

BorderLayout.CENTER, BorderLayout.SOUTH

BorderLayout.EAST, BorderLayout.WEST

BorderLayout.NORTH

When adding components, you will use these constants with the following
form of

add( ), which is defined by Container:

void add(Component compObj, Object region);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 140


3.GridLayout

GridLayout lays out components in a two-dimensional grid. When you


instantiate a GridLayout, you define the number of rows and columns.

The constructors supported by GridLayout are shown here:

GridLayout( )

GridLayout(int numRows, int numColumns )

Event Handling

Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven.

Event describes the change of state of any object.

Example :

Pressing a button, Entering a character in Textbox.

Typing with keyboard or closing window.

Components of Event Handling

Event

An event is an object that describes a state change in a source. It can be


generated as a consequence of a person interacting with the elements in a

graphical user interface. Some of the activities that cause events to be


generated are pressing a button, entering a character via the keyboard,
selecting an item in a list, and clicking the mouse.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 141


Events may also occur that are not directly caused by interactions with a user
interface ie. Timer base event

Events Source : Event source is an object that generates an event.

Event Listeners

A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to
receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.

The methods that receive and process events are defined in set of interfaces
found in java.awt.event. For example, the MouseMotionListener interface
defines two methods to receive notifications when the mouse is dragged or
moved.

Event Classes

The lasses that represe t e e ts are at the ore of Ja a s e e t ha dling


mechanism. Thus, we begin our study of event handling with a tour of the
event classes. As you will see, they provide a consistent, easy-to-use means of
encapsulating events.At the root of the Java event class hierarchy is
EventObject, which is in java.util. It is the super class for all events. Its one
constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event.

EventObject contains two methods: getSource( ) and toString( ). The


getSource( )method returns the source of the event.

Its general form is shown here:

Object getSource( )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 142


Steps to perform Event Handling

Following steps are required to perform event handling:

Implement the Listener interface and overrides its methods

Register the component with the ListenerBy

addListenername(Object)

ie.

btnObject.addActionListener(this)

Main Event Listener

ActionListener

MouseListener and MouseMotionListener

KeyListener

ItemListener

TextListener

AdjustmentListener

WindowListener

ComponentListener

ContainerListener

FocusListener

Event Handler

Each Listener has one or more event handler function that must be
implemented in order to handle event response

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 143


Example – void actionPerformed (ActionEvent) of ActionListener interface.

Example of event handle program

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class MyFirstEvent extends Applet implements ActionListener {

Button btn;

public void init()

btn=new Button("Change Color");

add(btn);

btn.addActionListener(this);

public void actionPerformed(ActionEvent e) {

setBackground(Color.RED);

} } }

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 144


Chapter-19
JAVA IO
Java I/O (Input and Output) is used to process the input and produce the
output based on the input.

Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.

We can perform file handling in java by java IO API.

The io package contains a collection of stream classes that support these


algorithms for reading and writing. To use these classes, a program needs to
import the java.io package. The stream classes are divided into two class
hierarchies, based on the data type (either characters or bytes) on which they
operate.

Stream

A stream is a sequence of data.In Java a stream is composed of bytes. It's


called a stream because it's like a stream of water that continues to flow.

In java, 3 streams are created for us automatically. All these streams are
attached with console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

InputStream

Java application uses an input stream to read data from a source, it may be a
file,an array,peripheral device or socket.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 145


OutputStream class

OutputStream class is an abstract class.It is the superclass of all classes


representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.

Commonly used methods of OutputStream class

Method Description

1) public void write(int)throws IOException: is used to write a byte


to the current output stream.

2) public void write(byte[])throws IOException: is used to write an array


of byte to the current output stream.

3) public void flush()throws IOException: flushes the current


output stream.

4) public void close()throws IOException: is used to close the


current output stream.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 146


InputStream class

InputStream class is an abstract class.It is the superclass of all classes


representing an input stream of bytes.

Commonly used methods of InputStream class

Method Description

1) public abstract int read()throws reads the next byte of data


IOException: from the input stream.It
returns -1 at the end of file.

2) public int available()throws IOException: returns an estimate of the


number of bytes that can be
read from the current input
stream.

3) public void close()throws IOException: is used to close the current

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 147


input stream.

Character Streams
Reader and Writer are the abstract superclasses for character streams
in java.io. Reader provides the API and partial implementation for readers--
streams that read 16-bit characters--andWriter provides the API and partial
implementation for writers--streams that write 16-bit characters. Subclasses
of Reader and Writer implement specialized streams and are divided into two
categories: those that read from or write to data sinks (shown in gray in the
following figures) and those that perform some sort of processing (shown in
white). The figure shows the class hierarchies for
the Reader and Writer classes.

Byte Streams

To read and write 8-bit bytes, programs should use the byte streams,
descendants
of InputStream and OutputStream. InputStream and OutputStream provide the
API and partial implementation for input streams (streams that read 8-bit

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 148


bytes) and output streams (streams that write 8-bit bytes). These streams are
typically used to read and write binary data such as images and sounds.

As with Reader and Writer, subclasses


of InputStream and OutputStream provide specialized I/O that falls into two
categories, as shown in the following class hierarchy figure: data sink streams
(shaded) and processing streams (unshaded).

How to read input from console –


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

public class ReadConsoleSystem {

public static void main(String[] args) {

System.out.println("Enter something here : ");

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 149


try{

BufferedReader bufferRead = new BufferedReader(new


InputStreamReader(System.in));

String s = bufferRead.readLine();

System.out.println(s);

catch(IOException e)

e.printStackTrace();

Reading and Writing Files


Java provides a number of classes and methods that allow you to read and
write files. In Java, all files are byte-oriented, and Java provides methods to
read and write bytes from and to a file. However, Java allows you to wrap a
byte-oriented file stream within a character-based object.

Two of the most often-used stream classes are FileInputStream and


FileOutputStream, which create byte streams linked to files. To open a file,
you simply create an object of one of these classes, specifying the name of the
file as an argument to the constructor. While both classes support additional,
overridden constructors, the following are the forms that we will be using:

FileInputStream(String fileName) throws FileNotFoundException


FileOutputStream(String fileName) throws FileNotFoundException

Here, fileName specifies the name of the file that you want to open. When you
create an input stream, if the file does not exist, then FileNotFoundException

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 150


is thrown. For output streams, if the file cannot be created, then
FileNotFoundException is thrown.
When an output file is opened, any preexisting file by the same name is
destroyed.

Example

import java.io.*;
class MyFileOutputStream {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good people"
+ " to come to the aid of their country\n";
byte buf[] = source.getBytes();
FileOutputStream f0 = new FileOutputStream("D:\\file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
}
}

File Class

A File object is used to obtain or manipulate the information associated with a


disk file, such as the permissions, time, date, and directory path, and to
navigate subdirectory hierarchies.

The main constructors can be used to create File objects:

File(String directoryPath)
File(String directoryPath, String filename)

File defines many methods that obtain the standard properties of a File object.

For example, getName( ) returns the name of the file, getParent( ) returns the
name of theparent directory, and exists( ) returns true if the file exists, false if
it does not.

File also includes two useful utility methods.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 151


boolean renameTo(File newName)
boolean delete( )

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 152


Chapter-20
Java Reflection API

Java Reflection is a process of examining or modifying the run time behaviour


of a class at run time.

The java.lang.Class class provides many methods that can be used to get
metadata, examine and change the run time behaviour of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection.
The first component of the Reflection API is the mechanism used to fetch
information about a class. This mechanism is built into the class named Class.
The special class Class is the universal type for the meta information that
describes objects within the Java system. Class loaders in the Java system
return objects of type class.

Up until now the three most interesting methods in this class were:

forName, which would load a class of a given name, using the current class
loader

getName, which would return the name of the class as a String object, which
was useful for identifying object references by their class name

newInstance, which would invoke the null constructor on the class (if it exists)
and return you an object instance of that class of object.

To these three useful methods the Reflection API adds some additional
methods to class Class.

These are as follows:

 getConstructor, getConstructors, getDeclaredConstructor


 getMethod, getMethods, getDeclaredMethods
 getField, getFields, getDeclaredFields
 getSuperclass
 getInterfaces
 getDeclaredClasses

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 153


In addition to these methods, many new classes were added to represent the
objects that these methods would return.
The new classes mostly are part of the java.lang.reflect package, but some of
the new basic type classes (void, Byte, and so on) are in the java.lang package.
The decision was made to put the new classes where they are by putting
classes that represented meta-data in the reflection package and classes that
represented types in the language package.

Main Classes Defined in java.lang.reflect

Array Allows you to dynamically create and manipulate arrays.

Constructor Provides information about a constructor.

Field Provides information about a field.

Method Provides information about a method.

Modifier Provides information about class and member access modifiers.

Example

import java.lang.reflect.*;

public class ReflectionDemo {

public static void main(String args[]) {

try {

Class c = Class.forName("java.awt.Graphics");

System.out.println("Constructors:");

Constructor constructors[] = c.getConstructors();

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

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 154


System.out.println(" " + constructors[i]);

System.out.println("Fields:");

Field fields[] = c.getFields();

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

System.out.println(" " + fields[i]);

System.out.println("Methods:");

Method methods[] = c.getMethods();

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

System.out.println(" " + methods[i]);

catch(Exception e)

System.out.println("Exception: " + e);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 155


Chapter-21
Collections & Dates (util package) in Java
Collections in java is a framework that provides an architecture to store and
manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection


framework provides many interfaces (Set, List, Queue, Deque etc.) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet
etc).

What is Collection framework

Collection framework represents a unified architecture for storing and


manipulating group of objects. It has:

Interfaces and its implementations i.e. classes

Algorithm

Collection Framework
Let us see the hierarchy of collection framework.The java.util package contains
all the classes and interfaces for Collection framework.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 156


Methods of Collection interface
There are many methods declared in the Collection interface. They are as
follows:
No. Method Description
1 public boolean add(Object element) is used to insert an element in
this collection.

2 public boolean addAll(collection c) is used to insert the specified


collection elements in the invoking collection.

3 public boolean remove(Object element) is used to delete an element


from this collection.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 157


4 public boolean removeAll(Collection c) is used to delete all the
elements of specified collection from the invoking collection.

5 public boolean retainAll(Collection c) is used to delete all the


elements of invoking collection except the specified collection.

6 public int size() return the total number of


elements in the collection.

7 public void clear() removes the total no of


element from the collection.

8 public boolean contains(object element) is used to search an element.

9 public boolean containsAll(Collection c) is used to search the specified


collection in this collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

13 public boolean equals(Object element) matches two collection.

14 public int hashCode() returns the hashcode number


for collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward


direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:
1. public boolean hasNext() it returns true if iterator has more
elements.
2. public object next() it returns the element and moves the cursor
pointer to the next element.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 158


3. public void remove() it removes the last elements returned by the
iterator. It is rarely used.

List interface
The List interface extends Collection and declares the behaviour of a collection
that stores a sequence of elements. Elements can be inserted or accessed by
their position in the list, using a zero-based index. A list may contain duplicate
elements. A list is an ordered sequence of elements

interface List<E> extends Collection, Iterable

Some important List methods are:

void add(int index, E element)


E remove(int index)
boolean remove(Object o)
E set(int index, E element)
E get(int index)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator<E> listIterator() // to retrieve the values

List implementation
AbstractList Extends AbstractCollection and implements most of the List
interface.
AbstractSequentialList Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.

ArrayList Implements a dynamic array by extending AbstractList.


LinkedList extending AbstractSequentialList.

ArrayList
The ArrayList class extends AbstractList and implements the List interface.
ArrayList supports dynamic arrays that can grow as needed.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 159


ArrayList has the constructors:

ArrayList( )
ArrayList(Collection c)
ArrayList(int capacity)

Example

import java.util.*;

public class MyArrayList {

public static void main(String[] args) {


ArrayList al=new ArrayList();
al.add(new String("ABC"));
al.add(new Integer(120));
al.add(new String("Test"));
al.add(new Boolean(true));
al.add(new Integer(123));
System.out.println(al);
al.remove(1);
System.out.println(al);
Iterator its=al.iterator();
while(its.hasNext())
{
System.out.println(its.next());
}

}
Output
[ABC, 120, Test, true, 123]
[ABC, Test, true, 123]
ABC
Test
true
123

LinkedList

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 160


The LinkedList class extends AbstractSequentialList and implements the List
interface.
It provides a linked-list data structure. It has the two constructors:
LinkedList( )
LinkedList(Collection c)
The LinkedList class defines some useful methods of its own for manipulating
and accessing lists.
addFirst( )
addLast( ).
getFirst( ).
getLast( ).
removeFirst( )
removeLast( )

package com.MyCollection;
import java.util.*;
public class MyLinkedList {

/**
* @param args
*/
public static void main(String[] args) {
LinkedList lt=new LinkedList();
lt.add(12);
lt.add("RRRR");
lt.add(99);
System.out.println(lt);
lt.addFirst("WWWW");
System.out.println(lt);
lt.addLast("LLL");
System.out.println(lt);
System.out.println(lt.getLast());
System.out.println(lt.get(2));

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 161


Output
[12, RRRR, 99]
[WWWW, 12, RRRR, 99]
[WWWW, 12, RRRR, 99, LLL]
LLL
RRRR

Set Interface

The Set interface defines a set. It extends Collection and declares the behavior
of a collection that does not allow duplicate elements. Therefore, the add( )
method returns false if an attempt is made to add duplicate elements to a set.
It does not define any additional methods of its own.

AbstractSet Extends AbstractCollection and implements most of the


Set interface.

HashSet Extends AbstractSet for use with a hash table.


LinkedHashSet Extends HashSet to allow insertion-order iterations.
TreeSet Extends AbstractSet It Implements a set stored in a tree sorted order.

Set Implementations

HashSet implements the Set interface. It creates a collection that uses a hash
table for storage.

The following constructors are defined:

HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
HashSet does not define any additional methods beyond those provided by its
superclasses and interfaces.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 162


Tree Set

TreeSet provides an implementation of the Set interface that uses a tree for
storage. Objects are stored in sorted, ascending order. Access and retrieval
times are quite fast,which makes TreeSet an excellent choice when storing
large amounts of sorted information that must be found quickly.

import java.util.*;
public class MyTreeSet {

/**
* @param args
*/
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add("FFF");
ts.add("PPP");
ts.add("ZZZ");
ts.add("AAA");
ts.add("MMM");
System.out.println(ts);
Iterator its=ts.iterator();
while(its.hasNext())
{
System.out.println(its.next());
}
}
}
Output
[AAA, FFF, MMM, PPP, ZZZ]
AAA
FFF
MMM
PPP
ZZZ

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 163


The Date class
The Date class, found in the java.util package, encapsulates a long value
representing a specific moment in time. One useful constructor is Date(), which
creates a Date object representing the time the object was created.
The getTime() method returns the long value of a Date object.

Example

import java.util.*;

public class Now {

public static void main(String[] args) {

Date now = new Date();

long nowLong = now.getTime();

System.out.println("Value is " + nowLong);

The DateFormat class


DateFormat class is to create Strings in ways that humans can easily deal with
them. However, because of language differences, not all people want to see a
date in exactly the same way. Someone in France may prefer to see "25
decembre 2000," while someone in the United States may be more
accustomed to seeing "December 25, 2000." So when an instance of a

DateFormat class is created, the object contains information concerning the


particular format in which the date is to be displayed. To use the default
format of the user's computer, you can apply the

getDateInstance

method in the following way to create the appropriate

DateFormat df = DateFormat.getDateInstance();

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 164


The DateFormat class is found in the java.text package.

Converting to a String

You can convert a Date object to a string with the format method. This is
shown in the following demonstration program:

Example

import java.util.*;

import java.text.*;

public class NowString {

public static void main(String[] args) {

Date now = new Date();

DateFormat df = DateFormat.getDateInstance();

String s = df.format(now);

System.out.println("Today is " + s);

}}

DateFormat provides some ready-made constants that you can use as


arguments in the getDateInstancemethod.

Some examples are SHORT, MEDIUM, LONG, and FULL, which are
demonstrated in the program below:

Example

import java.util.*;

import java.text.*;

public class StyleDemo {

public static void main(String[] args) {

Date now = new Date();

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 165


DateFormat df = DateFormat.getDateInstance();

DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);

DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);

DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);

DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL);

String s = df.format(now);

String s1 = df1.format(now);

String s2 = df2.format(now);

String s3 = df3.format(now);

String s4 = df4.format(now);

System.out.println("(Default) Today is " + s);

System.out.println("(SHORT) Today is " + s1);

System.out.println("(MEDIUM) Today is " + s2);

System.out.println("(LONG) Today is " + s3);

System.out.println("(FULL) Today is " + s4);

That program output the following:

(Default) Today is Nov 8, 2000

(SHORT) Today is 11/8/00

(MEDIUM) Today is Nov 8, 2000

(LONG) Today is November 8, 2000

(FULL) Today is Wednesday, November 8, 2000

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 166


The GregorianCalendar class
One way to create an object representing an arbitrary date is to use the
following constructor of the GregorianCalendar class, found in
the java.utilpackage:

GregorianCalendar(int year, int month, int date)

Note that for the month, January is 0, February is 1, and so on, until December,
which is 11. Since those are not the numbers most of us associate with the
months of the year, programs will probably be more readable if they use the
constants of the parent Calendar class: JANUARY, FEBRUARY, and so on. So, to
create an object representing the date that Wilbur and Orville Wright first flew
their motored aircraft (December 17, 1903), you can use:

GregorianCalendar firstFlight = new GregorianCalendar(1903,


Calendar.DECEMBER, 17);

For clarity's sake, you should use the preceding form. However, you should
also learn how to read the shorter form, below. The following example
represents the same December 17, 1903, date (remember, in the shorter
form 11 represents December):

GregorianCalendar firstFlight = new GregorianCalendar(1903, 11, 17);

In the previous section, you learned how to turn Date objects into Strings. You
will do the same again; but first, you need to convert
a GregorianCalendarobject to a Date. To do so, you will use
the getTime() method, which GregorianCalendar inherits from its
parent Calendar class. The getTime()method returns a Date corresponding to
a GregorianCalendar object. You can put the whole process of creating
a GregorianCalendar object, converting it to a Date, and getting and outputting
the corresponding String in the following program:

import java.util.*;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 167


import java.text.*;

public class Flight {

public static void main(String[] args) {

GregorianCalendar firstFlight = new GregorianCalendar(1903,


Calendar.DECEMBER, 17);

Date d = firstFlight.getTime();

DateFormat df = DateFormat.getDateInstance();

String s = df.format(d);

System.out.println("First flight was " + s);

Example

import java.util.*;

import java.text.*;

class Today {

public static void main(String[] args) {

GregorianCalendar thisday = new GregorianCalendar();

Date d = thisday.getTime();

DateFormat df = DateFormat.getDateInstance();

String s = df.format(d);

System.out.println("Today is " + s);

}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 168


Chapter-22
Java Regex
The Java Regex or Regular Expression is an API to define pattern for searching
or manipulating strings.
It is widely used to define constraint on strings such as password and email
validation. After learning java regex tutorial, you will be able to test your own
regular expressions by the Java Regex Tester Tool.
Java Regex API provides 1 interface and 3 classes in java.util.regex package.

java.util.regex package
It provides following classes and interface for regular expressions. The Matcher
and Pattern classes are widely used in java regular expression.

MatchResult interface

Matcher class

Pattern class

PatternSyntaxException class

Matcher class

It implements MatchResult interface. It is a regex engine i.e. used to perform


match operations on a character sequence.

No. Method Description


1 boolean matches() test whether the regular expression matches
the pattern.

2 boolean find() finds the next expression that matches the


pattern.

3 boolean find(int start) finds the next expression that matches the
pattern from the given start number.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 169


Pattern class
It is the compiled version of a regular expression. It is used to define a pattern
for the regex engine.

No. Method Description


1 static Pattern compile(String regex) compiles the given regex and
return the instance of pattern.

2 Matcher matcher(CharSequence creates a matcher that matches


input) the given input with pattern.

3 static boolean matches(String regex, It works as the combination of


CharSequence input) compile and matcher methods. It
compiles the regular expression
and matches the given input with
the pattern.

4 String[] split(CharSequence input) splits the given input string


around matches of given pattern.

5 String pattern() returns the regex pattern.

Example of Java Regular Expressions

There are three ways to write the regex example in java.

import java.util.regex.*;
public class RegexExample1{
public static void main(String args[]){
//1st way
Pattern p = Pattern.compile(".s");//. represents single character
Matcher m = p.matcher("as");
boolean b = m.matches();

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 170


//2nd way
boolean b2=Pattern.compile(".s").matcher("as").matches();

//3rd way
boolean b3 = Pattern.matches(".s", "as");

System.out.println(b+" "+b2+" "+b3);


}}

Regular Expression
Example

The . (dot) represents a single character.

import java.util.regex.*;

class RegexExample2

public static void main(String args[])

System.out.println(Pattern.matches(".s", "as"));//true (2nd char is s)

System.out.println(Pattern.matches(".s", "mk"));//false (2nd char is not s)

System.out.println(Pattern.matches(".s", "mst"));//false (has more than 2 char)

System.out.println(Pattern.matches(".s", "amms"));//false (has more tha


n 2 char)

System.out.println(Pattern.matches("..s", "mas"));//true (3rd char is s)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 171


Regex Character classes

No. Character Class Description


1 [abc] a, b, or c (simple class)

2 [^abc] Any character except a, b, or c (negation)

3 [a-zA-Z] a through z or A through Z, inclusive


(range)

4 [a-d[m-p]] a through d, or m through p: [a-dm-p]


(union)

5 [a-z&&[def]] d, e, or f (intersection)

6 [a-z&&[^bc]] a through z, except for b and c: [ad-z]


(subtraction)

7 [a-z&&[^m-p]] a through z, and not m through p: [a-lq-


z](subtraction)

Regular Expression Character classes Example

import java.util.regex.*;

class RegexExample3

public static void main(String args[])


{
System.out.println(Pattern.matches("[amn]", "abcd"));//false (not a or m or n)

System.out.println(Pattern.matches("[amn]", "a"));//true (among a or m or n)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 172


System.out.println(Pattern.matches("[amn]", "ammmna"));
//false (m and a comes more than once)
}
}

Regex Quantifiers
The quantifiers specify the number of occurrences of a character.
Regex Description
X? X occurs once or not at all

X+ X occurs once or more times

X* X occurs zero or more times

X{n} X occurs n times only

X{n,} X occurs n or more times


X{y,z} X occurs at least y times but less than z times

Regular Expression Character classes and Quantifiers Example

import java.util.regex.*;

class MyRegExWild {

public static void main(String args[]) {

Pattern pat = Pattern.compile("J+");

Matcher mat = pat.matcher("J JJ JSP ASP JAVA");

int c=0;

while(mat.find())

System.out.println("Match: " + mat.group());

c=c+1;

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 173


}

System.out.print(c);
Pattern pat1 = Pattern.compile("J.P");
Matcher mat1 = pat1.matcher("J JP JSP ASP JAVA");
while(mat1.find())
System.out.println("Match: " + mat1.group());
}
}
Example to show [] usage

import java.util.regex.*;

class MyRegExWildNew {

public static void main(String args[]) {

// Match lowercase words.

Pattern pat = Pattern.compile("[a-z]+");

Matcher mat = pat.matcher("this is a test. 123456");

while(mat.find())

System.out.println("Match: " + mat.group());

String str = mat.replaceAll("New ");

System.out.println("Modified sequence: " + str);

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 174


Chapter 23
Generics

Generics was first introduced in Java5. Now it is one of the most profound
feature of java programming language. It provides facility to write algorithm
independent of any specific type of data. Generics also provide type safety.

Using Generics, it becomes possible to create a single class or method that


automatically works with all types of data (Integer, String, Float etc). It
expanded the ability to reuse code safely and easily.

Before generics, we can store any type of objects in collection i.e. non-generic.
Now generics, forces the java programmer to store specific type of objects.

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We a hold o l a si gle t pe of o je ts i ge eri s. It does t


allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

List list = new ArrayList();

list.add("hello");

String s = (String) list.get(0);//typecasting

After Generics, we don't need to typecast the object.

List<String> list = new ArrayList<String>();

list.add("hello");

String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not


occur at runtime. The good programming strategy says it is far better to handle
the problem at compile time than runtime.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 175


List<String> list = new ArrayList<String>();

list.add("hello");

list.add(32);//Compile Time Error

Syntax to use generic collection

import java.util.*;

class TestGenerics1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();

list.add("rahul");

list.add("jai");

//list.add(32);//compile time error

String s=list.get(1);//type casting is not required

System.out.println("element is: "+s);

Iterator<String> itr=list.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 176


Generic class

A class that can refer to any type is known as generic class. Here, we are
using T type parameter to create the generic class of specific type.

Let s see the simple example to create and use the generic class.

Creating generic class:

class MyGen<T>{

T obj;

void add(T obj){this.obj=obj;}

T get(){return obj;}

The T type indicates that it can refer to any type (like String, Integer, Employee
etc.). The type you specify for the class, will be used to store and retrieve the
data.

Using generic class:

Let s see the ode to use the ge eri lass.

class TestGenerics3{

public static void main(String args[]){

MyGen<Integer> m=new MyGen<Integer>();

m.add(2);

//m.add("vivek");//Compile time error

System.out.println(m.get());

}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 177


Type Parameters

The type parameters naming conventions are important to learn generics


thoroughly. The commonly type parameters are as follows:

T - Type

E - Element

K - Key

N - Number

V - Value

Generic Method

Like generic class, we can create generic method that can accept any type of
argument.

Let s see a si ple e a ple of ja a ge eri ethod to pri t arra ele e ts. We
are using here E to denote the element.

public class TestGenerics4{

public static < E > void printArray(E[] elements) {

for ( E element : elements){

System.out.println(element );

System.out.println();

public static void main( String args[] ) {

Integer[] intArray = { 10, 20, 30, 40, 50 };

Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 178


System.out.println( "Printing Integer Array" );

printArray( intArray );

System.out.println( "Printing Character Array" );

printArray( charArray );

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 179


Chapter 24
Internationalization and Localization in Java

Internationalization is also abbreviated as I18N because there are total 18


characters between the first letter 'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be
adapted to different languages and regions.
Internationalization is one of the powerful concept of java if you are
developing an application and want to display messages, currencies, date, time
etc. according to the specific region or language.
Localization is also abbreviated as I10N because there are total 10 characters
between the first letter 'L' and last letter 'N'. Localization is the mechanism to
create such an application that can be adapted to a specific language and
region by adding locale-specific text and component.

Do You Know ?

What is the use of Locale class ?

How can we globalize the messages (or) What is the use of ResourceBundle
class?

How can we internationalize the date, time, number, currency and


measurements?

Understanding the culturally dependent data before starting


internationalization

Before starting the internationalization, Let's first understand what are the
information that differ from one region to another. There is the list of
culturally dependent data:

 Messages
 Dates
 Times
 Numbers
 Currencies
 Measurements
 Phone Numbers

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 180


 Postal Addresses
 Labels on GUI components etc.
Importance of Locale class in Internationalization

An object of Locale class represents a geographical or cultural region. This


object can be used to get the locale specific information such as country name,
language, variant etc.

Fields of Locale class

 There are fields of Locale class:


 public static final Locale ENGLISH
 public static final Locale FRENCH
 public static final Locale GERMAN
 public static final Locale ITALIAN
 public static final Locale JAPANESE
 public static final Locale KOREAN
 public static final Locale CHINESE
 public static final Locale SIMPLIFIED_CHINESE
 public static final Locale TRADITIONAL_CHINESE
 public static final Locale FRANCE
 public static final Locale GERMANY
 public static final Locale ITALY
 public static final Locale JAPAN
 public static final Locale KOREA
 public static final Locale CHINA
 public static final Locale PRC
 public static final Locale TAIWAN
 public static final Locale UK
 public static final Locale US
 public static final Locale CANADA
 public static final Locale CANADA_FRENCH
 public static final Locale ROOT

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 181


Constructors of Locale class

There are three constructors of Locale class. They are as follows:


1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)

Commonly used methods of Locale class

There are given commonly used methods of Locale class.

public static Locale getDefault() it returns the instance of current Locale

public static Locale[] getAvailableLocales() it returns an array of available


locales.

public String getDisplayCountry() it returns the country name of this locale


object.

public String getDisplayLanguage() it returns the language name of this locale


object.

public String getDisplayVariant() it returns the variant code for this locale
object.

public String getISO3Country() it returns the three letter abbreviation for the
current locale's country.

public String getISO3Language() it returns the three letter abbreviation for the
current locale's language.

Example of Local class that prints the informations of the default locale

In this example, we are displaying the informations of the default locale. If you
want to get the informations about any specific locale, comment the first line
statement and uncomment the second line statement in the main method.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 182


import java.util.*;

public class LocaleExample {

public static void main(String[] args) {

Locale locale=Locale.getDefault();

//Locale locale=new Locale("fr","fr");//for the specific locale

System.out.println(locale.getDisplayCountry());

System.out.println(locale.getDisplayLanguage());

System.out.println(locale.getDisplayName());

System.out.println(locale.getISO3Country());

System.out.println(locale.getISO3Language());

System.out.println(locale.getLanguage());

System.out.println(locale.getCountry());

Example of Local class that prints english in different languages

In this example, we are displaying english language in different language. Let's


see how english is written in french and spanish languages.

import java.util.*;

public class LocaleExample2 {

public static void main(String[] args) {

Locale enLocale = new Locale("en", "US");

Locale frLocale = new Locale("fr", "FR");

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 183


Locale esLocale = new Locale("es", "ES");

System.out.println("English language name (default): " +

enLocale.getDisplayLanguage());

System.out.println("English language name in French: " +

enLocale.getDisplayLanguage(frLocale));

System.out.println("English language name in spanish: " +

enLocale.getDisplayLanguage(esLocale));

Example of Local class that print display language of many locales

In this example, we are displaying the display lanuage of many locales.

import java.util.*;

public class LocaleEx {

public static void main(String[] args) {

Locale[] locales = { new Locale("en", "US"),

new Locale("es", "ES"), new Locale("it", "IT") };

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

String displayLanguage = locales[i].getDisplayLanguage(locales[i]);

System.out.println(locales[i].toString() + ": " + displayLanguage);

}}

} Output:en_US: English

es_ES: espa?ol

it_IT: italiano

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 184


Chapter 25
Serialization
Serialization is a process in which current state of Object will be saved in
stream of bytes. As byte stream create is platform neutral hence once objects
created in one system can be deserialized in other platform.

Use of Serialization

Write to Disk

Store in Memory

Sent byte stream to other platform over network

Save byte stream in DB(As BLOB)

How to make Serialization

Java has already provided out of the box way(java.io.Serializable Interface) to


serialize an Object. If you want any class to be serialized then that class needs
to implement serializable interface.

(Serializable is also called Marker Interface.)

After a serialized object has been written into a file, it can be read from the file
and deserialized that is, the type information and bytes that represent the
object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an


object can be serialized on one platform and deserialized on an entirely
different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams


that contain the methods for serializing and deserializing an object

The ObjectOutputStream class contains many write methods for writing


various data types………..

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 185


public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream.
Similarly, the ObjectInputStream class contains the following method for
deserializi g a o je t −

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The
return value is Object, so you will need to cast it to its appropriate data type.

Example-

Create a class that need to serialize

import java.io.*;

public class Employee implements Serializable {

public String ename;

public String eCity;

Be sure that for a class to be serialized successfully, two conditions must be


et −

The class must implement the java.io.Serializable interface.

All of the fields in the class must be serializable. If a field is not serializable, it
must be marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check
the documentation for the class. The test is simple: If the class implements
java.io.Serializable, then it is serializable; otherwise, it's not.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 186


Serialize the Object

import java.io.*;

public class SerializationClass {

public static void main(String[] args) {

Employee emp=new Employee();

emp.ename="Raju";

emp.eCity="Agra";

try

FileOutputStream fout=new FileOutputStream("Abc.txt");

ObjectOutputStream op=new ObjectOutputStream(fout);

op.writeObject(emp);

op.close();

System.out.println("Data Saved...");

catch(Exception e)

System.out.println(e.getMessage());

} } }

Now Deserialize the object using ObjectInputStream

import java.io.*;

public class DeSerializationClass {

public static void main(String[] args) throws Exception {

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 187


Employee emp=null;

FileInputStream fin=new FileInputStream("Abc.txt");

ObjectInputStream oin=new ObjectInputStream(fin);

emp=(Employee)oin.readObject();

System.out.println(emp.ename);

System.out.println(emp.eCity);

}}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 188


Chapter 26
Advanced Topics (JDK 1.5 onwards)
Enum
Enumerations was added to Java language in JDK5. Enumeration means a list of
named constant. In Java, enumeration defines a class type. An Enumeration
can have constructors, methods and instance variables. It is created
using enum keyword. Each enumeration constant is public, static and final by
default. Even though enumeration defines a class type and have constructors,
you do not instantiate an enum using new. Enumeration variables are used and
declared in much a same way as you do a primitive variable.

An enumeration can be defined simply by creating a list of enum variable. Let


us take an example for list of Subject variable, with different subjects in the
list.

enum Subject //Enumeration defined

Java, Cpp, C, Dbms

Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are
public, static final by default.

Variables of Enumeration can be defined directly without any new keyword.

Subject sub

Variables of Enumeration type can have only enumeration constants as value.

sub = Subject.Java;

Example---

public class enumk {

public enum weak

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 189


{

Sunday, Monday,Tuesday,Wednesday,Thursday,Friday;

public enumk()

System.out.println(weak.Monday);

System.out.println(weak.Saturady);

public static void main(String[] args) {

enumk obj=new enumk();

Output--

Monday

Saturday

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 190


AutoBoxing / UnBoxing

 Autoboxing and Unboxing features was added in Java5.


 Autoboxing is a process by which primitive type is automatically
encapsulated(boxed) into its equivalent type wrapper
 Auto-Unboxing is a process by which the value of object is automatically
extracted from a type wrapper.

Example of Autoboxing and Unboxing


class Test

public static void main(String[] args)

Integer iob = 100; //Autoboxing of int

int i = iob; //unboxing of Integer

System.out.println(i+" "+iob);

Character cob = 'a'; /Autoboxing of char

char ch = cob; //Auto-unboxing of Character

System.out.println(cob+" "+ch);

Output :
100 100

aa

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 191


Autoboxing / Unboxing in Expressions
Whenever we use object of Wrapper class in an expression, automatic
unboxing and boxing is done by JVM.
Integer iOb;

iOb = 100; //Autoboxing of int

++iOb;

When we perform increment operation on Integer object, it is first unboxed,


then incremented and then again reboxed into Integer type object.

This will happen always, when we will use Wrapper class objects in expressions
or conditions etc.

Benefits of Autoboxing / Unboxing

Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.

We don't have to perform Explicit typecasting.

It helps prevent errors, but may lead to unexpected results sometimes. Hence
must be used with care.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 192


Static import

The static import feature of Java 5 facilitate the java programmer to access any
static member of a class directly. There is no need to qualify it by the class
name.

Advantage of static import:

Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:

If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

Simple Example of static import

import static java.lang.System.*;

class StaticImportExample{

public static void main(String args[]){

out.println("Hello");//Now no need of System.out

out.println("Java");

Output: Hello

Java

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 193


Java Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can
be used by java compiler and JVM.

Annotations in java are used to provide additional information, so it is an


alternative option for XML and java marker interfaces.

Built-In Java Annotations


There are several built-in annotations in java. Some annotations are applied to
java code and some to other annotations.

Built-In Java Annotations used in java code

 @Override
 @SuppressWarnings
 @Deprecated

Built-In Java Annotations used in other annotations

 @Target
 @Retention
 @Inherited
 @Documented

Understanding Built-In Annotations in java

 @Override

@Override annotation assures that the subclass method is overriding the


parent class method. If it is not so, compile time error occurs.

Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is
better to mark @Override annotation that provides assurity that method is
overridden.

class Animal{
void eatSomething(){System.out.println("eating something");}
}

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 194


class Dog extends Animal{
@Override
void eatsomething(){System.out.println("eating foods");}//should be eatSomet
hing
}

class TestAnnotation1{

public static void main(String args[]){

Animal a=new Dog();

a.eatSomething();

}}

Output:Comple Time Error

@SuppressWarnings

@SuppressWarnings annotation: is used to suppress warnings issued by the


compiler.

import java.util.*;

class TestAnnotation2{

@SuppressWarnings("unchecked")

public static void main(String args[]){

ArrayList list=new ArrayList();

list.add("sonoo");

list.add("vimal");

list.add("ratan");

for(Object obj:list)

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 195


System.out.println(obj);

}}

Now no warning at compile time.

If you remove the @SuppressWarnings("unchecked") annotation, it will show


warning at compile time because we are using non-generic collection.

@Deprecated

@Deprecated annotation marks that this method is deprecated so compiler


prints warning. It informs user that it may be removed in the future versions.
So, it is better not to use such methods.

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 196


Assertion
Assertion is a statement in java. It can be used to test your assumptions about
the program.

While executing assertion, it is believed to be true. If it fails, JVM will throw an


error named AssertionError. It is mainly used for testing purpose.

It provides an effective way to detect and correct programming errors.

Syntax of using Assertion:

There are two ways to use assertion.

assert expression;

assert expression1 : expression2;

Example

import java.util.Scanner;

class AssertionExample{

public static void main( String args[] ){

Scanner scanner = new Scanner( System.in );

System.out.print("Enter ur age ");

int value = scanner.nextInt();

assert value>=18:" Not valid";

System.out.println("value is "+value);

If you use assertion, It will not run simply because assertion is disabled by
default. To enable the assertion, -ea or -enableassertions switch of java must

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 197


be used.

Compile it by: javac AssertionExample.java

Run it by: java -ea AssertionExample

Output: Enter ur age 11

Exception in thread "main" java.lang.AssertionError: Not valid

Core JAVA By – TAJENDAR ARORA (SCJP) Ph. 8449091201 Page 198

You might also like