0% found this document useful (0 votes)
2 views143 pages

Java Notes (R23)

The document provides an introduction to Java, detailing its definition as a programming language and its classification into system and application software. It outlines the features of Java, including its simplicity, object-oriented nature, security, portability, and platform independence, as well as the architecture of the Java Virtual Machine (JVM) and data types. Additionally, it covers variable declaration, initialization, and the structure of a Java program, along with the steps to develop, save, compile, and execute a Java program.

Uploaded by

siddhardhar471
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views143 pages

Java Notes (R23)

The document provides an introduction to Java, detailing its definition as a programming language and its classification into system and application software. It outlines the features of Java, including its simplicity, object-oriented nature, security, portability, and platform independence, as well as the architecture of the Java Virtual Machine (JVM) and data types. Additionally, it covers variable declaration, initialization, and the structure of a Java program, along with the steps to develop, save, compile, and execute a Java program.

Uploaded by

siddhardhar471
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INTRODUCTION TO JAVA

Program: A program is a set of instructions, which are executed by a machine


to reduce the burden of a user or a human being by performing the operations
faster without any mistakes.
Software: It is a set of programs, which can perform multiple tasks.
The software’s are classified into two types.
1) System software: The softwares which are designed to interact or
communicate with the hardware devices, to make them work are called as
system software. This software’s are generally developed in languages like
C, C++ etc.
Ex: Operating System, drivers, compilers etc.

2) Application Software: The software’s which are called designed to provide


entertainment, store data, process data, do business, generate reports etc.
are called as application software. This software’s are generally developed
in languages like java, .net, etc.
The application software’s are further classified into two types.
i) Stand Alone Software: This software which can execute in the
context of a single machine are called as standalone software.
Ex: MS-Word, media player, etc.
ii) Web Based Software: This software which can execute on any
machine with the help of a browser.
Ex: Gmail, Facebook, etc
The java language is released by SUN Micro Systems in the year 1995 in three
editions:
1) JSE (Java Standard Edition): This edition can be used for developing stand
alone software.
2) JEE (Java Enterprise Edition): This edition can be used for developing web
based software.
3) JME (Java Mobile Edition): This edition can be used for developing
applications for mobile devices, wireless devices, embedded controllers etc,
where memory is limited i.e. less memory.

1
Features of Java
The features of any programming language are the services or the facilities
provided by that language. The various features of java language are:
1) Simple: The java language is called as simple programming language
because of the following reasons:
i) The syntax of java language is similar to other programming
languages like C, C+ etc. & therefore, simple to migrate from other
languages.
ii) The complex topics like pointers, templates etc. are eliminated from
java making it simple.
iii) In the java language the programmer is responsible for only
allocation of memory. The deallocation of the memory is done by
the garbage collector.
2) Object-Oriented: The java language is called as object oriented language.
Any language can be called as object oriented if the development of the
application is based on objects and classes.
Object: Any entity that exists physically in this real world which requires
some memory, is called as object.
Every object contains some properties and some actions. The properties
are the data which describes the object and the actions are the tasks or the
operations performed by the objects.
Class: A class is a collection of common properties, and common actions of
a group of objects. A class can be considered as a plan or a model or a blue
print for creating the objects. For every class we can create any number of
objects and without a class object can’t be created.
Example:
Class: Student
Object: rajesh, amit
3) SECURED: Security is one of the most important principles of any
programming language. The java language contains in-built security
programs for protecting the data from unauthorized usage.
4) Distributed: Using the distributed feature we can access the data available
in multiple machines and provide it to the user. Using this feature we can
improve the performance of the application by making the data more
available and more accessible.
5) Portable: The java language is said to be portable language using which we
can develop an application which is a collection of small components which
can be replaced and reused.

2
6) Platform Independent or Machine Independent or Architecture Neutral:
The java program can be executed on any machine irrespective of their
hardware, software, architecture, O.S. etc therefore it is called as platform
independent language.
C Language: When we compile a ‘C’ program, the compiler verifies
whether, the ‘C’ language instructions are valid not, if valid the compiler
generates .exe files containing machine language instructions.

The machine language instructions available in the .exe files generated by


the compiler can be executed only in that machine, where it is compiled. If
we want to execute the ‘C’ program in another machine, then we need to
recompile and then execute. This nature of ‘C’ language makes it machine
dependent or platform dependent language.
Java Language: When we compile a ‘java program, the compiler verifies
whether the java language instructions are valid or not, if valid the
compiler will generate .class files containing special java instructions (byte
code instructions).

The special java instructions available in the .class file generated by the
compiler can be executed on any machine with help of JVM, without
recompiling it. This nature of java language makes it platform independent.

7) Interpreted: The java language is said to interpreted language as the


execution of the program is done by the interpreter available inside the
JVM.
8) High Performance: The execution of a java program is done by an
interpreter along with a special compiler called JIT compiler, thereby
reducing the execution time and improving the performance of the
application.
9) Dynamic: The java language is said to be dynamic because the allocation of
memory is done at execution time according to the requirement.

3
10) Robust: The java language is said to be strong programming language,
because of the following reasons:
1. Memory management: In java language the allocation of memory and
deallocation of memory, both are efficient. During the memory
allocation time, there will be no wastage of memory and deallocation is
done by garbage collector which is also efficient as the unused memory
will be removed.
2. Exception handling: The errors that occur at runtime because of the
logical failure or invalid inputs are called as exceptions. When an
exception occurs, the application will be terminated abnormally and
executed incompletely. In order to execute the code completely and
terminate normally, we take the help of exception handling. The process
of exception handling in java is simple and efficient.
11) Multithreaded: A language is said to be multithreaded, if it supports
multithreading. Every thread in java program is a control. If the program
contains multiple controls then we can reduce the waiting time, and
provide response faster and thereby improving the performance.

JVM ARCHITECTURE

4
Class loader subsystem: The class loader subsystem will take .class file as the
input and perform the following operations:
a. It will load the .class file into the JVM’s memory
b. Before loading the .class file, it will verify whether the byte code
instructions are valid or not with the help of byte code verifier.
c. If the byte code instructions are valid then it will load a byte code
instruction into different areas of the JVM called runtime data areas.
Runtime data areas: These areas are available at runtime to store different
code. The various runtime data areas are:
a. Method area: This area can be used for storing all the class code along with
their method code.
b. Heap: This area can be used for storing the objects.
c. Java Stack: This area can be used for storing the methods that are under
execution. The java stack can be considered as a collection of frames,
where each frame will contain the information of only one method.
d. PC (Program Counter) Register: This register will contain the address of
the next instruction that has to be executed.
e. Java Native Stack: This area can be used for storing non-java code during
the migration of the application from non java code to java code. Non-Java
code will be called as native code.
Execution Engine: The execution engine is responsible for executing the java
program. It contains two parts
1. Interpreter
2. JIT (Just-In-Time) Compiler
Both the parts of the execution engine are responsible for executing the code
parallely, reducing the execution time, and thereby improving the performance
of the application.
Note: The JIT compiler is designed by Hot Spot Technologies and the code
executed by a JIT compiler will be called as hot spots.
Native Libraries: A library is a collection of pre-defined programs of a
language. The collection of libraries of the non java languages will be together
called as native libraries.
Native Interface: The native interface will help to load the native code from
native libraries into the java native stack.
OS(Operating System): To execute a java program the JVM requires some
resources like memory, processor etc from the machine. To get those
resources from the machine, the JVM has to communicate with the operating
system.
5
DATA TYPES
The data types represent the type of data that we store into the memory. The
data types in Java language are classified into three types:
1. Primitive data type: The primitive data types are predefined and designed
to store a single value.
Example: int, char etc.
2. Derived data type: The derived data types are predefined and designed to
store multiple values.
Example: array
3. User defined data type: If a data type is created by the user or the
programmer, then it is called as user defined data type. Using the user
defined data type we can store any number of values and any type of
values, according to the application requirement.
Example: class
Primitive data types: The primitive data types are designed to store a single
value and they are used to store the basic inputs required for a program. The
primitive data types are also called as fundamental data types.
The java language provides 8 primitive data types classified into 4 categories:
1. Integer Category
2. Floating-Point Category
3. Character Category
4. Boolean Category
Integer Category: This category can be used for storing numbers, either
positive or negative without a decimal point. Under the integer category we
have 4 primitive data types and they are:
1. byte
2. short
3. int
4. long
All the 4 primitive data types are used for storing same kind of data, but their
sizes and ranges are different so that the memory can be utilized efficiently
without any wastage.

6
Floating-Point Category: This category used for storing numbers either positive
or negative with decimal point. Under the floating point category we have two
primitive data types and they are:
1. float
2. double
Both the primitive data types under floating-point category are used for storing
same kind of data, but their sizes and ranges are different so that the memory
can be utilized efficiency without wastage.

Character Category: This category can be used for storing a single character. A
character can be represented by either one alphabet or one digit or one special
symbol. Under the character category there is only on primitive data type and
it is char.

Q) Why is the size of char 1 byte in c language and 2 bytes in java


A) When an application is developed in ‘c’ language, it uses the characters of
only english language. To store the English language characters 1 byte of
memory is sufficient. The ‘C’ language uses ASCII Character Set (0-255).
When an application is developed in java language, it uses the characters of all
the foreign languages. To store the characters of all languages 1 byte of
memory is not sufficient, therefore the size is increased to 2 bytes in java
language. The java language uses UNICODE Character Set (0-65535).

7
Boolean Category: This category is used for storing only 2 values and they are
either true or false. Under the boolean category we have only one primitive
type i.e. boolean.

Variable: A variable is a name given to a memory location where we can store


some data.

Variable Declaration: The process of specifying what type of data is stored into
the memory is called as variable declaration.
Syntax:
datatype variableName;
datatype variable1, variable2, variable3, ….;
Example:
int rollNo;
double marks;
char grade;
boolean result;
int custId, accountNumber, pinNo, age;
When a variable is declared, the memory for that variable will be allocated.
The amount of memory allocated to a variable will depend upon the data type
that is specified.
Once the memory for that variable is allocated and if we do not provide any
value to that variable, then the variable will automatically contain its default
value.

8
If we declare a variable and if don’t provide a value to that variable then that
variable will be initialized automatically with default values. If we do not want
the variable to contain default values, then we can initialize the variable with
our own values.
Syntax for initialing a variable during declaration time:
datatype variableName = value;
datatype var1 = value1, var2 = value2, …….;
Example:
int rollNo = 123;
double marks = 89.5;
char grade = ‘A’;
boolean result = true;
int age = 23, accNo = 45633, pinNo = 1212;
Initialization: The process of specifying a value to a variable for the first time is
called initialization.
The value of a variable can be changed any number of times during the
execution of the program.
Assignment: The process of specifying value to a variable from the second time
onwards or after the initialization is called assignment.
Example: double dollar = 61.45; 🡪 initialization
dollar = 62.05; 🡪 assignment
dollar = 58.34; 🡪 assignment
Keyword: The words that have predefined meaning in java or the words whose
meaning is reserved in java are called keywords.
Literal: The values that we store into a variable are called as literals.
Identifier: Any name that is used for the purpose of identification is called
identifier.

9
Rules for writing an Identifier:
1) An identifier can be a combination of alphabets, digits, underscore(_) and
dollar($).
2) An identifier must not begin with a digit. It can begin with either an
alphabet or underscore or dollar.
3) Identifier should not contain any spaces.
4) The keywords of the java language should not be used as identifier.
5) There is no restriction on the length of the identifier, but it is
recommended to write an identifier having not more than 16 characters.
6) The name of the identifier should be meaningful and appropriate to the
application.
int x = 23 ; valid but not recommended
int custId = 23; valid and recommended
Structure of java program:
package statement;
import statements;
class ClassName {
variables
methods
public static void main (String [] args) {
statements;
}
}
Specifying the package statement in a java program is optional. A java
program can contain at most one package statement. The package statement
should be the first executable statement in a program.
Specifying the import statements in a java program is optional. A java program
can contain any number of import statements. The import statements should
be specified after the package statement and before the class.
A java program can contain any number of classes and every class can contain
variables and methods, which are together called as member of the class. A
class can contain any number of members.
Execution of a java program is done by JVM and begins from main method,
whose syntax must be as follows:

10
The main method can contain any number of statements.
A java program can contain any number of comments, and they can be
specified anywhere in the program. The comments are non executable
statements.
Procedure to develop, save, compile, and execute a java program.
Step 1 Developing a java program: To develop a java program we require an
editor like, notepad, wordpad, VI editor etc.
Example:
class FirstProgram {
public static void main (string [] args) {
[Link] (“welcome to java @ inetsolv”);
}
}
Step 2 Saving a java program: A java program can be saved with any name but
the extension must be .java
Ex: [Link]
Step 3 Compiling a java program: To compile a java program we require a
command prompt and we use javac command.
Syntax: javac programname/filename with extension
Example: javac [Link]
java compiler will take the java program and verifies whether the java code is
valid or not, if valid the compiler generates .class file. The .class file generated
by the compiler will be given to the JVM for execution.
Step 4 Executing a java program: To execute a java program we require a
command prompt and we use java command.
Syntax: java ClassName without extension
Example: java FirstProgram
Output: welcome to java @ inetsolv.

Comments: The comments are used for explaining the code. The comments
make the understandability of a program faster. The comments improve the
readability of the code. The java language provides 3 types of comments

11
1. Single Line Comments
2. Multi Line Comments
3. Documentation Comments

1. Single Line Comments: Using the single line comments we can write a
message in a single line. The single line comments begin with “∕∕” symbols
and they end in the same line.
Example: ∕∕ This is a single line comment
2. Multi Line Comments: Using the multi line comments we can write the
message in multiple lines. Multi line comments begin with ∕* and ends with
*∕. In between these symbols we can specify any numbers of lines.
Example: ∕* This is line one comment
This is second line comment
This is line three comment *∕
3. Documentation Comments: Using the documentation comments we can
create the manual for the project that is developed. Using these comments
we can create the API (Application Programming Interface). The
documentation comments begins with ∕** and ends with *∕.
Example: ∕** author: inetsolv
created on: 1/1/2014
last modified on: 28/11/2014
…. */
To develop the java program we need to install java software. The java
software is a free ware, which can be downloaded from internet.
Once the java software is installed, we need to set the path. The PATH is called
an environment variable. The variables of the Operating System are called as
environment variables.
Setting the path is a process of specifying the address or location of the java
commands to the OS (operating system).
Syntax:
set PATH=C:\Program Files\Java\jdk1.6.0_21\bin;
class SecondProgram {
public static void main(String[ ] args) {
[Link](“ this is my second”);
[Link](“java program “);
[Link](“at inetsolv”);
}
}
12
Java Coding Conventions (Hungarian Notations):
Every predefined class, interface, method etc. will follow the java coding
conventions and we are recommended to follow the same conventions. It is
always a good programming practice to develop a program by following the
coding conventions.
1. Conventions for a class: A class name can contain any number of words
and the first letter of every word should be specified in uppercase.
Example: System StringBuffer SecondProgram
2. Convention for an interface: An interface name can contain any number of
words and the first letter of every word should be specified in uppercase.
Example: Runnable ActionListener MyInterface
3. Convention for a method: A method name can contain any number of
words and the first word should be specified completely in lowercase. The
first letter of the remaining words if available should be specified in
uppercase.
Example: main() toCharArray() areaOfSquare()
4. Convention for a variable: A variable name can contain any number of
words and the first word should be specified completely in lowercase. The
first letter of the remaining words, if available should be specified in
uppercase.
Example: length numberOfStudents accountNumber
5. Convention for a constant: A constant can contain any number of words.
All the letters of all the words should be specified in uppercase, if multiple
words are available then separate them by underscore (_).
Example: MIN_VALUE MAX_PRIORITY PI
6. Convention for a package: A package name should be specified completely
in lowercase.
Example: [Link] [Link] [Link]
Note: The key words of java language must be specified in lowercase only.
OPERATORS
Operator: Any symbol that performs an operation will be called as operators.
Operand: The values on which the operations are performed are called as
operands.

13
Based on the number of operands, the operators are classified into the
following categories:
1) Unary Operators: These operators will perform operations on one
operand.
2) Binary Operators: These operators will be performed operations on two
operands.
3) Ternary Operators: These operators will be performed operators on three
operands.
The operators in Java Language are classified into various categories based on
the task that is performed:
Arithmetic Operators: These operators perform simple mathematical
calculations. The various arithmetic operators are +, -, *, /, %
If both the operands are of integer type, then the result will be of integer type.
If at least one of the operand is of floating point type, then the result will be of
floating point type.
Example: 7+2 = 9, 7-2 = 5, 7*2 = 14, 7/2 = 3, 7/2.0 = 3.5, 7%2 = 1
Unary Operators: These operators will perform operations on a single
operand. The various unary operators are -, ++, --
Unary Minus( - ): It can be used to convert values from positive to negative or
negative to positive.
int temp = 23;
int temp = -23;
int temp = - (-23);
Increment Operator(++): The increment operator will increase the value of a
variable by 1. Based on the position of the increment operator, the
increment operator is classified into 2 types.
PreIncrement(++x): If the increment operator is placed before the variable
then it is called preincrement operator. The preincrement operator will use the
value after increasing it.
PostIncrement(x++): If the increment operator is placed after the variable then
it is called postincrement operator. The postincrement operator will use the
value before increasing it.
Decrement Operator(--): The decrement operator will decrease the value of a
variable by 1. Based on the position of the decrement operator, the decrement
operator is classified into 2 types.
PreDecrement(--x): If the decrement operator is placed before the variable
then it is called predecrement. The predecrement operator will use the value
after decreasing it.
14
PostDecrement(x--): If the decrement operator is placed after the variable then
it is called postdecrement. The postdecrement operator will use the value
before decreasing it.
Example:
class Operators {
public static void main (String[] args) {
int a = 6;
int b = ++a;
int c = b--;
int d = a++ + --b - --c;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
}
}
Rule 1: The increment and decrement operators can be applied to all numeric
data types( byte, short, int, long, double, float, char)
Rule 2: The increment and decrement operators can be applied to only
variables, not to constants.
Rule 3: The increment and decrement operators cannot be nested.
Assignment Operators: This operator can be used for assigning a value to a
variable. The assignment operator is =
The assignment operator will copy the value from right side to left side. On the
right side we can specify either a variable or a value or an expression but on
the left side we must specify only a variable.
Example: x = 5, y = x, z = x+y
The assignment operators can be nested after the declaration of variable but
not during the declaration.
Example:
class Operators {
public static void main(String[] args) {
int a=b=c=d=6; not valid because nested during declaration
int a, b, c, d;
a=b=c=d=6; valid because nested after declaration
int a=6,b=6, c=6,d=6; valid because there is no nesting
}
}
15
If the assignment operator is combined with other operators then it is called as
compound assignment operator(+= -= *= /= %=).
Relational Operators: These operators can be used for comparing the values.
These operators are also called as comparison operators. The various relational
operators are <, <=, >, >=, ==, !=
The relational operators can be used for creating conditions.
Example: x<y x>y x>=y x==y
The result of the condition will be of boolean type, i.e. if the condition is
satisfied, then the result will be true, otherwise the result will be false.
Rule 1: The relational operators <, <=, >, >=, can be applied to any combination
of numeric types only.
Rule 2: The relational operators ==, != also called as equality operators can be
applied to any combination of numeric types or any combination of boolean
types, but not to mixed types, i.e. one boolean and one numeric data.
Logical Operators: The logical operators can be used for combining the
conditions or complimenting the result of a condition. The various logical
operators are &, &&, I, II, ^, !
AND Operator(&): This operator can be used for combining multiple
conditions.
Syntax: (cond1) & (cond2)

The result of & operator will be of boolean type i.e. the result will be either
true or false. The result will be true only if all the conditions are true.
The & operator will evaluate all the conditions and then decide the result.
And Operator(&&): This operator can be used for combining multiple
conditions.
Syntax: (cond1) && (cond2)

16
The result of && operator will be of boolean type i.e. the result will be either
true or false. The result will be true only if all the conditions are true.
The && operator will evaluate the first condition. If the result of the first
condition is false, then it will skip the evaluation of remaining conditions and
directly decide the result as false, but if the result of first condition is true, then
it will evaluate the next condition and then decide the result.
Note: The && operator is designed to improve the performance of the
application sometimes, when the result of the first condition is false.
OR Operator(I): This operator can be used for combining multiple conditions.
Syntax: (cond1) I (cond2)

The result of | operator will be of boolean type i.e. the result will be either true
or false. The result will be true, if at least one of the condition is true.
The I pipe operator will evaluate all the conditions and then decide the result.
OR Operator(||): This operator can be used for combining multiple conditions.
Syntax: (cond1) II (cond2)

The result of II operator will be of boolean type i.e. the result will be either
true or false. The result will be true, if at least one of the conditions is true.
The II pipe operator will evaluate the first condition, if the result of the first
condition is true, then it will skip the evaluation of remaining conditions and
directly decide the result as true, but if the result of the first condition is false,
then it will evaluate the next condition and then decide the result.
Note: The II operator is designed to improve the perform of the application
sometimes, when the result of first condition is true.
X-OR Operator: This operator can be used for combining multiple conditions.
Syntax: (cond1) ^ (cond2)

17
The result of ^ operator will be of boolean type i.e. the result will be either
true or false. The result will be true if the inputs are different and if the inputs
are same the result will be false
Not operator(!): This operator can be used for complimenting the result of a
condition i.e it converts true to false or false to true.
Syntax: !(condition)
Rule: The logical operators can be applied to any combination of boolean type
only.
Bitwise Operators: This operator will perform the operation on the bits of a
number. The various bit wise operators are ~ & | ^ << >> >>>
Negation Operator(~)(tilde): This operator will convert the bits from 0 ’s to 1’s
and 1’s to 0’s

Note: ~x = x+1
Bitwise AND Operator(&): This operator will perform AND operation on the
bits of a number.

18
Bitwise OR Operator(|): This operator will perform OR operation on the bits of
number.

Bitwise X-OR Operator(^): This operator will perform X-OR operation on the
bits of number.

Left Shift Operator(<<): This operator will shift the bits of a number towards
left side by the specified number of positions.

Shifting the bits of a number towards left side by one position is equivalent to
multiplying a number by 2.
Right Shift Operator(>>): This operator will shift the bits of a number towards
right side by the specified number of positions.

Shifting the bits of a number towards right side by one position is equivalent to
dividing a number by 2.

19
Unsigned Right Shift Operator(>>>): This operator will shift the bits of a
number towards right side by the specified number of positions.
Difference between >> & >>>:
When we shift the bits of a number towards right side by using >> operator,
the sign bit of the input number will be copied as it is into the resultant i.e
positive input will lead to positive output and negative input will lead to
negative output.
When we shift the bits of a number towards right side by using >>> operator,
the sign bit will be never copied into the resultant. We will always insert a bit 0
into the sign bit of the result. i.e the result will be always positive, whether the
input is positive or negative.
Rule: Bitwise operators can be applied to any combination of numbers without
decimal point(byte, short, int, long, float, double, char).
Note: The & l ^ operators can be applied to any combination of boolean type
or any combination of numbers without decimal point.
Conditional Operator: This operator will perform a task based on a condition.
The conditional operator is ? :
Syntax: (condition) ? exp1: exp2
If the condition is satisfied, then it will evaluate the expression available after
question mark (?) and if the condition is not satisfied, then it will evaluate the
expression available after colon (:). The conditional operator is also called as
ternary operator.
max = (x > y) ? x : y
diff = (x > y) ? x-y : y-x
5 > 6 ? “hai : “bye”
2 < 3 ? 4 > 5 ? “hai” : ”hello” : ”bye”
new operator: The new operator is used for creating the object. Creating an
object means allocating memory for that class in heap memory.
class Student {
}
Student stu = new Student();
stu is called as the reference variable. It is used to refer or point to an object.
The name of the reference variable can be any valid java identifier.

20
For every class we can create any number of objects but without a class we
cannot create an object. The new operator can be used for creating an object
of predefined classes, and user defined classes.
Dot(.) Operator: This operator can used for accessing the members(variables
and methods) from a class or access a class from a package.
[Link]
[Link]
[Link]
[Link]
[Link]

CONTROL STATEMENTS
The statement of a java program will be executed in sequential order. If we
don’t want to execute the statements in sequential order i.e if we want to
execute the statements in random order according to programmer choice,
then we take the help of control statements.
The control statements will help the programmer to control the flow of
execution in a java program. The control statements are classified as following
1. Conditional statements
a. if else statement
b. switch statement
2. Iterating statements
a. for loop
b. while loop
c. do-while loop
d. for each loop
3. Transfer statements
a. break
b. continue
c. return

21
Conditional Statements:
If-else statement: if else statement can be used for executing a group of
statements based on a condition.
Syntax :
if (condition) {
statements1; if block
}
else {
statements2; else block
}
If the condition is satisfied then it will be executing if block and if the condition
is not satisfied then it will be executing else block.
Example:
class IfElseDemo {
public static void main (String[] args) {
int n = 98;
if (n%2 == 0) {
[Link](“Even Number”);
}
else {
[Link](“Odd Number”);
}
}
}
Rule 1: Specifying the condition to if else statement is mandatory and it should
be of boolean type (either a condition or boolean variable or boolean value).
Rule 2: Specifying the else block is optional.
Rule 3: Specifying the { } is optional. If we don’t specify the { } then it will
consider only one statement, and that one statement is mandatory. If we want
to consider multiple statements then specifying the { } is mandatory. Within
the { } we can specify any number of statements.
Rule 4: In if else statement we cannot execute both the blocks and we cannot
skip both the blocks, it will always execute exactly one block.

Switch statement: The switch statement can be used for executing a group of
statements based on a value.

22
Syntax:
switch (argument) {
case label1: statements1;
break;
case label2: statements2;
break;
case label3: statements3;
break;

:
default: default statements;
}
Example:
class SwitchDemo {
public static void main (String[] args) {
int ch = 2;
switch(ch) {
case 1: [Link](“First Choice”);
break;
case 2: [Link](“Second Choice”);
break;
case 3: [Link](“Third Choice”);
break;
case 4: [Link](“Fourth Choice”);
break;
default: [Link](“Wrong Choice”);
}
}
}
Rule 1: Specifying the argument to switch statement is mandatory and it
should be of either byte, short, int or char only.
Rule 2: Specifying the flower braces to switch statement is mandatory.
Rule 3: Specifying the case and default statements in switch is optional.
Rule 4: A switch statement can contain any number of cases and it can contain
at most one default.
Rule 5: The default statement can be specified anywhere in the switch
statement.

23
Rule 6: The case labels must be unique i.e. they should not be empty and they
should not be duplicated.
Rule 7: Specifying the break statement is optional. The break is a transfer
statement and it will transfer the control from inside the switch to outside the
switch, so that it skips the execution of remaining cases.
When a switch statement is executed, switch argument is compared with case
labels and execution will begin from that case onwards whose label is matching
with the argument and continues until it encounters a break statement or until
it encounters the end of switch.
For Loop: This loop can be used for executing the statements multiple times. A
for loop has to be used when we know the exact number of iterations.
Syntax:
1 2 5 8… 3 6 9…
for (initialization ; condition ; increment/decrement) {
statements; 4 7 10…
}
Example:
class ForDemo {
public static void main(String[] args) {
int n = 6;
for(int i=1; i<=10 ; i++) {
[Link] (n+” * ”+ i+” = ”+ (n*i));
}
}
}
Rule 1: All the three sections of for loop are optional. If we do not specify any
initialization and if do not specify any inc/dec, then the compiler will not
specify any initialization and will not specify any inc/dec, but if we do not
specify any condition then the compile will automatically specify a boolean
value true.
Rule 2: Specifying the section separators(;) in a for loop are mandatory.
for( ; ; ) will execute for infinite times.
Rule 3: In for loop initialization section and the inc/dec section can contain any
number of valid java statements, but the condition section must contain a
value of only boolean type.
Rule 4: The initialization section can contain multiple initializations separated
by a comma(,) all should be of same time and the data type should be specified
only one time.
24
Rule 5: The condition section can contain any number of conditions, but they
must be joined by using a logical operator(& && | || ^).
Rule 6: The inc/dec section can contain multiple increments or decrements but
separated by a comma (,)
Rule 7: If a variable is declared inside for loop, then it can be used only in that
for loop.
Rule 8: Specifying the { } is optional. If we don’t specify the { } then it will
consider only one statement, and that one statement is mandatory. If we want
to consider multiple statements then specifying the { } is mandatory. Within
the { } we can specify any number of statements.

While loop: This loop can be used for executing the statements multiple times.
A while loop has to be used when we do not know the exact number of
iterations.
Syntax:
while(condition) {
statements;
}
Example:
class WhileDemo {
public static void main(String args[]) {
int n = 8 ,i = 1;
while(i <=10) {
[Link](n+” * ”+i+” = ”+(n*i));
i++;
}
}
}
Rule 1: Specifying a condition to while loop is mandatory and it should be of
boolean type.
Rule 2: Specifying the { } is optional. If we don’t specify the { } then it will
consider only one statement, and that one statement is mandatory. If we want
to consider multiple statements then specifying the { } is mandatory. Within
the { } we can specify any number of statements.
Note: A java program should not contain any unreachable statements i.e.
every statement has to be executed at some point of time.

25
Do-While loop: This loop can be used for executing the statements multiple
times. A do-while loop has to be used when we do not know the exact number
of iterations.
Syntax:
do {
statements;
} while(condition);
Example:
class DoWhileDemo {
public static void main(String args[]) {
int n = 9 ,i = 1;
do {
[Link](n+” * ”+i+” = ”+(n*i));
i++;
} while(i <=10);
}
}
Rule 1: Specifying a condition to do-while loop is mandatory and it should be of
boolean type.
Rule 2: Specifying the { } is optional. If we don’t specify the { } then we must
specify exactly only one statement. If we want to consider multiple statements
then specifying the { } is mandatory. Within the { } we can specify any number
of statements.
Nested Loop: If we specify a loop inside another loop then it is called as nested
loop. Any loop can be specified inside any other loop any number of times.
Example:
class NestedDemo {
public static void main(String[] args) {
for(int i=1;i<=5;i++) {
for(int j=1;j<=5;j++) {
[Link](“* ”);
}
[Link]();
}
}
}

26
Transfer Statements:
Break: break is a transfer statement which can be used either inside switch
statement or inside a loop.
The break statement, when used in switch will transfer the control from inside
the switch to outside the switch, so that we skip the execution of removing
cases.
The break statement, when used in loop, will transfer the control from inside
the loop to outside the loop, so that we will skip the execution of remaining
iterations.
Note: When we are specifying the break statement in a loop we are
recommended to specify the break statement along with condition.
Example:
class BreakDemo {
public static void main (string[]args) {
int sum = 0, capacity = 15;
for(int i=1,i<=100;i++) {
[Link](i);
sum = sum + i;
if(sum>=capacity)
break;
}
[Link](sum);
}
}
Continue: continue is a transfer statement which has to be used only in loops.
The continue statements will skip the current iteration and continues with the
remaining iterations.
Note: When we are specifying a continue statement in a loop, then we are
recommended to specify the continue statement along with a condition.
Example:
class ContinueDemo {
public static void main(String[] args)
for(int i=1;i<=20;i++) {
if(i==7 | i==13)
continue;
[Link](i);
}
}
}
27
ARRAYS
An array is a derived data type, which can be used for storing multiple values.
If an application requires multiple values, then we can store those multiple
values by declaring multiple variables. If we declare multiple variables in a
program then the code size will increase, and readability will be reduced.
In order to reduce the code size, and improve the readability of the code, we
take the help of arrays.
Arrays in java language are classified into two types. They are
1) Single dimension arrays
2) Multi dimension arrays
Single dimension arrays: single dimension array is a collection of multiple
values represented in the form of a single row or single column.
Syntax for declaring a single dimension array:
datatype arrayName[]; each pair of square bracket represents one dimension.
The name of the array can be any valid java identifier
Rule 1: At the time of array declaration we can specify pair of [] either before
the array name or after the array name.
Example:
int rollNo[];
double[] marks;
char []grade;
boolean result[]; result is the name of the array which can store multiple
values of boolean type.
Rule 2: At the time of array declaration we should not specify size of the array.
Synatx for Creation of single dimension Array:
datatype arrayName[] = new datatype[size];
OR
datatype arrayName[];
arrayName = new datatype[size];
Example:
int arr[] = new int[10];
OR
int arr[];
arr=new int[10];

28
Rule: Specifying the size of the array at the time of array creation is
mandatory. It should be of byte, short, int, char type only.
The size of the array must be a positive number. If a negative number is
specified, then we get a runtime error as NegativeArraySizeException.
When an array is created, the memory for that array will be allocated in
sequential memory locations. The amount of memory allocated to an array
depends upon the size of the array and the size of the data type of the array.
Once the memory for the array is allocated, all the array elements will be
initialized automatically with default values.
An array contains multiple values and for the entire array we have only one
name. In order to access the array elements we take the help of index position.
The index position will always begin with 0. The range of the index position will
be 0 to size -1. Every array is internally an object and it contains a default
variable called length, which represents the size of the array.

Syntax for accessing the array elements:


arrayName[index]
Example:
arr[0]
arr[1]
When we are accessing the array elements, we are supposed to specify the
index position within the range otherwise we get runtime error called
ArrayIndexOutOfBoundsException.
Syntax to assign a value to an array element:
arrayName[index] = value;

29
Example:
arr[0] = 10;
arr[1] = 20;
For each loop(enhanced for loop): This loop is introduced in java 1.5 version
and it designed for accessing the elements from arrays(collection). It is also
called as enhanced for loop.
Syntax:
for(declaration : arrayName) {
statements;
}
The declaration of a variable in for each loop must be same as that of the type
of elements available in the [Link] for each loop, the statements will be
executed one time for each element available in the array and therefore called
for each loop.
Example:
class ArrayDemo {
public static void main(String[] args) {
int[] arr;
arr = new int[5];
[Link](arr[0]);
[Link](arr[1]);
[Link](arr[2]);
[Link](arr[3]);
[Link](arr[4]);
arr[0] = 11;
arr[1] = 22;
arr[2] = 33;
arr[3] = 44;
arr[4] = 55;
for(int i=0; i<[Link] ;i++) {
[Link](arr[i]);
}
for(int x: arr) {
[Link](x)
}
}
}

30
Declaring, creating, and assigning the array elements in a single line.
Syntax:
datatype arrayName[] = { list of values separated by comma};
Within the { } we can specify any number of values separated by a comma.
● When we are declaring, creating and assigning the values in a single line,
then we need not specify the size of the array.
● The creation of array will be done by JVM and the size of the array is also
decided by JVM based on number o f values specified within the { }.
● Once the size of the array is decided the JVM itself will assign the values to
the array element.
Example: int [] arr = {10,20,30,40,50};

class ArrayDemo {
public static void main (String[] args) {
int[] iarr = {12,34,45,67,89};
for(int x : iarr) {
[Link](x);
}
double []darr = {1.1,2.2,.3.3,4.4,5.5,6.6};
for(double y : darr) {
[Link](y);
}
char carr[] = {‘a’,’b’,’c’,’d’};
for(char z:carr) {
[Link](z)
}
}
}

31
Multidimensional arrays: The multi dimension arrays in java will be
represented in the form of array of arrays.
Syntax for declaring a two dimension array:
datatype arrayName[][];
Rule 1: At the time of array declaration we can specify pair of [] [] either before
the array name or after the array name.
datatype arrayName[][];
int arr1[][];
int[][] arr2;
int [][]arr3;
int[] []arr4;
int []arr5[];
int[] arr6[];
Rule 2: At the time of array declaration we should not specify size of the array.
Syntax for creating 2 dimensional array :
datatype arrayName[][] = new datatype[size1][size2];
OR
datatype arrayName[][];
arrayName = new datatype[size1][size2];
Example:
int arr[][] = new int[3][4];
OR
int arr[][];
arr = new int[3][4];

32
Rule: In a multi dimension array specifying the first dimension of array is
mandatory and the remaining are optional. If we are specifying the remaining
dimensions then they must be specified in the order from left to right.
Arrays of Varying Lengths: In Java, a two-dimensional array is treated as an
array whose elements are one-dimensional arrays, which may have different
sizes, that is, different number of elements. This is not possible in C or C++.
Thus, in Java, we may declare a two-dimensional array as
int a2D [][] = new int [3 ][];
The second dimension may be defined as
a2D [0] = new int [2];
a2D [1] = new int [3];
a2D [2] = new int [4];

Example:
public class Array2D2 {
public static void main(String[] args) {
int [][] array = new int [3][];
array[0] = new int[]{ 6, 7};
array[1] = new int []{10,11,12,14};
array[2] = new int [] {2,3,4};
for (int i =0; i<3;i++)
{
for (int j = 0; j<array[i].length; j++)
[Link](array[i][j] + “ ”);
[Link]();
} } }

Example:
class Student {
public static void main(String[] args) {
int[] marks = {91,95,100,89,79,99};
int total = 0;
boolean result = true;
[Link](“student report card”);
for(int i=0; i<[Link]; i++){

33
[Link](“subject ” + (i+1)) + “ marks : ”+marks[i])
total = total + marks[i];
if(marks[i] < 35)
result = false;
}
[Link](“total marks : “ + total);
int avg = total / [Link];
[Link](“average : ”+avg);
if(result) {
if(avg >= 75) {
[Link](“Grade : Distinction”);
}
else if(avg >= 60) {
[Link](“Grade : First Class”);
}
else if(avg >= 50) {
[Link](“Grade : Second Class”);
}
else {
[Link](“Grade : Third Class”);
}
}
else {
[Link](“Welcome Again”);
}
}
}

String, StringBuffer, StringBuilder


String: String is a predefined class, which can be used for storing a group of
characters.
To store a group of characters we need to create an object of String class.
The String class object can be created in two ways.
1. The String class object can be created by using new operator
String str = new String(“hello”);

34
2. The String class object can be created by specifying a group of characters
enclosed directly in a pair of double quotes(””).
String str = “hello”;
The String objects created by both the mechanisms are called immutable
objects, which means once the String object is created we cannot modify the
content of the object.
Storage of Strings:
The objects of class String have a special storage facility, which is not available
to objects of other two String classes or to objects of any other class. The
memory allocated to a Java program is divided into two segments:
1. Stack
2. Heap
The variables are stored on heap, whereas the program is stored on stack.
Within the heap, there is a memory segment called ‘String constant pool’. The
String class objects can be created in two different ways.
String strx = “abc”;
Strings defined like this are stored in String constant pool
String strz = new String(“abcd”);
String stry = “abcd”;

The strings that are defined like String strx are stored in the String constant
pool, whereas the strings that are defined by operator new like String strz are
stored on the heap; however, they are stored outside the String constant pool,
where the objects of other classes are also stored. Important The String class
objects can be created in two different ways

String s1 = “”;// an empty string


String s2 = new String();// an empty string
String str1 = new String(“abcd”);
In String constant pool, only unique strings exist as shown by strx and stry.
Outside the String

35
Stack heap String constant pool
S1
strx
abc
stry

strz
str1
s2

abc

Immutability
abc
The string objects created by class String are immutable. By immutable, we
mean that once an object is created, its value or contents cannot be changed.
Neither the characters in the String object once created nor their case (upper
or lower) can be changed. However, new String objects can always be created
and assigned to older String object references. Thus, when you change the
content of a string by defining a new string, the old and new remain in the
memory; this causes wastage of memory. However, the immutable objects are
thread safe and so are the String objects. The objects created by class
StringBuffer are mutable and are stored on the heap segment of memory
outside the String constant pool. The contents of StringBuffer strings may be
changed without creating new objects. The methods of StringBuffer are
synchronized, and hence, they are thread safe; however, the overburden of
thread safety makes them heavy and lowers the program execution speed.
The objects of class StringBuilder are also mutable but are not thread safe;
hence, the operations are fast as compared to StringBuffer and there is no
memory loss as is the case with String class when string contents are changed.
The class StringBuilder has the same methods as the class StringBuffer.
Therefore, if multithreads are not being used, then StringBuilder class should
be used to avoid memory loss.

Property String StringBuffer StringBuilder


36
Storage area Constrant string Heap Heap
pool and heap

Object mutability Not mutable Mutable Mutable

Thread safety Safe Safe Not safe

Performance Fast Slow Fast

Interface CharSequence
It is an interface in [Link] package. It is implemented by several classes
including the classes String, StringBuffer, and StringBuilder.
It has the following four methods.
1. charcharAt(int index): The method returns character value at specified
index value.
2. int length(): This method returns the length of this (invoking) character
sequence.
3. CharSequence subsequence(int startIndex, endIndex): The method returns a
subsequence from start index to end index of this sequence. Throws
IndexOutOfBoundsException.
4. String toString(): The method returns a string containing characters of the
sequence in the same order.

Method Of String Class:


Methods for Extracting Characters from Strings
These methods may be used for manipulation of a single or a group of
characters in a string.

[Link] charAt(int n) Extracts a character at a specified index position


2. void getChars(args) Extracts more than one character at a time
[Link][] getBytes() Encodes a given string into a sequence of bytes and
returns an array of bytes

37
4. int length() Finds out the length of a given string
5. char toCharArray() Converts the string into an array of characters and
returns the array
class MethodsChar {
public static void main (String args[]){
String str1 = “Delhi”;
String str2 = “Amritsar”;
String str = “I am going to Delhi and from there to Mumbai.”;
int begin = 14; //14 and 19 are index values in str
int end = 19;
char aSTR[] = new char [end - begin];
[Link](begin, end, aSTR, 0);
[Link](“Length of string str1 = ” + [Link]());
[Link](“Fourth character in Delhi = ” + [Link](3));
[Link] (“Fifth character in str2 = ” + [Link](4));
[Link] (aSTR);

String str1 = “Delhi”;


byte[]array = [Link]();
for(int i = 0; i< [Link](); i++)
[Link] (“array[“ + i + ”] = “ + array[i]+” ”);
}
}

Methods for Comparison of Strings


The different methods used in comparison of strings are
Method Description
int compareTo Compares the invoking string with argument string
(String str) lexicographically. It returns a value less than 0, 0, or
more than 0 if the invoking string is either less than,
equal, or more than argument string, respectively
int Compares the invoking string with argument string
compareToIgnoreCas lexicographically ignoring the case differences. The
e (String str) outputs are as described for compareTo
boolean equals() Compares the characters inside the two strings.
Returns true if the match occurs, otherwise false. It is
different from operator == in which case only the

38
references of the two strings are compared.
boolean Compares the strings ignoring the case of letters
equalsIgnoreCase()
boolean Compares a specified region in one string with a
regionMatches(String specified region in another string. Returns true if the
str) two match, otherwise returns false
endsWith(String str) Returns true if a string ends with the given substring
startsWith(String str) Returns true if a string starts with the given substring

Difference between == and Method Equals()


The operator == simply compares the references, that is, whether the two
references point to the same object.
For example, let us consider the three strings.
String str1 = “Delhi”;
String str2 = “Delhi”;
String str3 = new String(“Delhi”);
All the three strings have value “Delhi”.
Here, the following code will give output true. if (str1==str2)
However, the following code will give output “false” if (str1 == str3)
The output is false because the references to the two objects str1 and str3 are
different, although the contents are same. there will be only one string “Delhi”
in the String constant pool region of heap.
The operator == does not compare the contents of the two strings. The
contents are compared by the method equals() as if ([Link](str3)) This will
give output “true”.
Operator == compares the two references and point to the same object,
whereas equals() method compares the contents of two strings.

Ex:
class MethodCompare {
public static void main (String args[]) {
String str1 = “AA”;
String str2 = “ZZ”;

39
String str3 = new String (str1);
[Link] (“str3 = ” + str 3);
[Link] (“[Link](str1)= ” + [Link](str1));
[Link] (“[Link] (str2)= ” + [Link](str2));
[Link] (“[Link] (str1)= ” + [Link](str1));
}
}

Illustration of the methods equals() and length()


class StringMethods {
public static void main (String Str[]) {
String str1 = “AA”;
String str2 = “ZZ”;
String str3 = new String (str1);
[Link] (“str3 = ” + str3);
[Link] (“[Link] (str1)= ” + [Link](str1));
[Link] (“[Link] (str2)= ” + [Link](str2));
[Link] (“[Link] (str1)= ” + [Link](str1));
[Link] (“Length of str2 = ” + [Link]());
} }

Methods for Modifying Strings


A string is an object of class String, and therefore, it cannot be modified. The
ways to modify strings are as follows:
1. Define a new string.
2. Create a new string out of substring of an existing string.
3. Create a new string by adding two or more substrings.
4. Create a new string by replacing a substring of an existing string.
5. Create a new string by trimming the existing string, that is, trim the white
spaces in the beginning and end of the existing string.
Methods for modifying strings
substring(int indexbegin) -- Creates new string as a substring of existing string
starting from indexbegin to end of string
substring (int indexbegin, int indexend) -- Creates new string that has
characters from indexbegin to indexend of the existing string

40
String concat (String S) -- Creates a new string by concating the string S with
the existing string. It returns a new String object that contains characters from
both the String objects
String replace(char current, char replacement) -- Returns string in which all
occurrences of a character are replaced with another character
String replace(Char Sequencecurrent, Char Sequence replacement) -- Returns
string in which all occurrences of a sequence of characters is replaced with
another sequence of characters
String trim() -- Trims/removes the white spaces at the beginning and the end
of current string to create a new string. Original string is obtained if there is no
white space characters at the beginning or end of string

Illustration of methods replace(), substring (), and trim()


class ModifyString {
public static void main (String args[]) {
String str1 = “Belhi”;
String mstr1 = [Link]( ‘B’, ‘D’);
[Link] (“Modified string mstr1 = ” + mstr1);
String str2 = “ WELCOME ”;
String mstr2 = [Link]();
[Link] (“mstr2 = ” + mstr2);
String str3 = “I am going to Delhi and from there to Mumbai.”;
String mstr3 = [Link](0, 19);
[Link] (“mstr3 = ” + mstr3);
String mstr4 = [Link] (19);
[Link] (“mstr4 = ” + mstr4); } }

Methods for Searching Strings The strings are searched for index value of a
particular character or substring. The following two methods are defined in
String class for the purpose.
indexOf()
1. int indexOf(int character/substring)—searches for the first occurrence of a
specified character in the string
2. int indexOf(int character/substring, int index)—searches for the first
occurrence of a specified character or substring and the search starts from the
specified index value, that is, the second argument.

lastIndexOf()

41
1. int lastIndexOf(int character/substring)—string is searched for the last
occurrence of a character or substring.
2. int lastIndexOf(int character/substring, int index)—string is searched for the
last occurrence of a character or substring, but the search starts from a
specified index value.

StringBuffer:
The class StringBuffer defines the strings that can be modified as well as the
number of characters that may be changed, replaced by another, a string that
may be appended, etc. The strings are also thread safe. For the strings created
by class StringBuffer, the compiler allocates extra capacity for 16 more
characters so that small modifications do not involve relocation of the string
that is costly in time.

StringBuffer is a predefined class, used for storing group of characters.


StringBuffer object can be created in only one way i.e. by using new operator.
Syntax:
StringBuffer sb = new StringBuffer(“welcome”);
The StringBuffer objects are mutable which means we can modify the content
of the object.
Example:
StringBuffer sb = new StringBuffer(“hai”);
sb = new StringBuffer(“hai”);

Methods Of StringBuffer:
int length(): This method will return the count of the number of characters
available in StringBuffer.
Example:
StringBuffer sb = new StringBuffer(“welcome”);
[Link](sb);

42
[Link]( [Link]());
StringBuffer append(xxxx): This method can be used to append the specified
content to the existing StringBuffer object.
Example:
StringBuffer sb = new StringBuffer(“java”);
[Link]([Link](1.7));
[Link]([Link](“program”));
StringBuffer deleteCharAt(int index): This method can be used to delete a
character that is available specified index position.
StringBuffer delete(int index, int offset): This method can be used to delete a
group of characters beginning with the specified index position up to the
specified offset.
Example:
StringBuffer sb = new StringBuffer(“java1.7program”);
[Link]([Link](sb));
[Link]([Link](3,10));
String substring(int index): This method can be used to retrieve a part of a
StringBuffer beginning from the specified index position up to the end of the
StringBuffer .
String substring(int index, int offset): This method can be used to retrieve a
part of the StringBuffer beginning from the specified index position up to the
specified offset.
Note: The substring method will not modify the content of the StringBuffer.
Example:
StringBuffer sb = new StringBuffer(“java 1.7program”);
[Link]([Link](6));
[Link]([Link](1,4));
StringBuffer insert(int index, xxx): This method can be used to insert the
specified content at the specified index position.
Example:
StringBuffer sb = new StringBuffer(“program”);
[Link]([Link](0,”java”));
[Link]([Link](4,1.7));

43
StringBuffer replace(int index, int offset, String): This method can be used to
replace a group of characters beginning with the specified index position up to
the specified offset, with the specified String.
Example:
StringBuffer sb = new StringBuffer(“java 1.7program”)
[Link]([Link] (0,4,“replace”));
StringBuffer reverse(): This method can be used to reverse the content of
StringBuffer.
Example:
StringBuffer sb = new StringBuffer(“java1.7program”);
[Link]([Link]());

Example:
class Sample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(“java”);
[Link]([Link](“program”).insert(0, “core”)
.delete(4,8) .append(“test”).replace(4,8 “frog”).substring (7)
.concat(“example”) .substring (4).replace (‘e’, ‘n’).touppercase ()
.chatAt (8));
}
}
StringBuilder: The StringBuilder class is introduced in java 1.5 version. The
StringBuilder can be used for storing group of characters.
Syntax:
StringBuilder sb = new StringBuilder(“java program”);
StringBuilder objects are mutable that is we can modify (or) update the
content of the Stringbuilder object.
Difference between StringBuffer & StringBuilder:
The StringBuffer object is synchronized (thread-safe) i.e it can be accessed by
only one thread at a time, whereas StringBuilder objects is not synchronized i.e
it can be accessed by multiple threads at a time.
Command Line Arguments: The values that we pass into the program during
the execution time in the command prompt are called as command line
arguments.

44
The purpose of command line arguments is to pass values dynamically and to
avoid hard coding.
Hard Coding: The process of providing a value to a variable within the program
is called hard coding.
As a programmer we are recommended to avoid hard coding during the
application development.
Example:
class Addition {
public static void main(String[] abc) {
int x = [Link](abc[0]);
int y = [Link](abc[1]);
int z = x + y;
[Link](z);
}
}
javac [Link]
java Addition 11 22
We are supposed to pass the command line arguments in the command
prompt during the execution time after the class name.
All the command line arguments will be stored into the string array of main
method in string format. We can convert the values from string format to
original format by using a technique is called parsing.
Parsing: It is a process of converting the value from string type to primitive
type.
Parsing can be applied to all primitives except character.
[Link]()
[Link]()
[Link]()
[Link] ()
[Link]()
[Link]()
[Link]()
As a programmer we are responsible for only declaring the array.
String[] abc;
The name of the array can be any valid java identifier.

45
The type of the array must be only string so that we can store any type of
values and any numbers of values.
It is the responsibility of the JVM to create an array and JVM itself will decide
the size of the array based on number of values specified. Once the array is
created the JVM will only assign the values to the array elements.
abc= new String[2];
abc[0] = “11”;
abc[1] = ”22”;
If we don’t specify any commad line arguments then also the JVM will create
any array of size 0.
abc = new String[0];
Buffered Reader: A program to read data from the keyboard
import [Link].*;
class Addition {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader ([Link]));
[Link](“Enter first number: ”);
String s1 = [Link]();
int fno = [Link](s1);
[Link](“Enter second number: ”);
int sno = [Link] ([Link]());
[Link](“Result : ”+(fno+sno));
}
}

Procedure To Set The Path:


Right clink on computer icon 🡪 select properties 🡪 click on advanced system
settings 🡪 select advanced tab 🡪 click on environment variables 🡪 click on either
new (or) edit button

46
Object Oriented Programming Concepts
To develop an application we require a programming language which uses one
of the following concepts.
1. Procedure oriented programming concepts
2. Object oriented programming concepts
Procedure Oriented Programming Concepts: A language is said to be
procedure oriented language, if the applications are developed with the help
of procedures or functions.
Examples of procedure oriented languages: C, Pascal, Cobal, Fortran etc.
Limitations or Drawbacks of procedure oriented programming languages:
1) The applications that are developed by using procedure oriented
programming concepts are difficult to maintain and debugging of such
application is time consuming.
2) The applications that are developed by using procedure oriented
programming concepts does not provide security to the data.
3) The applications that are developed by using procedure oriented
programming concepts gives more importance to the functions than to the
data.
4) The data available in the applications developed by using procedure
oriented programming concepts is open and therefore they are not
suitable for developing distributed application.
5) The applications that are developed by using procedure oriented
programming concepts are difficult to enhance i.e. it does not support the
integration of new modules.
6) The procedures and functions are the fundamental concepts of procedure
oriented programming concepts. The design of these fundamental
concepts is very weak therefore they are not suitable for developing real
time and complex applications.

47
Note: Procedure oriented languages also called as structured programming
languages.

Object Oriented Programming Concepts: The applications that are developed


with help of objects and classes are said to follow object oriented
programming concepts.
Example of object oriented languages: java, C++, .net, smalltalk etc.
Even though C++ is an object oriented programming language, but according to
the programming language experts it is called as partial object programming
language because of the following reasons:
i. In a C++ application we can write some code inside the class and some
code outside the class.
ii. An application in C++ can be developed without following any object
oriented programming concepts.
iii. The friend function concept can violate or break any level of security
provide to the data.
The objects and classes are the fundamentals concepts of object oriented
programming.
Object: Any entity that exists physically in the real word which requires some
memory will be called as an object. Every object will contain some properties
and some actions. The properties are the data or information which describes
the object and they are represented by variables. Actions are the tasks or the
operations performed by the object and they are represented by methods.
Class: A class is a collection of common properties and common actions of a
group of objects.
A class can be considered as a plan or a model or a blue print for creating an
object. For a class we can create any number of objects, without the class
object creation is not possible. An Object is an instance of a class.
All the object oriented programming concepts are derived from the real world,
from the human being lives so that programming becomes similar. The
programmer can understand the concepts easily an implement them without

48
any difficulty. The design of the object oriented programming concepts is very
strong and they are suitable for developing real time and complex applications.
The various object oriented concepts are:
1) Encapsulation
2) Inheritance
3) Polymorphism

Encapsulation: It is a process of binding the variables and methods into a


single entity.
● Encapsulation can be achieved with help of a class.
● Using encapsulation we can improve the maintenance of the application
● Using encapsulation we can implement abstraction (data hiding) which will
decide what to hide and what to present that is we can implement
security.
● Using encapsulation we can isolate or separate the members from one
class to another class and thereby reduce the debugging time.
Inheritance: It is a process of acquiring the members from one class to another
class.
● Using Inheritance we can achieve reusability and thereby reduce the code
size and reduce the development time of the application.
Polymorphism: If a single entity shows multiple behaviors or multiple forms,
then it is said to be polymorphism.
● Using polymorphism we can achieve flexibility where single entity can
perform different operations according to the requirements.
Class: Using a class we can achieve encapsulation and using a class we can
create user defined data type where we can store any number of values and
any type of values, according to the application requirement.
A Java program can contain any number of classes. A class can contain
variables and methods which are together called as members of the class.
Syntax for a Class:
class ClassName {
datatype variableName1;
datatype variableName2;
datatype variableName3;
returntype methodName1(list of parameters) {

49
statements;
}
returntype methodName2(list of parameters) {
statements;
}
}

Example:
class Student {
int rollNo;
double marks;
String name;
void display() {
[Link](“RollNo: “+rollNo);
[Link](“Marks: ”+marks);
[Link](“Name: ”+name);
}
public static void main(String[] args) {
[Link]( “Student Information”);
Student st = new Student();
[Link]();
}
}
When the above java program “[Link]” is compiled, the compiler will
verify whether the java code available in the program is valid or not, if valid the
compiler will generate the .class file. The .class file generated by the compiler
will be provided to the JVM for execution.
The execution of the java program will be done by the JVM and it begins from
the main(). Initially the java stack will be empty. The JVM will begin the
execution of the program by calling main(). When a method is called for
execution then that method will be pushed into the java stack and then begins
the execution.
Student st = new Student();
The above statement will create an object of Student class. Creating an object
means allocating memory for the instance variables in heap memory.

50
Instance Variable: If a variable is declared inside the class and outside the
methods, then they are called as instance variables.
If an instance variable is declared and not initialized then it will be initialized
automatically with default values of that type.
byte 0 short 0
int 0 long 0
float 0.0 double 0.0
char space boolean false
Employee null Customer null
String null AnyClass null

A class can contain any number of methods, but the JVM can call only main()
for execution. If we want other methods to be executed, then it is the
responsibility of the programmer to call the other method which has to be
executed.
[Link]();
The above statement will call display() for execution. When the display() is
called for execution, the display() will be pushed on to the top of the java stack
and then begins the execution.
When a method is completely executed then that method will be
poped(removed) from the java stack.
Every class in a java application will be represented in the form of class
diagram. The class diagram will be represented in rectangle shape with 3
partitions providing the information of class name, variables and methods
respectively.

51
A class in a java program can contain variables and methods.
Variable: The purpose of a variable is to store some value.
In a java program we can declare any number of variables. The declaration of
the variable in a java program is dynamic i.e. we can declare the variables
anywhere in the program.
The java language is called as strongly typed language. Any language can be
called as strongly typed, if the variables are first declared and then used and
whose compiler checks for type compatibility.
Method: The purpose of a method is to perform a task or an operation.
Syntax of method:
returntype methodName (list of parameters) {
statements;
}
Every method will be divided into two parts:
1) Method Declaration
2) Method Definition
Method Declaration/Header/Prototype: The method declaration consists of
three parts they are returntype, methodName and list of parameters.
● Specifying the return type and method name is mandatory, whereas
specifying the list of parameters is optional.
● We can specify any number of parameters and they can be of any type
separated by a comma.
● The return type of the method should be specified just before the method
name.
● If we don’t want the method to return any value, then specify the return
type as void. If we want the method to return a value then they do not
specify the return type as void.

52
Method Definition / Body / Implementation: The method definition is a group
of statements, that we specify with in a pair of { }.
{
statements;
}
In the method definition we can specify any number of statements. If we do
not specify any statements in the method definition, then it should be called as
empty definition or null implementation.
If the return type of the method is specified as void, then we should not specify
any return statement but if the return type of the method is not void then we
must specify the return statement in the method definition.
Syntax for return statement:
return value;
Example:
return 123;
return 3.14;
return ‘a’;
return true;
return “hello”;
● The value that we return must be compatible with the return type that is
specified.
● The return statement can be specified anywhere in the method definition.
● A method can return at must one value.
Method Invocation: The process of calling a method for the purpose of
execution will be called as invocation.
If a method is calling another method, then it is called as Calling method.
If a method is called by another method, then it is called as Called method.
The called method will always return the value to calling method.

53
Method without return type and without parameters:
Example:
class Addition {
void add() {
int a = 10;
int b = 20;
int c = a + b;
[Link](c);
}
public static void main(String[] args) {
Adition ad = new Addition();
[Link]();
}
}

Method without return type and with parameters:


Example:
class Addition {
void add(double a, double b) {
double c = a + b;
[Link](c);
}
public static void main(String[] args) {
54
Addition ad = new Addition();
double x = 1.5;
double y = 1.6;
[Link](x,y);
}
}

Method with return type and without parameters:


Example:
class Addition {
double add() {
double a = 1.4;
double b = 5.5;
double c = a + b;
return c;
}
public static void main(String[] args) {
Addition ad = new Addition();
double res = [Link]();
[Link](res);
}
}

55
Method with return type and with parameters:
Example:
class Addition {
double add(double a, double b) {
double c = a + b;
return c;
}
public static void main(String[] args) {
Addition ad = new Addition();
double res = [Link](2.3, 4.5);
[Link](res);
}
}

Method taking array as parameter:


Example1:
class ArrayDemo {
void display(double[] temp) {
for(double x : temp) {
[Link](x);
56
}
}
public static void main(String[] args) {
ArrayDemo ad = new ArrayDemo();
double arr[] = {1.2, 3.4, 5.6, 7.8};
[Link](arr);
double nos[] = {1.1, 2.2, 3.3, 4.4, 5.5};
[Link](nos);
}
}
Example2:
class ArrayDemo {
void display(char[] temp) {
for(char x : temp) {
[Link](x);
}
}
public static void main(String[] args) {
ArrayDemo ad = new ArrayDemo();
char[] arr = {‘a’, ’b’ ,’c’ ,’d’};
[Link](arr);
}
}
Method returning an array:
Example1:
class ArrayDemo {
String[] getArray() {
String[] name = {“aaa”, ”bbb”, “ccc”, “ddd”};
return name;
}
public static void main(String[] args) {
ArrayDemo ad = new ArrayDemo();
String[] abc = [Link]();
for(String x : abc) {
[Link](x);
}
}
}
Example2:

57
class ArrayDemo {
int[] getArray() {
int arr[] = {10, 20, 30, 40, 50};
return arr;
}
public static void main(String[] args) {
ArrayDemo ad = new ArrayDemo();
int[] abc = [Link]();
for(int x : abc) {
[Link](x);
}
}
}
Example3:
class ArrayDemo {
double[] add(double[] abc) {
double sum = 0.0;
for(double x : abc) {
sum = sum + x;
}
return sum;
}
public static void main(String[] args) {
ArrayDemo ad = new ArrayDemo();
double[] arr= {1.1, 2.2, 3.3, 4.4};
double res = [Link](arr);
[Link](res);
}
}
Method taking Object(user defined data type) as parameter:
Example1:
class Student {
int rollNo = 123;
double marks = 78.9;
String name = ”abcd”;
}
class ObjectDemo {
void display(Student stu) {
[Link]([Link]);
[Link]([Link]);

58
[Link]([Link]);
}
public static void main(String[] args) {
Student st = new Student();
ObjectDemo od = new ObjectDemo();
[Link](st);
}
}
Example2:
class Student {
int rollNo = 123, m1 = 60, m2 = 70, m3 = 80;
}
class ObjectDemo {
void calculate(Student stu) {
[Link]([Link]);
int sum = stu.m1 + stu.m2 + stu.m3;
[Link](sum);
int avg = sum / 3;
[Link](avg);
}
public static void main(String[] args) {
Student st = new Student();
ObjectDemo od = new ObjectDemo();
[Link](st);
}
}
Method Returning An Object:
Example:
class Customer {
int custId = 1234;
String name=”pqrs”;
}
class ObjectDemo {
public static void main(String[] args) {
ObjectDemo od = new ObjectDemo();
Customer c2 = [Link]();
[Link]([Link]);
[Link]([Link]);
}
Customer getObject() {

59
Customer c1= new Customer();
return c1;
}
}
Recursion: If a method is calling itself multiple times, then it is called as
recursion. Such methods are called as recursive methods.
Example:
class Factorial {
public static void main(String[] args) {
Factorial f = new Factorial();
for(int i=1;i<=10;i++) {
int res = [Link](i);
[Link](i+” ! = “+res);
}
}
int fact(int n) {
if(n==1)
return 1;
int x = n * fact(n-1);
return x;
}
}

Instance variable: If a variable is declared inside the class and outside the
methods, then it is called as instance variable.

If an instance variable is declared and not initialized, then it will be initialized


automatically with default value.

60
If we don’t want the instance variable to contain default values, then we can
initialize the instance variable with our own values in the following two
locations:
1. At the time of declaration
2. By using a constructor.
Constructor: A constructor is a block, which is used for initializing the instance
variables.
● The name of the constructor must be same as that of the class name.
● A constructor should not have any return type, not even void.
Note: If we specify any return type to a constructor then the code will be
valid, but it will be considered as a method instead of a constructor.
● The constructor will be executed during the object creation time.
● The constructor will execute one time for every object that is created.
● A constructor can have parameters. Based on the number of parameters,
the constructors are classified into two types:
1. Zero parameterized constructor
2. Parameterized constructor
Zero parameterized constructor: If a constructor does not have any
parameters, then it is called as zero parameterized constructor.

Syntax:
class ClassName {
ClassName() {
}
}
Parameterized constructor: If a constructor contains some parameters, then it
is called as parameterized constructor.
A parameterized constructor can contain any number of parameters and any
type of parameters separated by comma(,).
Syntax:
class ClassName {
ClassName(list of parameters) {
}
}
● Every class in java will contain a constructor whether we specify or not.
● A compiler will provide a zero parameterized constructor, only if the class
does not have any constructor.
Note: Compiler cannot provide a parameterized constructor.

61
Example:
class Student {
int rollNo;
Student() {
rollNo =123;
}
void display() {
[Link](rollNo);
}
public static void main(String[] args) {
Student stu = new Student();
[Link]();
}
}

Instance Variable: If a variable is declared inside the class and outside the
methods and outside the constructors, then it is called as instance variable.
● The memory for the instance variable will be allocated during object
creation time.
● The memory for the instance variable will be allocated in heap memory.
● The memory for the instance variable will be allocated one time for every
object that is created.
● Every object will contain its own copy of the instance variable.

❖ If we want all the objects to contain instance variable with same value,
then initialize that instance variable either at the time of declaration or by
using a zero parameterized constructor.
❖ If we want all the objects to contain instance variable with different value,
then initialize that instance variable by using a parameterized constructor.
Example:
class Student {
int rollNo;
Student(int x) {
62
rollNo = x;
}
void display () {
[Link](rollNo);
}
public static void main(String args[]) {
Student s1 = new Student(12);
[Link]();
Student s2 = new Student(34);
[Link]();
Student s3 = new Student(56);
[Link]();
}
}

this: this keyword refers to current instance(object).


This keyword can be used to access instance members (instance variable,
instance methods) of a class.
Local variable: If a variable is declared inside the class and inside the method
or inside the constructor, then it is called as local variable.
Specifying this keyword is sometimes optional and sometimes mandatory.
Optional: If there is no confusion between instance variable and local variable,
then specifying this keyword is optional. In such case, if we don’t specify this
keyword then the compiler will automatically specify this keyword and access
the instance variable.
Mandatory: If there is confusion between instance variable and local variable,
then specifying this keyboard is mandatory. In such case if we don’t specify this
keyword then the compiler will also not specify this keyword and access local
variable. If we want to access instance variable, then the program has to
explicitly specify this keyword.
Example:
class Sample {

63
int a = 11;
int b = 22;
void display() {
int b = 33;
int c = 44;
[Link](this.a);
[Link](this.b);
[Link](b);
[Link](c);
}
public static void main(String args[]) {
Sample s = new Sample();
[Link]();
}
}
Note: This keyword should not be applied to local variables.
Instance Variable: If a variable is declared inside the class and outside the
methods and outside the constructors without static keyword, then it is called
as instance variable or non static variable.
The memory for the instance variable will be allocated multiple times i.e. one
time for every object that is created. If we do not want to allocate the memory
for a variable multiple times, then declare the variable with static keyword.
▪ static keyword can be applied to both variables and methods.
Syntax for static variable:
static datatype variableName;
Syntax for static method:
static returntype methodName(list of parameters) {
statements;
}
Static Variable: If a variable is declared inside the class, outside the methods
and outside the constructors with static keyword, then it is called as static
variable.
● The memory for the static variable will be allocated during the class
loading time.
● The memory for static variable will be allocated in method area.
● The memory for static variable will be allocated one time for entire class.
● All the objects will share the same copy of the static variable.

64
The instance members(instance variables and instance methods) can be
accessed only by using reference(object).
The static members(static variables and static methods) can be accessed either
by using a class name or by using a reference(object).
Note: It is always recommended to access the static members by using class
name, because we can’t guarantee the existence of the object.
Example:
class Student {
int rollNo = 123;
static int code = 456;
public static void main (String []args) {
Student stu = new Student();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
● The class can contain both instance members(instance variables, instance
methods) and static members(static variables, static methods).
● An instance method can access both instance members and static members
directly.
● A static method can access only static members directly.
Example:
class Sample {
int x = 11;
static int y = 22;
void show() {
[Link](x);
[Link](y);
}
static void display() {
//[Link](x);
[Link](y);
}
public static void main(String[] args) {
Sample s = new Sample();
[Link]();
[Link]();
}
65
}
If a static variable is declared and not initialized, then it will be initialized
automatically with default value.
If we don’t want static variable to contain default value, then we can initialize
the static variable with our own value at the time of declaration.
Example:
class Sample {
int x;
static int y;
public static void main(Stirng[] args) {
Sample s1 = new Sample();
s1.x++;
s1.y++;
[Link](s1.x+” : ”+s1.y);
Sample s2 = new Sample();
s2.x++;
s2.y++;
[Link](s2.x+” : ”+s2.y);
Sample s3 = new Sample();
s3.x++;
s3.y++;
[Link](s3.x+” : ”+s3.y);
}
}

Rules for accessing instance and static members

66
instance instance combination: An instance method can access instance
members(instance variables and instance methods) directly provided they
belong to the same class, otherwise they must be accessed only by using
reference(object).
instance static combination: An instance method can access static
members(static variables and static methods) directly provided they belong to
the same class, otherwise they must be accessed either by using a class name
or a reference(object).
static static combination: A static method can access static members(static
variables, static methods) directly provided they belong to the same class,
otherwise they must be accessed either by using a class name or a
reference(object).
static instance combination: A static method can access instance
members(instance variables and instance methods) only by using a
reference(object) whether they belongs to same class or not.
Example:
class Access1 {
int x = 11;
static int y = 22;
void m1() {
[Link](“instance method m1”);
}
void m2() {
[Link](x); // rule 1
m1(); //rule 1
[Link](y); // rule 2
m3(); // rule 2
[Link](“instance method m2”);
}
static void m3() {
[Link](“instance method m3”);
}
public static void main(Stirng[] args) {
[Link](y); // rule 3
m3(); // rule 3
Access1 a = new Access1();
[Link](a.x); // rule 4
a.m2(); // rule 4

67
}
}
class Access2 {
void m4(){
Access1 c = new Access1();
[Link](c.x); // rule 1
c.m1(); // rule 1
[Link](Access 1.y); // rule 2
c.m3(); // rule 2
[Link](“instance method m4”);
}
public static void main(Stirng[] args) {
Access1 d = new Access1();
[Link](Access1.y); // rule 3
d.m3(); // rule 3
[Link](d.x); // rule 4
d.m1(); // rule 4
Access2 b = new Access2();
b.m4(); // rule 4
}
}
Explain public static void main(String[] args)
● public: The main method should be declared as public, so that the JVM can
access the main method from any location.
● static: The main method should be declared as static, so that the JVM can
invoke the main method directly by using class name.
● void: The caller of the main method is JVM and the JVM does not expect
any value from the main method, therefore the main method should not
return any value to JVM hence we specify the return type as void.
● main(): main is the name of the method, a valid java identifier, following
the java coding conventions and the name is fixed.
● String[]: It is used for storing command line arguments.
Note: The name of the string array can be any valid java identifier.
Note: If a declaration contains multiple modifiers, then we can specify them in
any sequence.
static public void main(String[] abc)
public static void main(String[] abc)
Explain [Link]()

68
System is a predefined class available in [Link] package.
out is a reference variable of PrintStream class declared as static in System
class.
println() is predefined method available in PrintStream. PrintStream is a
predefined class available in [Link] package.
out is a reference variable declared as static in System class and therefore it
can be accessed directly by using class name([Link]).
[Link] will provide an object of PrintStream class, using which we can
access the methods of PrintStream class and therefore we write
[Link].

Local variable: The variable that is declared inside the class and inside the
method or inside the constructor is called as local variable.
● The memory for the local variable will be allocated during the method or
constructor invocation time.
● The memory for the local variable will be allocated in the java stack.
● The memory for the local variable will be allocated one time for every
invocation. But only one copy of the local variable will be available.
If a local variable is declared and not initialized, then it will not be initialized
automatically. It is the responsibility of the programmer to initialize the local
variable either at the time of declaration or any where before using it.
If a local variable is not used, then it need not be initialized.
Note: static keyword cannot be applied to local variable.
Example:
class Sample {
int a = 11;
static int b = 22;

69
void show() {
int c = 33;
int d;
[Link](a);
[Link](b);
[Link](c);
d = 44;
[Link](d);
}
public static void main(String[] args) {
Sample s = new Sample();
[Link]();
}
}

Parameter: The values that are passed to a method or a constructor are called
as [Link] parameters of the method or a constructor will be
initialized during their invocation time.
The parameters of the method or constructor should be considered as local
variables.
Reference variable: If a variable is referring or pointing to an object, then it is
called as a reference variable.
The reference variable of any class can be declared either as instance or static
or local.
Example:
class Sample {
String s1 = new String (“hai”);
static String s2 = new String(“hello”);
public static void main(String[] args) {
String s3 = new String (“bye”);
}
}

Final: Final is a keyword which can be applied to variables, methods and


classes.
Final Variable:

70
The purpose of variable is to store some value. The value of the variable can
changed any number of times. If we do not want to change the value of the
variable, then declare the variable as final.
Syntax for final variable:
final datatype variable = value;
● Final variable must be initialized and they cannot be assigned.
● The final keyword can be applied to instance variables, static variables,
local variables, parameters and reference variables.
● By declaring the variable as final we are fixing the value of that variable. i.e
the value can’t be changed.
● By declaring the variable as final we are creating a constant in a java
program.
Instance variable: If an instance variable is declared and not initialized, then it
will be initialized automatically with default value.
Example:
class Sample {
int a;
}
If we don’t want the instance variable to contain default value, then we can
initialize the instance variable with our own value either at the time of
declaration or by using constructor.
Example:
class Sample {
int a = 10;
int b;
Sample() {
b = 20;
}
}

Final instance variable: If an instance variable is declared as final and not


initialized, then it will not be initialized automatically with default value.
class Sample {
final int a;
}
It is the responsibility of the programmer to initialize the final instance variable
either at the time of declaration or by using a constructor.

71
Example:
class Sample {
final int a = 10;
final int b = 20;
final int c;
final int d;
final int e;
Sample () {
b = 30;
c = 40;
}
void m1() {
d = 50;
}
}

Static variable: If a static variable is declared and not initialized then it will be
initialized automatically with default values.
Example:
class Sample {
static int a;
}
If don’t want a static variable to contain default values then we can initialize
the static variable with our own value at the time of declaration.
Example:
class Sample {
static int a = 10;
}
Final static variable: If a static variable is declared as final and not initialized,
then it will not be initialized automatically with default value.
Example:
class Sample {
final static int a;
}
It is the responsibility of the programmer to initialize the final static variable at
the time of declaration.
Example:
72
Class Sample {
final static int a =10;
final static int b = 20;
final static int c;
final static int d;
final static int e;
Sample () {
b = 30;
c = 40;
}
void main () {
d = 50;
}
}

Local variable: If a local variable is declared and not initialized, then it will not
be initialized automatically.
It is the responsibility of the programmer to initialize the local variable either
at the time of declaration or any where before using it.
Note: If the local variable is not used, then it need not be initialized.

Example:
class Sample {
void m1() {
int a = 10;
int b;
int c;
b = 20;
int d = a + b;
}
}
Final local variable: If a local variable is declared as final and not initialized,
then it will not be initialized automatically.
It is the responsibility of the programmer to initialize the local variable either
at the time of declaration or any where before using it.
Note: If the final local variable is not used, then it need not be initialized.

73
Example:
class Sample {
void m1() {
final int a = 10;
final int b;
final int c;
b = 20;
final int d = a + b;
}
}
Parameters: The parameters are the values that are passed to a method or a
constructor.
● The parameters of a method or a constructor can be initialized during their
invocation.
● The values of the parameters can be changed any number of times within
the method or constructor.
● If we don’t want the value of the parameter to change then declare the
parameter as final.
● A method or a constructor can contain any number of parameters and we
can declare any of them as final.

Example:
class Rectangle {
void area(final int length, int breadth) {
[Link](“area :” +(length * breadth));
breadth = 6;
[Link](“area : ” +(length *breadth));
}
public static void main(String[] ar) {
Rectangle r = new Rectangle();
[Link](3,4);
}
}
Reference variable: If a variable is referring or pointing to an object, then it is
called as reference variable.
● The reference of any class can refer to an object and later on refer to
another object of the same class.

74
● If we don’t want a reference variable to refer to another object, then
declare the reference variable as final.
● If a reference variable is declared as final, then it can’t refer to another
object but content of that object can be modify.
Example:
class Sample {
int a = 11;
int b = 22;
pulic static void main(Stirng[] ar) {
final Sample s = new Sample();
// s = new Sample();
[Link](s.a+” : ”+s.b);
s.a = 33;
s.b = 44;
[Link](s.a+” : ”+s.b);
}
}

INHERITANCE

Inheritance is a concept of acquiring the members from one class to another


class.

75
Using inheritance we can achieve reusability there by reducing the code size
and reduce the development time of the application.
The Java language supports two types of inheritance
1. Single level inheritance
2. Multi level inheritance
Single level inheritance: If the inheritance concept contains one parent class
and one child class, then it is called as single level Inheritance.

Multi level inheritance: If the inheritance concept contains one parent class,
one child class and one or more intermediate classes, then it is called multi
level inheritance.

Parent class / Super class / Base class: If a class provides members to another
class, then it is called as parent class.
Child class / Sub class / Derived class: If a class is receiving members from
another class, then it is called as child class.
Intermediate class: If a class acts as both parent class and child class, then it is
called as intermediate class.
Java doesn’t support multiple Inheritance.
Multiple Inheritance: If a class is inheriting from two or more classes then it is
called as multiple inheritance.

76
Q) Why the java language is not supporting multiple inheritance.
A) If both the parent classes contains same members, then it will be confusion
to the child class, whether to access the members from first parent or from the
second parent. To avoid this confusion, there is no concept in java language
and therefore the java does not support multiple Inheritance.
To achieve inheritance concept in a java keyword we use extends keyword.
Syntax:
class ParentClass {
}
class ChildClass extends ParentClass {
}
Example:
class Teacher {
}
class Student extends Teacher {
}
Class Diagram showing Inheritance

77
Example:
class Cone {
int x = 11;
void show() {
[Link](“cone class show()”);
}
}
class Ctwo extends Cone {
int y = 22;
void display() {
[Link](“two class display()”);
}
}
class Inheritance {
public static void main(String[] args) {
Ctwo c = new Ctwo();
[Link](c.x);
[Link]();
[Link](c.y);
[Link]();
}
}

If we create an object of parent class, then we can access the members of only
parent class, but if we create an object of child class, then we can access the
members of both parent class and child class.
Every class in java either predefined or user defined will be subclass of Object
class either directly or indirectly. The Object class is called as super most class
of all classes in java.
When a java program is compiled and if the class does not contain any parent
then the compiler will automatically specify extends Object and makes that
class as subclass of Object class.

78
When we create an object of any class, the constructor of that class has to be
executed. Before executing the constructor of that class it will verify whether
the class contains any parent class or not, if available then it will execute the
parent class constructor. But before executing the constructor of parent class it
will verify whether the parent class contain any parent or not and this process
will continue until it reaches the Object class. Once the control reaches the
Object class, it will begin the execution of the constructors.
The invocation of the constructor will be in the order of child to parent class
and the execution of the constructor will be in the order of parent to child class
and it will always begin from Object class.
Example:
class Cone {
Cone() {
[Link](“Cone constructor”);
}
}
class Ctwo extends Cone {
Ctwo() {
[Link](“Ctwo constructor”);
}
}
class Cthree extends Ctwo {
Cthree() {
[Link](“Cthree constructor”);
}
}
class Inheritance {
public static void main(String[] args) {
Cthree c = new Cthree();
}
}

79
Types Of Relationships:
1) IS-A Relationship: If a class is inheriting another class then it is called as
IS-A relationship.

Example:
class Vehicle {
}
class Car extends Vehicle {
}
Car IS-A Vehicle
Using IS-A relationship we can achieve reusability.
2) HAS-A Relationship: If a class contains an object of another class, then it is
called as HAS-A relationship.
Example:
class Engine {
}
class Car {
Engine object
}
Car HAS-A Engine
Using HAS-A relationship we can achieve reusability.

In a java application we can achieve reusability in two ways.


1) IS-A Relationship
2) HAS-A Relationship

80
Polymorphism
If a single entity shows multiple forms or multiple behaviors, then it is called as
polymorphism.
Using polymorphism we can achieve flexibility, where a single entity can
perform different operations according to the requirement.
Polymorphism is classified into two types and they are
1) Compiler Time Polymorphism
2) Run Time Polymorphism

1) Compiler Time Polymorphism: If the polymorphic nature of an entity is


decided by the compiler during the compilation time, then it is called as
compiler time polymorphism.
To achieve the compile time polymorphism, we take the help of a concept
called method overloading.
Method Overloading: The process of specifying multiple methods, having
different signature with same method name is called as method overloading.
Method Signature: The method signature includes 4 parts, they are
1) Method Name
2) Number Of Parameters
3) Type Of Parameters
4) Order Of Parameters
A class can contain any number of methods and no two methods must have
same signature i.e. every method must have different signature.
In method overloading, the methods must have same name, having either
different no of parameters or different type of parameters or different order of
parameters. The methods that participate in method overloading are called as
overloaded methods.
Note: The method signature does not include parameter names and does not
include return type of the method.
● In method overloading, the compiler will decide which method has to be
executed and therefore called compiler time polymorphism.

81
● When a method is invoked, the compiler will perform a process of linking
or binding the method invocation with the method definition, whose
signature is matching. Once the compiler performs the binding it cannot be
changed and therefore called as static binding.
● Since the binding is performed before the execution of the program, it is
called as early binding.
Example:
class Addition {
void add(int x, int y) {
[Link](“result1 : ”+(x+y));
}
void add(int x, int y, int z) {
[Link](“result2 : ”+(x+y+z));
}
void add(int x, double y) {
[Link](“result3 : ”+(x+y));
}
void add(double x, int y) {
[Link](“result4 : ”+(x+y));
}
public static void main(String[] args) {
[Link](3,4);
[Link](3,4,5);
[Link](3,4.5);
[Link](3.4,5);
}
}

Q) Why should be implement method overloading.


A) We implement method overloading to provide flexibility to the user so that,
the user can use one method to perform different operations according to the
requirement.
● Method overloading can be applied to instance methods, static methods or
both and even to main method.
Example:
class Sample {
static void show(int x) {

82
[Link](“int parameter”);
}
static void show(double y) {
[Link](“double parameter”);
}
public static void main(String[] args) {
show(12);
show(1.2);
}
}
Overloading Of main Method:
Example:
class Sample {
public static void main(String[] args) {
[Link](“string array”);
}
public static void main(String[] args) {
[Link](“string parameter”);
}
public static void main(int[] args) {
[Link](“int array”);
}
public static void main(int args) {
[Link](“int parameter”);
}
}
When a program is executed, the JVM can invoke only main method with
string array as the parameter, But as a programmer we can invoke any method
with any parameter including main method.
Example:
class Demo {
public static void main(String[] args) {
[Link](“demo class main method”);
[Link](12);
[Link](“hello”);
[Link](new int[] {4,5,6,7,8});
[Link](new String[] {“aaa”, “nn”,”zzz”});
}
}
83
Anonymous Array: An array is said to an anonymous array if the array does not
have any name.
The anonymous array has to be used when we want to use the array only one
[Link] anonymous arrays will be generally used in the process of method
invocation.
Method overloading can be implemented either in a single class or in two
different classes that have IS-A-Relationship.
Example:
class Demo {
void show(int x) {
[Link](“int value”);
}
}
class Test extends Demo {
void show(char x) {
[Link](“char value”);
}
}

2) Runtime polymorphism: If the polymorphic nature of an entity is decided by


the JVM during the runtime, then it is called as runtime polymorphism.
To achieve runtime polymorphism, we take the help of a concept called
method overriding.

Method Overriding: The process of specifying two methods with same


signature and same return type in two different classes that have IS-A
relationship is called as method overriding.
● When a method is invoked, the decision of which method to be executed is
taken by the JVM at run time and therefore called run time polymorphism.
● When a method is invoked, the JVM will perform a process of binding or
linking the method invocation with method definition of that class whose
object is created. Since the binding is done according to the object that is
created, it is called as dynamic binding.
● Since the binding is performed after the beginning of execution of the
program and after the object is created, it is called as late binding.

84
Example:
class Parent {
void msg () {
[Link](“good morning “);
}
}
class Child extends Parent {
void msg() {
[Link](“good night “);
}
}
class Polymorphism {
public static void main (String[] args) {
Parent p = new Parent ();
[Link]();
Child c = new Child ();
[Link]();
Parent p1 = new Child();
[Link]();
}
}
● The reference variable of any class can refer to its own object or it can
refer to its child class object.
Object O1 = new Object();
Object O2 = new Customer();
Object O3 = new Employee();
Object O4 = new String();
Q) Why should we implement method overriding
A) If the child class does not want the parent class method implementation,
then the child class will override that method to provide new implementation.
● The method over riding can be applied to only instance methods if the
same concept is applied to static method then it is called as method
overhiding.
● In method overriding or in method overhiding both the methods should be
either instance or static.

85
● Method overriding or method overhiding can be implemented only in two
different classes that have IS-A relation.
Constructor Overloading: The process of specifying multiple constructors with
different signature.
Example:
class Rectangle {
int length, breadth;
Rectangle() {
length = breadth = 3;
}
Rectangle(int x) {
length = breadth = x;
}
Rectangle(int length, int breadth) {
[Link] = length;
[Link] = breadth;
}
void area() {
[Link](“area : ”+(length * breadth));
}
public static void main (String[] args) {
Rectangle r1 = new Rectangle();
r1. area();
Rectangle r2 = new Rectangle(4);
r2. area();
Rectangle r3 = new Rectangle(5,6);
r3. area();
}
}
Q) Why should implement constructor over loading
A) We implement constructor overloading to provide flexibility to the user so
that, the user can create an object in different ways by passing different
values.
Note: In any class, if we are specifying a parameterized constructor then we
are recommended to specify a zero parameterized constructor whether
required or not.
● Constructor overloading can be implemented only in a single class, it can’t
be implemented in two different classes even if they have IS-A relationship.

86
● The concept of overriding is possible only there is a concept of Inheritance.
The constructors of a class can’t be inherited into another class and
therefore constructor overriding is not possible.
this keyword: this keyword will refer to the current instance(object) of a class.
Using this keyword we can access instance members(instance variables and
instance methods) of a class.
Specifying this keyword is sometimes optional, sometimes mandatory.
Optional: If there is no confusion between instance variable and local variable
then, specifying this keyword is optional. In such case, if we don’t specify this
keyword then, the compiler will automatically specify this keyword and access
instance variable.
Mandatory: If there is confusion between instance variable and local variable
then, specifying this keyword is mandatory. In such case if we don’t specify this
keyword then the compiler will also not specify this keyword and it will access
local variable. If we want to access the instance variable then the programmer
has to explicitly specify this keyword.
Note: this keyword cannot be applied to local variable.
Note: There is no concept of local methods i.e. we cannot specify a method
inside another method.
Example:
class Sample {
int a = 11;
int b = 22;
void show() {
int b = 33;
int c = 44;
[Link](this.a);
[Link](this.b);
[Link](b);
[Link](c);
[Link] ();
}
public static void main (String[] args) {
Sample s = new Sample();
[Link]()

87
}
}

this(): this() is used to refer to the zero parameterized constructor of current


class.
this(…): this(…) is used to refer to the parameterized constructor of the current
class.
Rules:
● A constructor can invoke at most one constructor.
● The invocation of the constructor must be specified as the first statement.
● The invocation of a constructor must not form a cycle or loop.
Example:
class Sample {
Sample() {
this(8);
[Link](“sample zero constructor“);
}
Sample(int x) {
[Link](“sample int constructor“);
}
Sample (double y) {
this();
[Link](“sample double constructor“);
}
public static void main (String[] args) {
Sample s = new Sample(1.2);
}
}

this:
● this keyword can be used to access the instance members of the current
class.
● this keyword can be specified either in constructors or instance methods of
the current class.
● this keyword cannot be specified in static methods.

this():
88
● this() is used to access zero parameterized constructor of the current class.
● this() can be specified in any parameterized constructor of any class.

this(…):
● this(…) is used to access parameterized constructor of the current class.
● this(…) can be specified either in zero parameterized constructor or other
parameterized constructor of the current class.
Note:
this()/this(…) are designed to called constructors from other constructors.
this()/this(…) cannot be specified in methods.
super Keyword: The super keyword is used for accessing parent class instance
members(instance variables and instance methods).
Specifying the super keyword is sometimes optional and sometimes
mandatory.
Optional: If there is no confusion between parent class instance members and
child class instance members then, specifying super keyword is optional. In
such case, if do not specify super keyword, then the compiler will automatically
specify this keyword and first search in current child class and then search in
parent class.
Mandatory: If there is confusion between parent class instance members and
child class instance members then, specifying super keyword is mandatory. In
such case, if we do not specify super keyword, then the compiler will also not
specify super keyword, instead the compiler will specify this keyword and
access current class instance members. If we want to access parent class
instance members, then the programmer has to explicitly specify super
keyword.
Note: The compiler can never specify super keyword. The super keyword
works for only one level i.e. only its parent class members.
Example:
class Test {
int a = 11;
int b = 22;
}
class Demo extends Test {
int a = 33;
int b = 44;
void m1() {

89
[Link](“demo class m1”);
}
}
class Sample extends Demo {
int a = 55;
int b = 66;
void m2() {
[Link](“sample class m2”);
}
void m3() {
[Link](“sample class m3”);
}
void show() {
int a = 77;
int c = 88;
Test t = new Test();
[Link](t.a);
[Link](b);
[Link](super.a);
[Link](c); //this .c super.c
[Link](this.a);
[Link](d); //this.d
[Link](a);
[Link](e);
m1(); //this.m1() super.m1()
super.m2();
m2(); //this.m2()
m3(); //this.m3()
}
public static void main(String[] args) {
Sample s = new Sample();
[Link]();
}
}
super(): super() can be used to access zero parameterized constructor of
parent class.
super(…): super(…) can be used to access parameterized constructor of parent
class.
Rules:

90
● Every constructor can invoke atmost one constructor of current class by
using this()/this(…) or atmost one constructor of parent class by using
super()/super(…)
● The invocation of the current class constructor by using this()/this(…) or the
invocation of the parent class constructor by using super()/super(…) must
be specified as the first statement.

Example:
class Demo {
Demo() {
[Link](“demo zero constructor”);
}
Demo(int x) {
this();
[Link](“demo para constructor”);
}
}
class Sample extends Demo {
Sample() {
this(8);
[Link](“sample zero constructor”);
}
Sample(int x) {
super(9);
[Link](“sample para constructor”);
}
public static void main(String[] args) {
Sample s = new Sample();
}
}

● super:
● super keyword can be used for accessing instance members of the parent
class.
● The super keyword can be specified either in child class constructors or
child class instance methods.
● The super keyword cannot be specified in child class static methods.

super():

91
● super() can be used to access zero parameterized constructor of parent
class
● super() can be specified in any constructor of child class.
super(…):
● super(…) can be used to access parameterized constructor of parent class.
● super(…) can be specified in any constructor of child class.

Note: super()/super(…) are designed for calling constructors from other


constructor. super()/super(…) cannot be specified in methods.
Instance Block: If we specify a group of statements within a pair of flower
braces without any keyword then, it is called as instance block.
Syntax:
{
Statements;
}
● The purpose of the instance block is to initialize instance variable.
● A class can contain any number of instance blocks and they can be
declared anywhere in the class.
● All the instance blocks will be executed in sequence from top to bottom,
one time for every object that is created.
If an instance variable is declared, not initialized then it will initialized
automatically with default values. If we do not want the instance variable to
contain default value then, we can initialize the instance variable with our own
values in the following three locations
1. At the time of declaration.
2. By using instance block
3. By using constructor
Procedure followed by the JVM during the object creation time:
● When an object is created, the JVM will go to the beginning of the class
and search for instance variables and instance blocks in sequence from top
to bottom. If the JVM encounters an instance variable, then memory for
that instance variable will be allocated and if the JVM encounters instance
block, then it will be executed (instance variables and instance blocks have
same preference.)

92
● Once the memory for all the instance variables is allocated and all the
instance blocks are executed then, the JVM will execute the constructor
that is specified.
Static Block: If we specify a group of statements within a pair of flower braces
with static keyword then, it is called as a static block.
Syntax:
static {
Statements;
}
● The purpose of the static variable is to initialize static variable.
● A class can contain any number of static blocks and they can be specified
anywhere in the class.
● All the static blocks will be executed in sequence from top to bottom, one
time during the class loading time.
If a static variable is declared and not initialized then, it will be initialized
automatically with default values. If we don’t want the static variable to
contain default value then, we can initialize a static variable with our own
values in the following two locations:
1. At the time of declaration
2. By using static block
Procedure followed by the JVM during class loading time:
● When a class is loaded, the JVM will go to the beginning of the class and
search for static variables and static blocks in sequence from top to
bottom. If the JVM encounters a static variable, then memory for that
static variable will be allocated and if the JVM encounters static, then it will
be executed (static variables and static blocks have same preference).
● Once the memory for the all the static variable is allocated and all the static
blocks are executed then, the JVM will search for main method and then
begins the execution of main method.
Example:
class Sample {
static {
[Link](“static block1”);
}
{
[Link](“instance block1”);

93
}

Sample() {
[Link](“sample zero constructor”);
}
Sample(int x) {
[Link](“sample para constructor”);
}
public static void main(String[] args) {
[Link](“sample main method ”);
Sample s1 = new Sample();
Sample s2 = new Sample(6);
}
{
[Link](“instance block2”);
}
static {
[Link](“static block2”);
}
}
Final: final keyword can be applied to variable, methods and classes.
Final variable: If a variable is declared as final then, the value of that variable
cannot be changed.
By declaring the variable as final, we are creating constant or we are fixing the
value of a variable.
The final variables must be initialized and cannot be assigned.
Final method: If a method is declared as final then, we cannot change the
implementation of that method.
We cannot override a final method.
A method should be declared as final, when we want to protect the logic or
implementation of that method.
Example:
class Parent {
final void msg () {
[Link](“we are listening ”);
94
}
}
class Child extends Parent {
void msg () {
[Link](“we are sleeping”);
}
}
The final methods can be inherited and accessed in the child class but, they
can’t be overridden.
Example:
class Parent {
final void msg() {
[Link](“we are listening ”);
}
}
class Child extends Parent {
public static void main (String[] args) {
Child c = new Child();
[Link] ();
}
}

Final class: If a class is declared as final then, that class cannot be inherited.
By declaring the class as final, we want to protect the implementation of all the
methods of that class.
Example:
final class Parent {
}
class Child extends Parent {
}
● Declarating a class as final is equivalent to declaring all the methods of that
class as final.
● The variables available in the final class or not final.
Example:
final class Parent {
int x = 12;
void msg() {
95
[Link](“we are listening”);
}
}
class Child {
public static void main(String[] args) {
Parent p = new Parent();
[Link]();
[Link](p.x);
p.x = 34;
[Link](p.x);
}
}
By declaring the class as final, we are restricting IS-A relationship and forcing to
use HAS-A relationship.
Literal: Any value that we store into a variable will be called as literal.
int literal: If we specify any number either positive or negative without decimal
point then, it will be by default considered as int literal.
Example of int literals: 123 87429 -456 0
The int literals can be stored into all numeric data types(byte, short, int, long,
float, double, char).
long literal: The long literals can be created indirectly by suffixing l or L to int
literal.
Example of long literals: 123l 87429L -456l 0L
The long literal can be stored into long, float and double type.
Note: we cannot create byte literals and short literals either directly or
indirectly.
● Under the integer category we have 4 types and they are byte, short, int
and long. The default data type of integer category is int and the default
value of integer category is 0.
double literal: The double literals can be created in two ways.
1. The double literal can be created directly by specifying any number either
positive or negative with decimal point.
Example of double literals: 23.4 5674.9 -0.0119 0.0
23.4d 5674.90D -0.0119d 0.00D

96
2. The double literal can be created indirectly by suffixing either d or D to int
literal.
Example of double literals: 23D 45679d -435d 0d
The double literal can be stored only into double type.
Float literal: The float literals can be created indirectly by suffexing f or F to
eitherint literals or to double literals.
Example of float literals: 23f 45679F -435F 0f
23.4f 5674.9f -0.0119F 0.0F
The float literals can be stored into either float type or double type.
● Under the floating point category we have two primitive data types and
they are float and double. The default data type of floating point category
is double and the default value is 0.0
Character literal: A character literal can be created by specifying exactly one
character enclosed in a pair of single quotes.
Example of char literals: ‘a’ ’N’ ‘8’ ‘$’
The character literals can be stored into all numeric data (byte, short, int, long,
float, double, char).
The character literals can be specified in UNICODE format. The UNICODE
format must begin with \ and followed by u (lower case) and followed by
exactly 4 digit hexadecimal number enclosed in a pair of single quotes.
UNICODE Format: ‘\uxxxx’ (0-9a-f or 0-9A-F)
The character literal can be created by specifying any one of the escape
sequence in a pair of single quotes.
Escape sequences of java: \n \t \r \f \b \\ \’ \”
boolean Literals: There are only two boolean literals and they are true and
false. The boolean literals can be stored only into boolean type.
● The java language provides three predefined literals and they are true,
false, and null.
The true and false literals can be stored only into boolean type and null can be
stored into any reference.
The three predefined literals must be specified in lower case only.
TypeCasting: Typecasting is the process of converting a value from one type to
another type.

97
If the values are of same type, then we do not require any typecasting.
Typecasting has to be performed, if the values are of different type and if they
are compatible.
Typecasting can be performed for the following two types:
1) Typecasting with respect to Primitive Types.
2) Typecasting with respect to Reference Types.
Typecasting with respect to Primitive Types: Typecasting with respect to
primitive types is a process of converting a value from one primitive type to
another primitive type which is compatible.
All the numeric data types are compatible to each other. The numeric data
types are byte, short, int, long, float, double and char
Widening: It is a process of converting a value from smaller primitive type to
bigger primitive type.
Syntax:

Specifying a data type with in a pair of parenthesis is called Typecasting.


In the process of widening, specifying the typecasting is optional. If we do not
specify the typecasting then, the compiler will perform the typecasting
automatically and therefore called Implicit Typecasting.
Example:
int x = 14;
double y = (double) x;
char c = ’d’;
int i = (int) c;
Narrowing: It is a process of converting a value from bigger primitive type to
smaller primitive type.
Syntax:

In the process of narrowing, specifying the typecasting is mandatory. If we do


not specify the typecasting, then the compiler cannot perform typecasting

98
automatically because there is a chance of losing data therefore, it has to be
done explicitly by the programmer hence called Explicit Typecasting.
Example:
double x = 12.34;
int y = (int) x;
int i = 97;
char c = (char)i;

Automatic Type Promotion or Implicit Type Conversion

Type Casting With Respect To Reference Type: It is a process of converting an


object from one reference type to another reference type, which is
compatible.
The reference types are said to be compatible, if their corresponding classes
have IS-A relationship.
Example:
class Parent {
void show() {
[Link](“parent class show method”);
}
void display() {
[Link](“parent class display method”);
}
}
class Child extends Parent {
void show() {
[Link](“child class show method”);
}

99
void print() {
[Link](“child class print method”);
}
}
Case 1:
class Typecasting {
public static void main(String[] args) {
Parent p = new Parent();
[Link]();
[Link]();
//[Link]();
}
}
In the above code ‘p’ is the reference of parent class, referring to an object of
parent class. Using the ‘p’ reference variable we can access the members of
only parent class.

Case 2:
class Typecasting {
public static void main(String args[]) {
Child c = new Child();
[Link]();
[Link]();
[Link]();
}
}
In the above code ‘c’ is reference variable of child class referring to an object of
child class. Using this ‘c’ reference variable we can access the members of the
parent class and child class.
Upcasting: If a child class object is referred by parent class reference then, it is
called as Upcasting.
Syntax:

100
In the process of upcasting, specifying the type casting is optional.
A reference variable of any class can refer to its own object or it can refer to
any of its child class object.
Example:
Object o1 = new Object();
Object o2 = new Customer();
Object o3 = new Employee();
Object o4 = new String();
When a java program is compiled, the compiler will check the code based on
reference type, and when the java program is executed, the JVM will execute
the program based on object type.
Case 3:
class Typecasting {
public static void main(String[] args) {
Parent p = (Parent) new Child();
[Link]();
[Link]();
//[Link]();
}
}
In the above code ‘p’ is the reference variable of parent class, referring to an
object of child class. Using the ‘p’ reference variable we can access all the
members of parent class and only those members of child class, which are
overridden.
Downcasting: If the parent class object is referred by child class reference
then, it is called as Downcasting.
Syntax:

In the process of downcasting, specifying the downcasting is mandatory.


Case 4:
class Typecasting {
public static void main(String[] args) {
Child c = (Child) new Parent();
[Link]();
[Link]();
[Link]();
101
}
}
In the above code ‘c’ is the reference variable of child class, referring to an
object of parent class. This code is valid during compilation time, and invalid
during execution time, down casting is not allowed.
Case 5:
class Typecasting {
public static void main(String[] args) {
Parent p = (parent) new Child();
Child c = (Child) p;
[Link]();
[Link]();
}
}

Example:
class Student {
}
class Employee extends Student {
void msg() {
[Link](“hello friends”);
}
}
class Typecasting {
public static void main(String[] args) {
Student s = new Employee();
Employee e = (Employee)s;
[Link] ();
}
}
Example:
class Typecasting {
public static void main(Stirng[] args) {
102
Object obj = new String();
String str = (String) obj;
[Link]([Link]());
}
}
ABSTRACT CLASSES
Concrete method: A method is said to be concrete, if it contains both
declaration and definition.
Concrete class: A class is said to be concrete, if all the methods of that class
are concrete.
A concrete class can be initialized i.e. we can create an object of concrete class
and using that object we can access the members of that class.
Abstract method: If a method contains only declaration without any definition
then, it is said to be an abstract method.
Syntax of abstract method:
abstract returntype methodName(list of parameters);
● Abstract methods must end with semi colon (;) and they must be declared
with abstract keyword.
Abstract class: If a class contains some abstract methods then, the class should
be called as abstract class.
Syntax of abstract class:
abstract class ClassName {
}
● An abstract class can be combination of abstract methods and non-abstract
(concrete) methods.
● An abstract class can contain zero or more abstract methods.
● If a class does not contain any abstract methods then, declaring the class as
abstract is optional.
● If a class contains at least one abstract method then, declaring the class as
abstract is mandatory.
An abstract class cannot be instantiated i.e. we cannot create an object of the
abstract class and therefore we cannot access the members of that class. In
order to access the members of the abstract class, we need to inherit the
abstract class into another class and override all the abstract methods
available in the abstract class.
Syntax:
abstract class AbstractClass {

103
}
class SubClass extends AbstractClass {
}
If the sub class does not override at least one abstract method then, declare
the sub class also as abstract.
Example:
abstract class Operation {
void msg() {
[Link](“hello friends”);
}
abstract void twice(int a);
}
class Programmer1 extends Operation {
void twice(int x) {
[Link](“result : ”+(x+x));
}
}
class Programmer2 extends Operation {
void twice(int y) {
[Link](“result : ” + (y*2));
}
}
class Programmer3 extends Operation {
void twice(int z) {
[Link](“result 3 : ”+(z<<1));
}
}
class AbstractDemo {
public static void main(Stirng[] args) {
Programmer1 p1 = new Programmer1();
[Link]();
[Link](5);
Programmer p2 = new Programmer2();
[Link]();
[Link](6);
Programmer p3 = new Programmer3();
[Link]();
[Link](8);

104
}
}
Q) Why should be declared a method as abstract ?
A) A method should be declared as abstract, when we want a method to be
implemented by different programmers with different logics.
Q) Why we are not allowed to instantiate an abstract class ?
A) Assume we are allowed to create an object of abstract class, using that
object if we invoke a concrete method then, it will be executed because it
contains definition, but using that object if we invoke an abstract method then,
it will lead to an unsafe operations because it does not contain any definition.
To avoid the unsafe operations, we are not allowed to instantiate an abstract
class.
Q) Why should we declare a class as abstract even though it does not contain
any abstract methods ?
A) We declare the class as abstract even though it does not contain any
abstract methods, when we don’t want an object our class to be created. By
declaring the class as abstract we are restricting HAS-A relationship and forcing
to use IS-A relationship.
● An abstract class can contain main method and it can be executed.
Example:
abstract class Sample {
public static void main(String[] args) {
[Link](“abstract class main method”);
}
}
● Every class in java, either predefined or user defined, either abstract or
concrete will be sub class of Object class either directly or indirectly
● Every class in java, either abstract class or concrete class will contain a
constructor whether we specify or not.
● The constructor of the abstract class cannot be executed directly, it can be
executed indirectly by creating an object of its child class.
● An abstract class cannot be instantiated, but we can declare a reference of
the abstract class. The reference of the abstract class can be used to refer
to an object of any of its child class which is concrete.
Example:
abstract class Shape {
int dim1, dim2;

105
Shape(int dim1, int dim2) {
this.dim1 = dim1;
this.dim2 = dim2;
}
abstract double area();
}
class Rectangle extends Shape {
Rectangle(int length, int breadth) {
super(length, breadth);
}
double area() {
return dim1 * dim2;
}
}
class Triangle extends Shape {
Triangle (int base, int height) {
super(base, height);
}
double area() {
return 0.5 * dim1 * dim2;
}
}
class Calculation {
public static void main(String[] args) {
Shape s;
s = new Rectangle(3,4);
double res = [Link]();
[Link](“Rectangle area : ”+res);
s = new Triangle(5,6);
res = [Link]();
[Link](“Triangle area : ”+res);
}
}
Modifiers: Modifiers are the keywords, which modify the meaning of a
declaration.
● The static modifier can be applied to variables, methods and inner classes.
● The final modifier can be applied to variables, methods and classes.
● The abstract modifier can be applied to methods and classes.

106
Illegal combination of modifiers for a method:
1) A method can’t be declared as abstract and final because the abstract
keyword says we must override the method where as the final keyword
says we must not override the method.
2) A method can’t be declared as abstract and static because if a static
method is invoked directly by using class name then, it will lead to unsafe
operation because it doesn’t have definition.
Illegal combination of modifiers for a class:
1) A class can’t be declared as abstract and final because the abstract
keyword says we must inherit the class whereas the final keyword says we
must not inherit the class.
● We can restrict HAS-A relationship by declaring the class as abstract and
we can restrict IS-A relationship by declaring the class as final but we can’t
restrict both relationships at the same time.
● An abstract class can have final method but a final class cannot have
abstract method.
INTERFACES
An interface is a collection of only abstract methods.
An interface can be used as a contract or an agreement for developing a
project or software etc.
Syntax:
interface InterfaceName {
variables ;
methods;
}
The name of an interface can be any valid java identifier.
Example:
interface Test {
int x =12;
void m1();
}
When a java program is compiled, the compiler generates a .class file for every
class and for every interface. When the above java program, [Link] is
compiled, the compiler will generate [Link]
javac [Link]
javap Test
107
interface Test {
public static final int x;
public abstract void m1();
}
● The variables of an interface are declared as public, static and final whether
we specify or not.
● The methods of an interface are declared as public and abstract whether
we specify or not.
public: The variables and methods of an interface are declared as public, so
that they can be accessed by any class from any location.
static: The variables of an interface are declared as static, so that they can be
accessed directly by using interface name.
final: The variables of an interface are declared as final, so that the value of
that variable does not change.
abstract: The methods of an interface are declared as abstract because they do
not have any definition.
An interface can be considered as 100% abstract and therefore interface
cannot be instantiated. In order to access the members of an interface, we
need to inherit the interface into another class by using implements keyword.
Example:
interface InterfaceName {
}
class SubClass implements InterfaceName {
}
Inheriting can interface should also be represented by IS-A relationship.

Class Diagram showing implementing an Interface:

108
● If a class is implementing an interface then that class must provide
implementation to all the methods available in that interface.
● It the subclass does not provide implementation to atleast one abstract
method then, declare the sub class as abstract.
● If the subclass is providing implementation to all the abstract methods
then, the subclass should be called as Implementation class.
● An Interface can have any number of implementation classes.
Example:
interface Animal {
void makeSound();
}
class Cat implements Animal {
public void makeSound() {
[Link](“meow, meow”);
}
}
class Dog implements Animal {
public void makeSound () {
[Link](“bow bow”);
}
}
class InterfaceDemo {
public static void main(String[] args) {
Cat c = new Cat();
[Link] ();
109
Dog d = new Dog();
[Link]();
}
}
The Cat and Dog are subclasses of Animal interface. Cat and Dog are
implementation classes of Animal interface.
Cat IS-A Animal
Dog IS-A Animal
The variables of an interface must be initialized. The variables of an interface
can be accessed by using interface name or can be accessed directly by
implementing the interface.
An interface cannot be instantiated but we can declare a reference of that
interface. The reference of an interface can refer to an object of its
implementation class.
The java language does not support multiple inheritance but it can be achieved
with help of interface. A class can implement any number of interfaces.
Syntax:
class ClassName implements interface1, interface2, … {
}
Example:
interface Sample {
int x = 45;
void msg();
}
interface Test {
int y = 99;
void msg();
}
class InterfaceDemo implements Sample, Test {
public void msg() {
[Link](“multiple Inheritance”);
}
public static void main(String[] args) {
[Link](x);
[Link](y);
InterfaceDemo id = new InterfaceDemo();
[Link]();
Sample s = new InterfaceDemo();

110
[Link]();
Test t = new InterfaceDemo();
[Link]();
}
}
Rules:
● A class can extends atmost one class.
● A class can implement any number of interfaces.
● An interface can extends any number of interfaces.
● A class can extends a class and implement any number of interfaces
together at the same time (extends keyword should be followed by
implements keyword).
Marked Interface(Tagged Interface): An interface is said to be marked or
tagged if it is empty i.e. if the interface doesn’t have any members.
● The purpose of a marked interface is to provide some instructions to the
JVM to perform a task in a special way.
Examples of predefined marked interfaces:
Cloneable Serializable RandomAccess etc.
We can create user defined marked interface but they are of no use because
JVM has no meaning for user defined marked interfaces.

PACKAGES
A package is a collection of classes and interfaces which are related. The
purpose of a package is to improve the performance and increase accessibility.
Packages are classified into two types:
1. Predefined Packages
2. User defined Packages
Predefined package: The packages which are available as part of the java
software given by either SUN Microsystems or some other organizations are
called predefined packages.
The predefined packages are further classified into three types:
1. Core Packages: The packages which are given by SUN Microsystems and
which begin with “java” are called core packages.
2. Extended Packages: The packages which are given by SUN micro systems
and which begin with “javax” are called extended packages.

111
3. Third party packages (vendor packages): The packages which are given by
some other organizations as part of the java software are called third party
packages or vendor packages. The third party package may begin with any
term.
Examples of Predefined package:
● [Link]: This package contains a set of classes and interfaces required for
basic programming.
Note: [Link] package is called as default package.
● [Link]: This package contains a set of classes and interfaces required for
performing reading and writing operations.
● [Link]: This package contains a set of classes and interfaces required for
additional usage like Date, Time, Collections, etc.
● [Link]: This package contains a set of classes and interfaces required for
developing networking applications.
● [Link]: This package contains a set of classes and interfaces required for
formatting text, numbers, date, currency etc. Using this package we can
achieve Internationalization(I18N).
● [Link]: This package contains a set of classes and interfaces required for
developing a GUI.
● [Link]: This package contains a set of classes and interfaces required
for developing a GUI better than awt.
● [Link]: This package contains a set of classes and interfaces required
for developing a distributed GUI.
User defined Packages: The packages which are created by the user or the
programmer are called as user defined packages.
To create a user defined package we use package keyword.
Syntax:
package packagename;
package package1[.package2[.package3]];
A package statement can contain any number of levels, but specifying atleast
one level is mandatory.
Example:
package inetsolv;
package [Link];
package [Link];
A java program can contain atmost one package statement and it should be
specified as the first executable statement in a java program.
Example:

112
package inetsolv;
class Sample {
public static void main(String[] args) {
[Link](“hello friends”);
}
}
Syntax for compiling java program with a package statement:
javac -d path programname/filename with extension
-d is an option which indicates the compiler to create a directory by the name
that is specified in the package statement of the program, in the specified
destination.
Example:
javac -d . [Link]
javac -d d: [Link]
javac -d e: [Link]
javac -d e:\check [Link]
Syntax to execute a java program available in a package:
java [Link]
java package1[.package2[.package3]].ClassName
Example:
java [Link]

Every java program contains two default packages:


1. current working directory /package(user defined package)
2. [Link](predefined package)
All the classes and interfaces available in the default packages can be accessed
directly.
To access the classes and interfaces which are not available in default
packages, we need to use the following two mechanisms:
1. Fully Qualified Name
2. Import Statements
Fully Qualified Name: Fully qualified name is a process of specifying a class
name or interface name along with its complete package details (absolute
path).
Syntax:
[Link]
113
package1[.package2[.package3]].ClassName
Example:
[Link]
[Link]
[Link]
Using the fully qualified name we can access either one class or one Interface.
If a class or interface is used multiple times then, we need to specify the fully
qualified name also multiple times, thereby increasing the code size, and
reducing the readability of the code.
In order to improve the readability and reduce the code size, we take the help
of import statements.
Import statements:
Import statements can be used to a access a class or an interface from a
package.
The import statement can be specified one time and accessed multiple times.
A java language can contain any number of import statements. All the import
statements has to be specified after the package statement and before the
class.
Using the import statement we can access all the classes and interfaces from
the package or we can access either one class or one interface from a package.
Syntax for import statement accessing all the classes and interfaces from a
package:
import packagename.*;
import package1[.package2[.package3]].*;
Example:
import [Link].*;
import [Link].*;
import [Link].*;
Using the above import statement we can automatically access all the classes
and interfaces available in the specified package and therefore called as
implicit import statement.
Syntax for import statement accessing a single class or a single interface from
a package:
import [Link];

114
import package1[.package2[.package3]].ClassName;
Example:
import [Link];
import [Link];
import [Link];
Using the above import statements we can access only that class or interface
which is explicitly specified from a package and therefore called as explicit
import statements.
Note: It is recommended to always use explicit import statements because
they improve the readability of the code.

Difference between include statement and import statement:


In an application, if we specify an include statement then, it will load the entire
predefined program into our application whether require or not, increasing the
code size and compilation time. This kind of loading is called static loading.
In an application, if we specify an import statement then, it will load only those
classes and interfaces that are required and therefore there will not be any
increase in the code size and compilation time. The loading of classes and
interface will be done into JVM memory(method area) during the execution
time. This kind of loading is called dynamic loading or load on demand.
Static Import: static import statements are introduced in java 1.5 and it is used
to access the static members from a class or interface.
Syntax:
import static [Link].*;
import static package1[.package2].ClassName.*;
import static [Link];
import static package1[.package2].[Link];
Example:
import static [Link].*;
import static [Link].MAX_VALUE;
class Sample {
public static void main(String[] args) {
[Link](min(5,8));
[Link](max(5,8));
[Link](floor(5.8));
[Link](ceil(5.8));
[Link](round(5.8));

115
[Link](random());
[Link](pow(2,4));
[Link](abs(-8));
[Link](Integer.MAX_VALUE);
}
}
Difference between general import and static import
General import is used to access the classes and interfaces from a package.
import packagename.*;
import [Link].*;
Static import is used to access the static members from a class or interface.
import static [Link].*;
import static [Link];
Access Specifiers
The access specifiers can be used to define the level of accessibility of either
the members in a class/interface or the level of accessibility of a class/interface
in a package. Using the access specifies we can define the scope (life) of a
class/interface or its members and provide security.
The java language provides 4 levels of access specifiers, with three keywords.
1. public
2. private
3. protected
4. default (no access specifier)
public: If a member is declared as public then, it can be accesses from all the
classes of all the packages. The public access specifier can be applied to
classes, interfaces, variables, methods and constructors.
private: If a member is declared as private then, it can be accessed only in that
class. The private access specifier can be applied to variables, methods and
constructors.
protected: If a member is declared as protected then, it can be accessed from
all the classes of that package and from the sub classes available in other
packages. The protected access specifier can be applied to variables, methods
and constructors.
default(no access specifier): If a member is not declared with either public or
private or protected then, it is called as default access specifier. If a member is
declared as default then, it can be accessed from all the classes of that package
only. The default access specifier is also called as package level access. The

116
default access specifier can be applied to classes, interfaces, variables,
methods and constructors.

● If a variable x is declared as public in class A, then it can be accessed in A, B,


C, D and E.
● If a variable x is declared as private in class A, then it can be accessed in
only A.
● If a variable x is declared as protected in class A, then it can be accessed in
A, B, C and D.
● If a variable x is declared as default in class A, then it can be accessed in A,
B, and C.

117
private < default < protected < public
The most accessible access specifier is public and the most restricted access
specifier is private.
Overriding rule: When we are overriding a method, the child class method
should have an access specifier, same as that of the parent class method
access specifier or a bigger access specifier.
The private methods cannot be inherited and therefore cannot be overridden.
Illegal combination of modifiers for methods: A method cannot be declared as
abstract and private because, the abstract keyword says we must inherit and
then override whereas the private keyword say we cannot inherit and
therefore we cannot override.
A class or interface can be declared as either default or [Link] naming of
the java program is based on class declaration(access specifiers).
Note: The naming of the java program is not based on main method.
If a class is declared as default then, the name of the program can be any
name. But if a class is declared as public then, the name of the program must
be same as that of the public class name.
A java program can have any number of classes, but it can contain atmost one
public class.
Example:

118
In the above program all the classes are declared as default and therefore the
name of the program can be any name.
Example:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Let us name it as Sample java.
Syntax for compiling a java program:
javac programname/filename with extension
When a java program is compiled, the compiler generates .class file. The
number of .class files that are generated will be equal to number of classes and
interfaces available in the program.
The name of the .class files will be same as the class names or interface names.
Syntax for executing a java program:
java ClassName without extension
119
Example:
java A
java B
java C
java D
java Sample
Every class in java will have a constructor whether we specify or not. If we do
not specify any constructor then, the compiler will provide either public zero
parameterized constructor or default zero parameterized constructor i.e. the
declaration of the constructor provided by the compiler will be based on class
declaration. If the class is declared as public then, the compiler will provide
public zero parameterized constructor and if the class is declared as default
then, the compiler will provide default zero parameterized constructor.
Note: The compiler cannot provide private and protected constructor and it
cannot provide parameterized constructor.
As a programmer we can specify either a zero parameterized constructor or a
parameterized constructor or both and we can declare them as either public or
private or protected or default.
Singleton class: A class is said to be singleton, if we are able to create only one
object for that class.
To create a singleton class, the class must have private constructor and a
factory method.
Factory method: If a method returns an object of its own class then, it is called
as a factory method.
Note: The factory method must be declared as static.
Example:
public class Sample {
static Sample s;
private Sample() {
}
void msg() {
[Link](“hello friends”);
}
static Sample getObject() {
if(s == null)
s = new Sample();
return s;
120
}
}
class Demo {
public static void main(String[] args) {
Sample s = [Link]();
[Link]();
}
}
Example:
package abcd;
public class Sample {
public void msg() {
[Link](“hello friends”);
}
public static void main(String[] args) {
Sample s = new Sample();
}
}
class Demo {
public static void main(String[] args) {
Sample s = new Sample();
[Link]();
}
}

package xyz;
import [Link];
class Test {
public static void main(String[] args) {
Sample s = new Sample();
[Link]();
}
}
Keywords: The words that have predefined meaning in java or the words
whose meaning is reserved in java are called keywords.
Example: class, import, static, public, private, final, default, abstract
Modifiers: Modifiers are the keywords, which modifies the meaning of a
declaration.

121
Example: static, final, abstract, public, private, protected
Specifiers: Specifiers are the modifiers, which specify the level of accessibility.
Example: public, private, protected.

EXCEPTION HANDLING
When an application is developed, the application may contain some errors.
The errors that occur in the applications are classified into two types:
1. Compiler time errors
2. Runtime errors
Complier time error: The errors that occur in a program or application because
of the syntactical mistakes are called as compile time errors.
Runtime errors: The errors that occur in a program at execution time, because
of either programmer failure or JVM failure are called as run time errors.

Exception hierarchy:

Object: Object is the super most class of all the classes in Java.
Throwable: Throwable is the super most class of all the runtime errors in Java.
Throwable is the subclass of Object class.
Exception and Error are the subclasses of Throwable.

122
Exception: An exception is a runtime error, which occurs because of the
programmer failure(logical failure, invalid inputs etc). Exception is the super
most class of all the Exceptions.
Exceptions are classified into two types based on when they are identified:
1. Compile time exception: The exceptions which occur at runtime and which
can be identified before runtime or during compilation time are called as
compiler time exceptions.
2. Runtime exception: The exceptions which occur at runtime and which can
be identified during runtime are called as runtime exceptions.
Error: An Error is a runtime error which occurs because of the JVM failure.
Error is the super most class of all the Error classes.
The exceptions are classified into two types based on whether they are
handled or not:
1. Checked exception: The exceptions whose handling is mandatory are
called as checked exception.
2. Unchecked exception: The exceptions whose handling is optional are
called as unchecked exception.
According to the exception hierarchy, RuntimeException and its subclasses,
Error and its subclasses are unchecked and the remaining are checked.
If an application contains an exception then, the application will be terminated
abnormally leading to incomplete execution. In order to execute the code
completely and terminate the application normally then, we need to take the
help of exception handling.
Exception handling is a process of finding an alternate solution so that the
remaining code execute completely and terminates normally.
Note: The exception handling process will not remove the exception from the
program.
The code that performs exception handling will be called as exception handler.
Example:
public class Sample {
public static void main(String[] args) {
[Link](“line one”);
[Link](10/0);
[Link](“line three”);
[Link](“line four”);
}

123
}
When an exception occurs in an application, an object of its corresponding
exception class will be created and then, all the details related to that
exception will be stored into that object and then, the object will be thrown to
the JVM by that method in which an exception has occurred.
The JVM will catch the object and reads the information available in that object
and then the JVM looks for exception handling code, if not available the JVM
will call default exception handler.
The responsibility of the default exception handler is to display the information
available in the exception object and terminate the application abnormally and
therefore leading to incomplete execution.
The keywords related to exception handling concept are:
1. try
2. catch
3. finally
4. throws
5. throw
try: A try is a block, in which we can specify a group of statements, that may
generate an execption.
Syntax:
try {
statements generating exception;
}
A try block can contain any number of statements but recommended to specify
only those statements which may generate the exception.
catch: A catch is a block, in which we can specify a group of statements, that
will display the information of the exception that has occurred.
Syntax:
catch(AnyException ref) {
statements displaying exception information;
}
Note: Every catch block must contain a reference of any one of the exception.
finally: A finally is a block, in which we can specify a group of statements, that
will perform code cleanup activities like releasing memory, resources etc.
Syntax:
124
finally {
statements performing code cleanup activities,
}
Note: we cannot guarantee the execution of the try and catch block but the
execution of finally block is guarantee.
1) A try block must be followed by either a catch block or a finally block.
2) A catch block must be preceded by either try or catch block but in the
hierarchy we must specify try block on the top.
3) A catch block can be followed by either a catch block or finally block.
4) A finally block must be preceded by either a try or a catch but in the
hierarchy we must specify try block on the top.
5) A try block can be followed by any number of catch blocks(zero or more).
6) A try block contains multiple catch blocks and if the exceptions specified in
the catch blocks have IS-A relationship then, they have to specified in the
order from child to parent, but if the exceptions don’t have IS-A
relationship then, we can specify them in any order.
7) A try block can contain atmost one finally block.
8) We can specify the statements either before the blocks or after blocks or
inside the blocks but not in between the blocks.
9) A try block may contain multiple catch blocks but, it can execute atmost
one catch block, which in matching.
10) A try block may contain multiple catch blocks but, none of the catch
blocks may execute in the following situation.
i. When there is no exception in the program.
ii. An exception has occurred but not matching.
11) The try, catch and finally blocks can be nested either in try or catch or
finally and they can be nested any number of times.
12) A program can contain any number of combinations of try, catch, and
finally blocks.
13) If statements in a try block generate an exception then, the control will
be transferred from inside the try block to the corresponding catch block.
14) Once the control is out of the try block it cannot return back to the try
block.
Example:
public class Sample {
public static void main (String[] args) {
[Link](“line one”);
try {

125
String s1 = args[0];
String s2 = args[1];
int a = [Link](s1);
int b = [Link](s2);
[Link](a/b);
}
catch(ArithmeticException ae) {
[Link]();
}
catch(ArrayIndexOutOfBoundsExecption aioobe) {
[Link]();
}
finally {
[Link](“special line”);
}
[Link](“line four”);
}
}
Multi catch block: In java 1.7 version we can handle multiple exceptions by
writing a single catch block.
Syntax:
catch(Exception1 | Exception2 | Exception3… ref) {
statements;
}
Example:
catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
[Link]();
}
The exceptions specified in multi catch block must not have IS-A relationship.
throws: The throws keyword is designed to transfer or delegate the
responsibility of exception handling to its caller.
Syntax:
returntype methodName(parameters) throws Exception1, Exception2, … {
statements;
}
Note: The throws keyword will not handle exceptions.
Example:

126
public class Sample {
public static void main(String[] args) {
[Link](“main first line”);
try {
show();
}
catch(ArithmeticException ae) {
[Link]();
}
[Link](“main last line”);
}
static void show() throws ArithmeticException {
[Link](“show first line”);
[Link](6/0);
[Link](“show last line”);
}
}
In the above program, an exception has occurred in show() and it is the
responsibility of the show() to handle the exception, but instead of show()
handling the exception, it has transferred the responsibility of exception
handling to its caller(main() method).
Note: Exception handling can be done only by using try-catch block.
throw: The throw keyword is used to throw an exception object explicitly to
the JVM.
Syntax:
throw AnyExceptionObject;
Different ways of displaying the information of the exception:
1) printStackTrace(): This method can be used to display the detailed
information of the exception that has occurred. This method will provide
details like exception name, reason for the occurrence of the exception,
line number, method name, class name, program name.
try {
[Link](10/0);
}
catch(ArithmeticException ae) {
[Link]();
}

127
[Link] : / by zero at [Link]([Link])
2) toString(): The To String method is used to display only the exception name
and the reason for the occurrence of the exception.
try {
[Link](10/0);
}
catch(ArithmeticException ae) {
[Link](ae);
//[Link]([Link]());
}
[Link] : / by zero

3) getMessage(): The getMessage() can be used to display only the reason for
the occurrence of the exception.
try {
[Link](10/0);
catch(ArithmeticException ae) {
[Link]([Link]());
}
/ by zero
4) User defined Message: If we don’t want the output to be provided by the
predefined methods then, we can display our own message by using
[Link]().
try {
[Link](10/0);
}
catch(ArithmeticException ae) {
[Link](“ArithmeticException has occurred”);
[Link](“it is a user defined message”);
}
Arithmetic has occurred
it is a user defined message
User defined exception: If an exception is created by a user or a programmer
then, it is called as user defined exception.

128
The user defined exceptions has to be created when none of the predefined
exceptions are matching our application requirement.
Procedure for creating user defined exception:
1. Every predefined exception is a class and therefore the user defined
exception should also be a class.
2. Every predefined exception is a subclass of Exception class either directly
or indirectly therefore every user defined exception should also be a
subclass of Exception class either directly or indirectly.
3. If the application doesn’t know when to generate the exception and which
one to generate the exception and therefore it is the responsibility of the
programmer to explicitly create an object and throw it to the JVM by using
throw keyword.
4. Every user defined exception must have two constructors, one zero
parameterized constructor and the other parameterized constructor taking
one parameter of String type.
Example:
class SmallAgeException extends RuntimeException {
SmallAgeException() {
}
SmallAgeException(String str) {
super(str);
}
}
class BigAgeException extends RuntimeException {
BigAgeException() {
}
BigAgeException(String str) {
super(str);
}
}
public class Sample {
public static void main(String[] args) {
int age = [Link](args[0]);
try {
if(age < 20) {
throw new SmallAgeException(“your age is less than 20”);
}
else if(age > 30) {
129
throw new BigAgeException(“your age is more than 30”);
}
else {
[Link](“you are eligible”);
}
}
catch(SmallAgeException sae) {
[Link]();
}
catch(BigAgeException bae) {
[Link]();
}
[Link](“have a good day”);
}
}

[Link]
The [Link] package is a predefined package available in java language and it
is a default package. All the classes available in that package can be accessed
directly.
Object: Object is the super most class of all the classes in java i.e. every class in
java will be subclass of Object class either directly or indirectly. Every class in
java either predefined or user defined can use the members of Object class.
Methods of Object class:
1) String toString(): The toString() method can be used to display an object in
the form of a string representation.
Example:
class Sample {
public static void main(String[] args) {
Sample s = new Sample();
[Link](s);
// OR
//[Link]([Link]());
}
}

130
The toString() will be invoked by the compiler automatically whenever we
display a reference variable of any class.
The toString() of Object class will always display class name followed by hash
code which is not meaningful and understandable to the user.
Predefined code tostring() of object class.
It is always recommended to override toString() in every user defined class to
display meaningful and understandable message to the user.

Example:
class Sample {
public static void main(String[] args) {
Sample s = new Sample();
[Link]([Link]());
Employee e1 = new Employee(12,”abcd”);
[Link]([Link]());
Employee e2 = new Employee(15,”xyz”);
[Link]([Link]());
}
public string toString() {
return “this is sample object”;
}
}
class Employee {
int empId;
String ename;
Employee (int empId, String ename) {
[Link] = empId;
[Link] = ename;
}

131
public string toString() {
return empId+ “ : “ +ename;
}
}
2) int hashCode():
Hash code is a unique number which is used to identify the object.
The hashCode() of Object class will generate a unique number for every object
i.e created. If we don’t want the hash code to be generated by the predefined
method then, we can override hashCode() is our class to generate your own
hash code.
If we are overriding the hashCode(), then we are recommended to override the
hashCode() in such way that, we generate a unique number for every object
that is created.

Example:
class Sample {
static int count =12;
public static void main(String[] args) {
Sample s1 = new Sample();
[Link]([Link]());
Sample s2 = new Sample();
[Link]([Link]());
}
public int hashCode() {
return count++;
}
}
3) boolean equals(Object): This method can be used for comparing the
objects.
The equals() of Object class will by default compare the hash codes of the
objects. If we don’t want to compare the hash codes of the objects then, we
must override the equal() in that class whose object has to be compared and
define the meaning of the equality.
Example:

132
class Sample {
public static void main(String[] args) {
String s1 = new String(“hello”);
String s2 = new String(“hello”);
[Link]([Link](s2));
Product p1 = new Product (12,90);
Product p2 = new Product (12,90);
[Link]([Link](p2));
}
}
class Product {
int pid, price;
Product (int pid, int price) {
[Link] = pid;
}
public boolean equals(Object obj) {
int id1 = [Link];
int pr1 = [Link];
Product pro = (Product) obj;
int id2 = [Link];
int pr2 = [Link];
if(id1 == id2 && pr1 = pr2)
return true;
else
return false;
}
}

4) Object clone(): This method can be used for taking the back up of an
object.
Using the clone() we can create duplicate copy of the existing object.
Any object created by the JVM can’t duplicated.
To use the clone() method we need to follow some procedure:
1) The return type of clone() is Object, which has to be type casted to our
required type
2) The clone() throws CloneNotSupportedException which must be handled
(because it is a checked exception).
3) The class whose object has to be duplicated, must implement Cloneable
interface.
133
Cloneable is a marked interface or tagged interface which will provide some
instructions to the JVM to create the object in a special way so that, we can
create a duplicate copy of an object.
Example:
class Product implements Cloneable {
int pid =12 , price = 89;
public static void main(String[] args) throws CloneNotSupportedException {
Product p1 = new Product();
[Link]([Link] +” : ” + [Link]);
Object obj = [Link]();
Product p2 = (Product) obj;
[Link] = 15;
[Link] = 90;
[Link]([Link] +” : ” + [Link]);
[Link]([Link] +” : ” + [Link]);
}
}
Reflection is a process of examining or introspecting the information of a class
during the execution time.
All the classes and interfaces related to reflections are available in
[Link] package.
5) Class getClass(): This method will return the information of the class whose
object is provided.
Example:
import [Link].*;
class Demo {
static Object getObject() {
return new String(“hello”);
}
}
class Sample {
public static void main(String[] args) {
Object obj = [Link]();
Class c = [Link]();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
Method[] mthds = [Link]();
134
for(method x : mthds) {
[Link](x);
}
Constructor[] cons = [Link]();
for(constructor y : cons) {
[Link](y);
}
Field[] f = [Link]();
for(Field z : f) {
[Link](z);
}
}
}

WRAPPER CLASSES
These classes are used to wrap or convert a primitive data types into a class, so
that the application is completely object oriented.
For every primitive type in java language, we have a corresponding wrapper
class. There are 8 wrapper classes and all are available in [Link] package.
Primitive types Wrapper classes
byte Byte
short Short
int Int
long Long
float Float
double Double
char Character
boolean Boolean
Creation of wrapper class objects:
Byte b = new Byte(byte);
Byte b = new Byte(String);
Short s = new short(shot);
Short s = new short(String);
Integer i = new Integer(int);
135
Integer i = new Integer(String);
Long l = new Long(long);
Long l = new Long(String);
Float f = new Float(float);
Float f = new Float(double);
Float f = new Float(String);
Double d = new Double (double);
Double d = new Double(String);
Character c = new Character(char);
Boolean b = new Boolean(boolean);
Boolean b = new Boolean(String);
Example:
int x = 12;
Integer y = new Integer(x);
Integer z = new Integer(“12”);
If we create a Boolean class object by specifying the boolean value true, then
the result is true and if we create a Boolean class object by specifying the
boolean value false then, the result is false. If we create a Boolean class object
by specifying a string whose content is true in any case(“true” , “True” “tRUe”,
“ TRUE”) will result as true and any other content will lead to false.
Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean(false);
Boolean b3 = new Boolean(True);
Boolean b4 = new Boolean(False);
Boolean b5 = new Boolean(TRUE);
Boolean b6 = new Boolean(FALSE);
Boolean b7 = new Boolean(“TRUE”);
Boolean b8 = new Boolean(“TrUe”);
Boolean b9 = new Boolean(“TrUe”);
Boolean b10 = new Boolean(“TrUE”);
Boolean b11 = new Boolean(“tRUE”);
Boolean b12 = new Boolean(“true”);
Boolean b13 = new Boolean(“FALSE”);
Boolean b14 = new Boolean(“FALSE”);
Boolean b15 = new Boolean(“FaLSE”);
Boolean b16 = new Boolean(“fALSE”);
Boolean b17 = new Boolean(“hello”);
Boolean b18 = new Boolean(“ ”);
136
Boolean b19 = new Boolean (null);
Boolean b20 = new Boolean(“started discussing”);
Methods of wrapper classes:
1) valueOf():
Syntax: static WrapperClass valueOf(primitivetype)
The above syntax can be used for converting a value from primitive type to
wrapper type. This method is available in all the 8 wrapper classes.
Syntax2: static WrapperClass valueOf(String)
The above syntax can be used to convert a value from string type to wrapper
type. This method is available in all wrapper classes except Character class.
Example:
int x = 12;
Integer y = [Link] (x);
Integer z = [Link](“12”);
2) xxxxvalue(): This method can be used for converting a value from wrapper
type to primitive type.
byteValue()
shortValue()
intValue()
longValue()
floatValue()
doubleValue()
charValue()
booleanValue()
Example:
Integer x = [Link](12);
byte b = [Link]();
int i = [Link]();
float f = [Link]();
4) parsexxxx():
Syntax: static primitivetype parsexxxx(String)
This method will convert a value from string type to primitive type. This
method is available in all wrapper classes except Character class.
Example:
String s = “45”;
short x = [Link](s);
137
int y = [Link](s);
float z = [Link](s);
5) toxxxxString():
static String toBinaryString(int/long)
static String toOctalString(int/long)
static String toHexString(int/long)
The above three methods are used to convert a value from decimal number
system to binary, octal, hexadecimal number system respectively.
The above three methods are available in Integer and Long class only.
Example:
int x = 12;
[Link](x);
[Link]([Link](x));
[Link]([Link](x));
[Link]([Link](x));
Hierarchy of wrapper classes:

Boxing: It is a process of converting a value from primitive type to wrapper


type.
This process is done automatically from java 1.5 version onwards and therefore
called as auto boxing.
Example:
int x = 12;
Integer y = x;

138
UnBoxing: It is process of converting a value from wrapper type to primitive
type.
This process is done automatically from java 1.5 version onwards and therefore
called as auto unboxing.
Example:
Integer x = new Integer(34);
int y = x;
Variable arguments: The variable arguments are a concept introduced in Java
1.5 version using which we can pass any number of values. The variable
arguments are represented by … called as ellipsis.
A method or a constructor can contain at most one variable argument and it
should be the last argument.
Note: We can replace a single dimensional array with variable arguments.

Example:
class Demo {
void show(double d, int . . . arr) {
for(int x : arr) {
[Link](x);
}
}
public static void main(String… args) {
Demo d = new Demo();
[Link](1.1);
[Link](1.2,4);
[Link](1.3,5,6);
[Link](1.4,7,8,9);
[Link](1.5,new int[] {3,4,5,6,7,8});
}
}
Rule: When a method is invoked or executed it will look for a method with
exact type, if not matching then, it will be promoted to next primitive and
perform searching, still not matching continue the process until it reaches
double type, still not matching convert it to its corresponding wrapper class
and perform searching, still not matching typecast to its parent type, still not
matching continue the process until we reach Object class still not matching
search for variable argument, still not matching it will generate a error.

139
1. Exact type
2. Type promotion
3. Boxing
4. Upcasting
5. Variable arguments
Enum
The enum keyword is introduced in java 1.5 version and it is designed to create
a group of named constants.
Syntax:
enum <enumName> {
Constants
}
Example: [Link]
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN
}
When a java program is compiled the compiler will generate a .class file for
every class, every interface and for every enum.
When the above java program is compiled, the compiler generates [Link]
javac [Link]
javap Day
final class Day extends Enum {
public static final Day MON;
public static final Day TUE;
:
public static Day[] values();
}
Every enum is internally a final class, extending from Enum class. Enum is an
abstract class and belongs to [Link] package. Enum class is subclass of
Object class.
● An enum can be empty.
● An enum can contain only constants.
● An enum can contain other code along with constants
● An enum cannot contain only other code without constants.
● If an enum contains only constants then, specifying the semicolon after the
constants is optional.

140
● If an enum contains other code along with constants then, specifying the
semicolon after the constants is mandatory.
● If an enum contains other code along with constants, then the constants
should be specified as the first statements.
● An enum can contain main method and it can be executed.

Example:
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN;
public static void main (String[] args) {
[Link](“enum main method”);
}
}
● An enum can’t be instantiated explicitly by the programmer. An enum can
be instatiated only by declaring a constant.
● An enum can contain constructor and it will execute one time for every
constant that is declared.
Example:
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN;
Day() {
[Link](“enum constructor”);
}
public static void main(String[] args) {
[Link](“enum main method”);
}
}
Example:
Enum Fruit {
APPLE(40), MANGO(90), GRAPES, BANANA(30), ORANGE(60);
int price;
Fruit() {
price = 50;
}
Fruit(int price) {
[Link] = price;
}
int getPrice() {

141
return price;
}
}
class Eat {
public static void main(String[] args) {
Fruit f = [Link];
[Link](f+” : ”+[Link]);
Fruit[] fr = [Link]();
for(Fruit x : fr) {
[Link](x+” : “+[Link]());
}
}
}

Rule: An argument to switch statement is mandatory and it should be of either


byte, short, int, char upto java 1.4 version. From java 1.5 version onwards the
switch statements can be 4 primitive types (int,byte,short,char) and therefore
corresponding wrapper classes (Byte, Short, Integer, Character) and enum.
From java 1.7 version onwards we can specify String as the argument to enum.
● If we are specifying an enum as an argument to switch then, the case labels
must be exactly same as that of the constants specified in the enum.

Example:
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN;
}
class Work {
public static void main(String[] args) {
Day d = [Link];
switch(d) {
case MON : [Link](“boring”);
break;
case FRI : [Link](“preparing”);
break;
case SAT : [Link](“sleeping”);

142
break;
case SUN : [Link](“eating”);
}
}
}

● An enum can’t be inherited into another enum or class.


● An enum can’t inherit from another enum or class.
● An enum can implement any number of interfaces.

143

You might also like