0% found this document useful (0 votes)
6 views156 pages

Java Tutorials Part 1

The document provides an introduction to Java, detailing its history, installation procedures for Windows and Ubuntu, and the evolution of programming languages leading to Java. It highlights Java's key features such as portability, security, and object-oriented principles, alongside its buzzwords like simplicity and robustness. Additionally, it discusses the object-oriented programming concepts using relatable examples to illustrate attributes and operations of real-world entities.

Uploaded by

Ravi Bansal
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)
6 views156 pages

Java Tutorials Part 1

The document provides an introduction to Java, detailing its history, installation procedures for Windows and Ubuntu, and the evolution of programming languages leading to Java. It highlights Java's key features such as portability, security, and object-oriented principles, alongside its buzzwords like simplicity and robustness. Additionally, it discusses the object-oriented programming concepts using relatable examples to illustrate attributes and operations of real-world entities.

Uploaded by

Ravi Bansal
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

Unit-I

An Introduction To Java and Buzzwords

History of java:
Java is a high-level programming [Link] called OAK.
Released By: Sun Microsystems (now it is subsidiary of Oracle Corporation)
In Year: 1995 (actually OAK was released in year 1991 but it got failed then again it was
launched with a new name “java” in spring of 1995)
Author: James Gosling, Mike Sheridan, Chris Warth, Ed Frank & Patrick Naughton
Designed for: Consumer goods

Downloading and Installing java:


Java can be downloaded from the link given below for all operating systems
[Link]

Installing java on windows OS


Download java from the link given above
double click on the setup that you have downloaded from the link given above.
after installation have completed, go through following steps:-
1. Copy you java installation path up to bin directory (it will be something like “C:\Program Files\
Java\jdk1.7.0_02\bin”)

2. Click on my computer icon provided on your desktop screen or in start menu.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


3. After clicking on properties button you will get a dialog box. In that dialog box click on
advance tab button given in the top of dialog box. After clicking on advanced tab click on
Environment variable button.

4. clicking will open another dialog box. in that newly opened dialog box you will find list of user
variables as well as system variables. you will be able to edit system variable only if you are

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


logged in as administrator.

In list of user variables check if there exist a variable path, if not click on new button provided
below list of user variables, it will open a dialog box.
● Enter “path” in variable name text box
● Paste java installation path that you got from step 1 in value

if path variable already exists then


● select path variable and click on edit button, clicking will open dialog box,
● In that dialog box place semicolon after already given value then paste java installation
path that you got from step 1 in value.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


after following these steps click ok button for all dialog boxes.

now go to start menu click on the run button type cmd in text box then click on run button,
console will be appeared in front of you. Now type javac then press enter. you will get list of all
options along with their description.

your java installation has been completed. :-)

Installing java on ubuntu OS

Download java tar file according to your need (32 bit or 64 bit).

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Open terminal, login as a root then move to file where you have placed your tar file. Now type
following commands
tar -xvf tar-file-name
running that command will extract your tar file in the same folder. Now type following command
mkdir /usr/lib/jvm
running that command will create a folder named “jvm” in lib directory. Now type following
command
mv ./extracted-folder-name /usr/lib/jvm/jdk1.7.0
runnning that command will move extracted folder inside jvm folder that we have just created.
Norw type following command.
update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1
Hit enter, then
update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1
Hit enter, then
update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1
Now finally run following command
java -version
will output like
java version "1.7.0_01"
Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
Java HotSpot(TM) Client VM (build 21.1-b02, mixed mode)
Your java installation has been completed. :-)

Journey of programming : From Binary to Java

Programming languages/Techniques Pros & Cons

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Binary 1. Can only be understood by scientist or
professional programmers (i.e. human
unfriendly).
2. Hard to maintain and debug hence
Only Useful for very small programs.
3. Machine dependent code

Assembly Languages 1. Machine dependant Code


2. Uses mnemonics, that were better
than binary but not still unfriendly for
human being
3. Difficult to debug and maintain hence
Useful for small programs (but larger
than what we can make with binary)
that were some hundred to thousand
lines long.

C 1. Human friendly
2. Uses procedural programming
approach that make code cleaner but
not suitable for very large programs
(like greater than 75,000)
3. Machine dependent code

C++ 1. Human friendly


2. Support Object oriented paradigm that
make code manageable
3. Machine dependent code means code
that is compiled on one hardware may
not run on another platform

After looking at the journey of programming from binary to C++ we have solved all problems like
(human friendliness of language, managing large code etc) but Machine Dependant Code is
still an issue, that is addressed by java.

One more issue:Security

In network, basically two broad categories of objects are transmitted between server and
personal computer
1. Passive information
2. Dynamic active programs

Passive means that is not executing. like when you are viewing a mail you are reading a
passive information, or you are just downloading a setup of a software it is also a passive data
until you do not install it.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Dynamic active programs are the programs that are self executing. means they start their
execution just after downloaded. such kind of programs expose huge risk for client’s computer
means these programs can make denial of service attacks and may send your computer’s data
to server because they have access to your file system.

Bytecode:
Whenever someone compile a java program its output is not an executable code it is a
intermediate highly optimized set of instruction that is executed by java runtime system, known
as JVM (Java virtual machine), that intermediate set of instruction is called Bytecode.

How java Respond of these challenges??

Portability:-
Java achieve portability with the help of bytecode. because bytecode runs on JVM so only the
JVM needs to be implemented for each platform. Once the run-time package (that is JVM)
exists for a given system, any Java program can run on it. Remember, although the details of
the JVM will differ from platform to platform, all interpret the same Java bytecode. That feature
make java an Architecture neutral language.

The Java environment itself is readily portable to new architectures and operating systems. The
Java compiler is written in Java. The Java run-time system is written in ANSI C with a clean
portability boundary which is essentially POSIX-compliant. There are no "implementation-
dependent" notes in the Java language specification.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


C and C++ both suffer from the defect of designating many fundamental data types as
"implementation dependent" while Java defining standard behavior that will apply to the data
types across all platforms. Java specifies the sizes of all its primitive data types and the
behavior of arithmetic on them.

Security:-
Now we are talking about security aspect. java provide us a facility to create dynamic, self
executing programs for web, called applet. you can consider an applet like a program that is
downloaded like other component of web page (i.e. images, text etc.). but that program runs on
java compatible web browser. Java compatible web browser allow that applet to just access
java execution environment, not other parts of computers. you can understand it very much like
there exists a firewall (The term firewall originally referred to a wall intended to confine a fire
within a building) between your applet and other part of your computer. that firewall prevent
applet to access other part of your computer like file system thus potential security risk has been
overcome.

JVM is an interpreter for bytecode. means it convert bytecode into executable code line by line
remember it is not possible to compile an entire Java program into executable code all at once,
because Java performs various run-time checks that can be done only at run time. hence
improve security.

Also it has bytecode verifier, that acts as a sort of gatekeeper: it ensures that code passed to

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


the Java interpreter is in a fit state to be executed and can run without fear of breaking the Java
interpreter. Imported code is not allowed to execute by any means until after it has passed the
verifier's tests. Once the verifier is done, a number of important properties are known:
● There are no operand stack overflows or underflows
● The types of the parameters of all bytecode instructions are known to always be correct
● Object field accesses are known to be legal--private, public, or protected

The Java Buzzwords


1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multi-threaded
7. Architecture-neutral
8. Interpreted
9. High performance
10. Distributed
11. Dynamic

1. Simple
Java inherits the C/C++ syntax and many of the object-oriented features of C++,Also, some of
the more confusing concepts from C++ are either left out of Java or implemented in a cleaner,
more approachable manner. so if you are familiar with C/C++ then it will take a little efforts to
learn java.

A common source of complexity in many C and C++ applications is storage management: the
allocation and freeing of memory, java provides automatic garbage collection, thereby
simplifying the task of programmer.

2. Secure
3. portable
we have already discussed above.

4. Object Oriented
Java is fundamentally based on the OOP notions of classes and objects Java uses a formal
OOP type system that must be obeyed at compile-time and run-time. This is helpful for larger
projects, where the structure helps keep the various parts consistent

5. Robust
Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime)
checking, and eliminating situations that are error prone.

Java is a strongly typed language, one of the advantages of a strongly typed language is that it

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


allows extensive compile-time checking so bugs can be found early.

Java has a pointer model that eliminates the possibility of overwriting memory and corrupting
data. Instead of pointer arithmetic, Java has true arrays. This allows subscript checking to be
performed. also cannot gain unauthorized access to memory, which could happen in C or C++.
Also garbage collector is responsible for managing memory means laking of memory due to
mismanagement is avoided.

Exception handling is another feature in Java that makes for more robust programs. An
exception is a signal that some sort of exceptional condition, such as a "file not found" error, has
occurred. Using Exception handling, you can group all of your error handling code in one place,
which greatly simplifies the task of error handling and recovery.

Also automatic memory management also contribute to make it robust.

6. Multithreaded
Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously.

7. Architectural Neutral
Java was designed to support applications on networks. In general, networks are composed of
a variety of systems with a variety of CPU and operating system architectures. Java follows
“Write once; run anywhere, any time, forever.”
paradigm. Means Any machine (architecture) that has a JVM running on it, can execute any
Java program that has been compiled into byte codes.
Architecture neutrality is just one part of a truly portable system.

8. Interpreted
Java bytecode are translated on the fly to native machine instructions (interpreted) and not
stored anywhere. And since linking is a more incremental and lightweight process, the
development process can be much more rapid and exploratory.

9. High Performance
Java bytecode was carefully designed so that it would be easy to translate directly into native
machine code for very high performance by using a just-in-time compiler. Java run-time systems
that provide this feature lose none of the benefits of the platform-independent code. “High-
performance cross-platform” is no longer an oxymoron. also java performance has gotten a lot
better with aggressive just-in-time-compiler (JIT) techniques (the HotSpot project). Java
performance is often similar to the speed of C in case of JIT.

Java supports multi-threading that help to improve resource optimization and achieve
concurrency means you program is able to do more than one task in a single execution.

10. Distributed

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Java has an extensive library of routines for coping easily with TCP/IP protocols like HTTP and
FTP. This makes creating network connections much easier than in C or C++. Java applications
can open and access objects across the net via URLs with the same ease that programmers
are used to when accessing a local file system.

Java also support remote method invocation (RMI). This feature enables a program to invoke
methods across a network.

11. Dynamic
Although the Java compiler is strict in its compile-time static checking, the language and run-
time system are dynamic in their linking stages. Classes are linked only as needed. New code
modules can be linked in on demand from a variety of sources, even from sources across a
network.

Also java programs carry with them substantial amounts of run time type information that is
used to verify and resolve accessed to object at run time. This makes it possible to dynamically
link code in a safe and expedient manner. This is crucial to the robustness of the java
environment in which small fragments of bytecode may be dynamically updates in a running
system.

Unit-II
The Object Oriented Programming Concept

Let us consider an example of a fan that might be available over your head now :P. take a look
at it and note down some attribute that describe about it like
1. No. of blades
2. company name
3. Color
4. On/Off
5. weight
6. Rotation per minute

and talking about Operations that changes the description of these components.
1. Turning it on from off and vice-versa
2. Changing its color
3. Making it light in weight
4. Increasing/Decreasing rotation per minute

Now take another example of mobile, that you might have in your hand now :P. and note down
some component that describe about it like
1. Weight
2. Price

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


3. Width
4. Height
5. Company name
6. Switch On/Off
7. some features like camera resolution, FM, Blue-tooth

and talking about Operations that changes the description of these components.
1. Turning it on from off and vice-versa.
2. Turning its FM on from off and vice-versa.
3. Turning its Blue-tooth on from off and vice-versa.
4. Changing its color etc

In the example of fan and mobile that we have discussed above, we are using some attribute to
describe a real world entity these attributes are called states. Or we can say any attribute that
describe about a real word entity is called state.

And we are also discussing operation that make changes in the state of the real world entity
these operations are known as behaviors. Or we can say any operation that make changes in
the state of an real world thing is called behavior.

Now again coming back to our example and observe following scenario.
Fan that you were observing is same as all other fan that have same model no and
manufactured by same company in the terms of state and behavior?

Again about mobile that you were observing is same as all other mobile that have same model
no and manufactured by same company in the terms of state and behavior?

Not surprisingly, answer to both observations are yes.

but is it a coincidence that all mobiles and fans that are manufactured by same company and
having same model number are identical??

Not surprisingly, answer to that observations is No.

Means we can say that before manufacturing these mobiles and fans, someone have already
define their states and behavior, say on a document, and that document serve as a blueprint for
all mobiles and fans.

Also that document itself is a passive entity that is just defining states and behaviors in a
document does not create a mobile or fan, while we have make a real world entity by following
that blueprint. that real world entity is called object while the document that serve as a blueprint
for that real world object is called class.

Formally we can say

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Object
An object is an instance of a class. that also consist of state and related behavior. An object
stores its state in fields (variables in some programming languages) and exposes its behavior
through methods (functions in some programming languages). It is a real world entity.

Class
A Class is the blueprint from which individual objects are created. It is a passive entity. It is also
knows as user defined data type.

Abstraction
Now again come back to the example of mobile. So far we have seen it as an object that have
its own state and behavior. Now consider a scenario, you are sitting in a garden and feeling
bored (might be because you are waiting for someone), you took out mobile from your pocket
and start traversing gallery then selecting a song and start it listening.

And now come to our another example that is about fan. In the season of summer you are
coming to home from office/college and feeling tired, then you go to your drying room, switching
on fan, sitting comfortably on chair and start enjoying cool air.

In both situation that we have discussed above, do you need to bother about how mobile phone
play songs or how a fan rotates?

Simple answer: no, you are able to use an object even you don’t have to bother about its
internal working. You just need to bother about how to use that particular object. so you are
using an object without knowing its internal mechanism. That is called abstraction.

Encapsulation
General meaning of encapsulation is

“To completely cover something especially so that it will not touch anything else.”

The wrapping up of data and its associated function together in a single unit (called class) and
keeps both safe from outside interference and misuse is known as encapsulation.
Encapsulation works as a wrapper that protect data and code from arbitrary access by other
code defined outside the wrapper.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


(private variable and methods are covered by public methods & variables, but creating public variable is not
recommended)

Encapsulation is achieved with the help of access specifiers. So whenever we want any
property of an object (constants, variables, or method) to be revealed to others, we just have to
set it as a public property and when we don't want it to be, we set it as private.

Inheritance:
It is the process by which one object acquire the property of another object. It is used to
implement concept of hierarchical classification.

Consider a simple hierarchy given below.

(A Simple Hierarchy)

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Without the use of hierarchies, each object would need to define all of its characteristics
explicitly. However, by use of inheritance, an object need only define those qualities that make it
unique within its class.

So with the help of inheritance, A professional course student have all attributes of student as
well as of human. So attributes of a professional course student are

Name, Height, Weight, Age, Gender, Roll no, Institution name, Semester, Year and University.

Polymorphism:
Taking a simple example of your mobile phone. Every mobile have call button (having green
icon of phone) with it now consider observe reaction of pressing call button in following
situations
1. Let say you have an incoming call on your phone. you are pressing call button, now you
can talk to person who have make call to you.
2. Let say you have received a message and you are reading it, at the time of reading
press call button you will get list of all numbers that are in message as well as mobile
number of sender.
3. Let say you are browsing your dialled number list and on when your control is on a
particular number again press call button, now you are calling on that particular number.

From the above discussion we can make a simple observation that applying same behavior
(that is, pressing call button)on an object (that is, mobile) react differently in different situation.
That feature is known as polymorphism.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Simple we can say polymorphism means many forms. It is a feature that allow one interface to
be used for general class of action and specific action is determined by nature of situation. More
specifically it can be defined as “single interface, multiple methods”.

Writing First Java Program


Step 1: Open Console if you are using windows operating system, or Terminal if you are using
linux.

Step 2: Now type command


notepad [Link] if you are using window
or
gedit [Link] if you are using linux

and hit enter, following step 2 will open an editor in front of you with file name [Link]

Step 3: Now type following program in editor (gedit/notepad)


/*
This is a simple Java program.
*/
class Example {
public static void main(String args[]) {
[Link]("This is a simple Java program.");
}
}
Be careful while typing, java is a case sensitive language.

Step 4: Now switch to console/terminal and type following command


javac [Link]
The javac compiler creates a file called [Link] that contains the bytecode version of the
program. bytecode is the intermediate representation of your program that contains instructions
the Java interpreter will execute. Thus, the output of javac is not code that can be directly
executed. General syntax of compiling java program is

javac <filename with extension>

Step 5: and finally type following command


java A

you will get output

This is a simple Java program.

When you execute the Java interpreter as just shown, you are actually specifying the name of

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


the class that you want the interpreter to execute. General syntax is

java <class-name that contains main method>

It will automatically search for a file by that name that has the .class extension. If it finds the file,
it will execute the code contained in the specified class.

Explaining first program


Our program begins with the line
/*
This is a simple Java program.
*/
This is a comment. like other programming languages The contents of a comment are ignored
by the compiler. Instead, a comment describes or explains the operation of the program to
anyone who is reading its source code.

then
class A{
This line uses the keyword class to declare that a new class is being defined. A is an identifier
that is the name of the class.
{ opening curly brace of the class
The entire class definition, including all of its members, will be between the opening curly brace
({) and the closing curly brace (}). The use of the curly braces in Java is identical to the way they
are used in C, C++, and C#.

public static void main(String args[]) {

This is the line at which the program will begin executing. Just like C/C++ all Java applications
begin execution by calling main( ).
public means that function is visible to all over.
static means method main can be called without creating an object of encapsulating class.
void tell the compiler that main function will not return any value
In main( ), there is only one parameter, String args[ ] declares a parameter named args, which
is an array of instances of the class String. you might choose other name instead of args.
{ opening curly brace of main method

[Link]("This is a simple Java program.");


that statement will simply print “This is a simple Java program” on console followed by new line.
println() is a inbuilt method that output everything to console whatever is passed as a
parameter. System is inbuilt class that have an object named out, that out object is an output
stream that is connected to the console.

finally two consecutive closing curly braces one for closing main method and one for closing
class A.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


One important point:
Everything that you code in java is written within class including variable to methods (even
main), that is why it is called object oriented language.

Comments In Java:
Comments are optional part of program that are written by developer to specify objective of a
program or module in simple human friendly language. Comments are transparent to java
compiler means compiler simply ignores all comments written in a code.
Similar to C/C++, java supports two styles of comments that are as follow
1. Single line comment:- Such type of comment are used when our comment have length
limited to just one line. To insert a single line comment, simply start comment with two
consecutive slashes (/). Example
// This is a single line comment.

2. Multi line comment:- Such type of comment are used when our comment have length
more than one line. To insert a multi line comment, simply start comment with a slash (/)
and asterisk sign (*), and after completing comment just place an asterisk (*) sign and
slash (/) Example
/* I am multi line comment.
Comments are transparent to compiler
*/

Unit-III
Data type, variables and Type conversion

Similar to the C,C++ syntax for creating a variable is


type identifier [ = initial value];
here type is type of variable
while identifier is the name of the variable
statement written within square brackets [ ] are optional.

Data type:
A variable's data type determines values it may contain and operations that may be performed
on it.

Java supports both user defined data type (e.g. class) as well as primitive data type. A primitive
type is predefined by the language and is named by a reserved keyword.

In that chapter, we will discuss about primitive data type. java basically support 8 kind of
primitive data types.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


1. byte 2. short 3. int 4. long
5. float 6. double 7. char 8. boolean

for the sake of convenience, out of these 8 primitive data types, first 4 that are (byte, short, int
and long) are placed in a common group that is integer because these four data type hold a
whole numbers.

next 2 (that are float, double) are placed in a group that is floating point numbers because they
hold floating point numbers.

char is used to store characters like letters, numbers and special symbols. it is placed in a group
that is Character

finally boolean is used to store true/false value. it is placed in a group that is Boolean.

Integer
byte:
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128
and a maximum value of 127 (inclusive).
example: byte b;
here b is name of variable that is byte type.
byte c = 1;
here c is name of variable that is byte type and having initial value 1.

short:
The short data type is a 16-bit signed two's complement integer. It has a minimum value of -
32,768 and a maximum value of 32,767 (inclusive).
example: short s;
here s is name of variable that is short type.
short t = 150;
here t is name of variable that is short type and having initial value 150.

int:
The int data type is a 32-bit signed two's complement integer. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)

The int type is the most versatile and efficient type, and it should be used most of the time when
you want to create a number for counting or indexing arrays or doing integer math. It may seem
that using short or byte will save space, but there is no guarantee that Java won’t promote those
types to int internally anyway.
example: int i;
here i is name of variable that is int type.
int j = 150000;
here j is name of variable that is int type and having initial value 150000.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


long:
The long data type is a 64-bit signed two's complement integer. It has a minimum value of -
9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
Use this data type when you need a range of values wider than those provided by int. like
counting total population of our loving planet earth.
whenever assigning a value to long variable, make sure to append alphabetic L (capital L) or l
(small L) at the end of value, otherwise compiler may report error message “integer number too
large”.
example: long l;
here l is name of variable that is long type.
long l = 15000000L;
here l is name of variable that is long type and having initial value 15000000.

One important point:


There is no unsigned type specifier for integer data types in Java.

Floating point numbers


float:
The float data type is a single-precision 32-bit IEEE 754 floating point, having
approximate range 1.4e−045 to 3.4e+038. float are useful when you don’t require
a large degree of precision. Whenever assigning a value to float variable, make sure
to append alphabetic f at the end of value, otherwise error message “possible loss
of precision” will be reported by compiler.
float prints maximum 7 digit next to decimal point.
example: float f;
here f is name of variable that is float type.
float f1 = 1.5f;
here f1 is name of variable that is float type and having initial value 1.5.

double:
The double data type is a double-precision 64-bit IEEE 754 floating point. having approximate
range 4.9e–324 to 1.8e+308. float are useful when you require a large degree of precision.
Optionally d or D can be appended to value that is assigned to a double variable.
double prints maximum 13 digit next to decimal point.
example: double d;
here d is name of variable that is double type.
double d1 = 1.5;
here d1 is name of variable that is float type and having initial value 1.5.

Character
char:
The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or
0) and a maximum value of '\uffff' (or 65,535 inclusive).

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


example: char c;
here c is name of variable that is char type.
float c1 = ‘A’;
here c1 is name of variable that is float type and having initial value ‘A’.

Boolean
boolean:
The boolean data type has only two possible values: true and false. Use this data type for
simple flags that track true/false conditions.
example: boolean b;
here b is name of variable that is boolean type.
boolean b1 = true;
here b1 is name of variable that is float type and having initial value true.

An Example:
class DataTypeDemo{
public static void main(String a[]){
byte b = 1;
short s = 300;
int i = 123123;
long l = 65467890987L;

float f = 3.1416256f;
double d = 1222.0235859256566;
char c = 'a';
boolean bln = true;

[Link]("byte b is "+b);
[Link]("short s is "+s);
[Link]("int i is "+i);
[Link]("long l is "+l);

[Link]("float f is "+f);
[Link]("double d is "+d);

[Link]("char c is "+c);

[Link]("boolean bln is "+bln);


}
}

Output of the above program is:

byte b is 1

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


short s is 300
int i is 123123
long l is 65467890987
float f is 3.1416256
double d is 1222.0235859256566
char c is a
boolean bln is true

Literals:
A literal is a source code representation of a fixed value. They are represented directly in the
code without any computation.

Integer:
Any whole number value is an integer literal. An integer literal is of type long if it ends with the
letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L
because the lower case letter l is hard to distinguish from the digit 1.
There are other bases which can be used in integer literals.

● Binary (base 2): Binary digits are denoted in Java by a leading zero- b(0b or 0B). (only
supported in Java SE 7 and later)
● Octal (base eight) : Octal values are denoted in Java by a leading zero.
● Hexadecimal (base 16) : You signify a hexadecimal constant with a leading zero-x, (0x
or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.

Floating point Literals:


A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double
and it can optionally end with the letter D or d.

The floating point types (float and double) can also be expressed using E or e (for scientific
notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by
convention is omitted).

Character Literals:
Literals of types char may contain any Unicode (UTF-16) [Link] your editor and file
system allow it, you can use such characters directly in your code. If not, you can use a
"Unicode escape" such as '\u0063' for alphabet c. Always use 'single quotes' for char literals.

An Example of literals
class LiteralDemo{
public static void main(String a[]){
int decVal = 26;//decimal literal
int hexVal = 0x1a;//hexadecimal literal
int octVal = 012;//octal literal

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]("decVal is "+decVal);
[Link]("octVal is "+octVal);
[Link]("hexVal is "+hexVal);
double d1 = 123.4;//double literal
double d2 = 1.234e2;//double literal with scientific notation
float f1 = 123.4f;//float literal

[Link]("d1 is "+d1);
[Link]("d2 is "+d2);
[Link]("f1 is "+f1);

char cc = '\u0063';//character literal with unicode escape


char cd = 'd';//character literal

[Link]("cc is "+cc);
[Link]("cd is "+cd);
}
}

Output of the above program is:

decVal is 26
octVal is 10
hexVal is 26
d1 is 123.4
d2 is 123.4
f1 is 123.4
cc is c
cd is d

Using Underscore Character in Numeric Literals:


Java 7 or later versions allow to place underscore character between number for the sake of
improving readability. For example if you have a large number then separate them by group of
three or more two improve readability of numbers.

long creditCardNumber = 1234_5678_9012_3456L;


long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Scope and Lifetime of a variable:
A scope determines what objects are visible to other parts of your program. scope is defined
with the help of blocks, each time you start a new block, you are creating a new scope.
variables declared inside a scope are not visible (that is, accessible) to code that is defined
outside that scope. Thus, when you declare a variable within a scope, you are localizing that
variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules
provide the foundation for encapsulation.
Scopes can be nested. For example, each time you create a block of code, you are creating a
new, nested scope. When this occurs, the outer scope encloses the inner scope. This means
that objects declared in the outer scope will be visible to code within the inner scope. However,
the reverse is not true.

An Example:
class ScopeDemo{
public static void main(String a[]){
int x = 10;
if(x == 10){ //starting a new block
int y = 1000;
[Link](“x is ” + x + “ and y is ” + y);
}//block ends here
//y = 10; // error! scope of has over
[Link](“x is ” + x);
}
}
As per the discussion x is visible inside nested block while y is not accessible outside its block.

variables can be declared at any point, but are valid only after they are declared. Thus, if you
define a variable at the start of a method, it is available to all of the code within that method.
if you are declaring a variable after using it, compiler will report an error.

An Example:
class DeclarationDemo{
public static void main(String a[]){
[Link](“x is ” + x);// error
int x = 10;
}
}
in the code snippet given above, we are trying to use x before it is declared. hence an error.

Similar to C/C++, blocks can be nested in java , you cannot declare a variable to have the same
name as one in an outer scope.

An Example:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class NestedDeclareDemo{
public static void main(String a[]){
int x = 10;
{//creating new block
int x = 20;//error, x already defined
}//ending new block
}
}

Dynamic Initialization:
Dynamic Initialization can be defined as the dynamic operation that allows variables to be
initialized dynamically using any expression valid at the time of the variable declaration.

An Example:
class DynamicInit{
public static void main(String a[]){
int a=5;
int b=2;
int c=a*a+b*b;
[Link]("value of c is "+c);
}
}

Output of the above program is:

value of c is 29

In the above program we have three variables a,b and [Link] has been declared as ' int
'.Variable a and b are declared and provided values on declaration whereas the variable c has
been assigned a expression to evaluate and store its [Link] is done through dynamic
evaluation.

Type conversion and casting:

Automatic type conversions:


when you assign one type of data to another type of variable then automatic type conversion
take place in the following conditions met
1. The two types are compatible.
2. The destination type is larger then the source type.

when the two conditions takes place then it is called “widening conversion”.
Widening conversion is take place in the following cases:-
1. byte to short, int, long, float, or double

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


2. Short to int, long, float, or double
3. int to long, float, or double
4. long to float or double
5. char to int, long, float, or double
6. float to double

Narrowing conversion:-
when your source type is larger than the destination type or when your variable is incompatible
with the data to be assigned then you have to explicitly make the value narrower so that it can fit
into the target type.

To perform conversion between two incompatible types, you must use a cast. A cast is simply
an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.

An Example:
class NarrowConversion {
public static void main(String[] args) {
int i = 100, j = 200;
//short s = i it’s an error because short is smaller then int
short s = (short) i;
byte b = (byte) j;
char ch = (char) i;
[Link]("i is " + i + " s is " + s + " b is " + b + “ ch is ” + ch);
}
}

in the example given above we have created two variable i and j. if we are trying to assign i to s
then compiler will report us error because short is smaller then int. to assign value of an integer
variable to a short variable we have to type cast it.
In the next statement we have casted value of int to byte due to same reason explained above.
and when we are assigning value of an integer to a char then due to smaller size as well as
incompatibility we have typecast then.

finally output of the above program

i is 100 s is 100 b is -56 ch is d

i is 100 simple to understand, s is 100 simple to understand.


b is -56. b is a byte variable that have range -128 to 127 and value of j is 200 so according to
signed 2’s compliment storage it is -56.
finally ch is d. because i is 100 and ASCII value of character d is 100.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Truncation:
When a floating-point value is assigned to an integer type, the fractional component is lost,
because integers do not have fractional components. such type of conversion in called
truncation.

An Example:
class Truncation{
public static void main(String args[]) {
byte b;
int i = 260;
double d = 330.14;

[Link]("\nConversion of double to int.");


i = (int) d;
[Link]("d and i " + d + " " + i);

[Link]("\nConversion of double to byte.");


b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}

Output of the above program is:

Conversion of double to int.


d and i 330.14 330
Conversion of double to byte.
d and b 330.14 74

After discussing widening and narrowing conversion, we have found one speciality of java that
is whenever you are assigning a value to a variable, java performs compatibility of assigned
value to the target type and generate proper error message if found them incompatible. We can
say java avoid accidental assignment of mismatching data to variable, that is why java is know
as Strongly typed language. as checking takes place whenever you are passing argument to
functions and assigning expression’s result to a variable.

One important point:


Be careful while choosing variable name they must not be any reserve keyword. Java have
following keywords.

abstract continue for new switch

assert default goto (not used) package synchronized

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


boolean do if private this

break double implements protected throw

byte else import public throws

case enum instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp volatile

const (not used) float native super while

Unit-IV
Operators

So far we have learned about declaring, initializing variables in java. Now its time to know about
operation that you can perform over these variable. In that chapter we will discuss about all
operator that java provides you with example.

Arithmetic operators:
Java provides following arithmetic operators:
Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulus Assignment

You can apply arithmetic operations on char data type also.

Basic Arithmetic Operators:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


basic arithmetic expressions includes addition, subtraction, multiplication and division.
- and + both also have unary form.

An Example:
class BasicArithmetric {
public static void main(String args[]) {
int ia = 10 + 10;
int ib = ia - 10;
int ic = ib * 10;
int id = ic/ib;

[Link]("Integer Addition is " + ia);


[Link]("Integer Subtraction is " + ib);
[Link]("Integer Multiplication is " + ic);
[Link]("Integer Division is " + id);

double da = 1 + 1;
double db = da - 1;
double dc = db * 1;
double dd = dc/db;

[Link]("Floating point Addition is " + da);


[Link]("Floating point Subtraction is " + db);
[Link]("Floating point Multiplication is " + dc);
[Link]("Floating point Division is " + dd);
}
}

Output of the above program is:

Integer Addition is 20
Integer Subtraction is 10
Integer Multiplication is 100
Integer Division is 10

Floating point Addition is 2.0


Floating point Subtraction is 1.0
Floating point Multiplication is 1.0
Floating point Division is 1.0

The Modulus Operator:


modulus operator (%) returns remainder of the division operation. In java you can apply that
operators over floating point values also.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


An Example:
class FloatMod {
public static void main(String args[]) {
float f = 14.25f;
double d = 123.25;

[Link]("remainder of float f with 10 is " + f%10);


[Link]("remainder of double d with 10 is " + d%10);
}
}

Output of the above program is:

remainder of f with 10 is 4.25


remainder of d with 10 is 3.25

Arithmetic Assignment Operator:


Arithmetic Assignment operators provide you ability to shorten the syntax of evaluating
expression and assigning result to a variable.

General form of arithmetic assignment is:


variable operator= expression

like to increment a variable by 2 you often write


a = a + 2;
with the help of arithmetic assignment operators that can be re-written as
a+=2;

both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.

An Example:
class ArithmeticAssign {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 30;

a+=5;
[Link]("Addition Assignment: a is " + a);
b-=5;
[Link]("Subtraction Assignment: b is " + b);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


c*=3;
[Link]("Multiplication Assignment: c is " + c);
b/=3;
[Link]("Division Assignment: b is " + b);
c%=20;
[Link]("Modulus Assignment: c is " + c);
}
}

Output of the above program is:

Addition Assignment: a is 15
Subtraction Assignment: b is 15
Multiplication Assignment: c is 90
Division Assignment: b is 5
Modulus Assignment: c is 10

Increment and Decrement:


The Increment operator increases value of the variable by one.
Expression
a = a + 1;
can be written as
a++;
here ++ is increment operator.

Similarly decrement operator decreases value of the variable by one.


Expression
a = a - 1;
can be written as
a--;
here -- is decrement operator.

both increment and decrement operator have two forms:


1. Postfix: When operand precedes the operator
like a++, a--;
In that form of increment/decrement previous value of operand is obtained for use in expression
then operand is modified.
2. Prefix: When operator precedes the operand
like --a, ++a;
In that form of increment/decrement operand is modified first then value of operand is obtained
for use in expression.

An Example:
class PrePost {

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String args[]) {
int a = 10;
[Link]("a is " + a);

int b = a++;
[Link]("a is " + a + " b is " + b);

int c = --a;
[Link]("a is " + a + " c is " + c);

b = a--;
[Link]("a is " + a + " b is " + b);

c = ++a;
[Link]("a is " + a + " c is " + c);
}
}

Output of the above program is:

a is 10
a is 11 b is 10
a is 10 c is 10
a is 9 b is 10
a is 10 c is 10

Take a look at the result of the above program.


Output of the first print statement is “a is 10”. well predicted,no need to explain.
Second print statement generates “a is 11 b is 10” after evaluation of expression.
int b = a++;
Here a++ is postfix from of increment, also known as postincrement. in that expression value
of a is obtained first for assignment then value of a is incremented by one. hence b is assigned
value 10 and then variable a becomes 11 after increment.
Third print statement generates “a is 10 c is 10” after the evaluation of expression.
int c = --a;
Here --a is prefix from of decrement, also known as predecrement. in that expression value of
a is decremented by one then assignment of variable a take place to variable c. hence a
becomes 10 after decrement and c is assigned with updated value of variable a that is 10.
Similarly fourth print statement generates output “a is 9 b is 10”. after evaluation of expression
b = a--;
Here a-- is postfix from of decrement, also known as postdecrement. in that expression value
of a is obtained first for assignment then decremented by one. hence b is assigned value 10 and
a is decremented by one, becomes 9.
fifth print statement generates “a is 10 c is 10” after evaluation of expression.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


c = ++a;
Here ++a is prefix from of increment, also known as preincrement. in that expression value of a
is incremented first by a then assignment of updated value of variable a takes place to variable
c. hence a becomes 10 and c is assigned value 10;

Relational Operators:
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
Java provide following arithmetic operators:
Operator Result
== Equal To
!= Not equal to
> Greater Than
< Less than
>= Greater than or equal to
<= Less than or equal to

● All data types in java can be compared using equaity test (==) and unequaity (!=) test.
● Only numeric type can be compared using rest of the relational operators. (i.e. <, <=, >,
>=)
● Output of the relational expression is always a boolean value.

An Example:
class Relational {
public static void main(String args[]) {
int a = 4;
int b = 8;
boolean rslt = a < b; //expression will preduce a boolean result
if(rslt){
[Link]("a is less than b");
}else{
[Link]("a is greater than or greater than b");
}
}
}

output of the above program is

a is less than b

one more thing to remember: in C/C++, you often write code like
int i = 10;
if(i){
cout<<”i is nonzero”;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
In java, it is completely wrong to put integer/floating point number & character data type with
if/while statement without using relational operators. because in C/C++, there is no data type for
boolean values. hence nonzero values are treated as true and zero is treated as false. But in
case of java you have separate data type to hold true/false value, that is boolean. hence you
can only put boolean variable without relational operators with if/while. for any other data type
you have to use relational operators.

Bitwise Operators:
Java's bitwise operators operate on individual bits of operand. Operand may be integer, short,
long, byte or character type.
before moving into the depth of bitwise operators we must have understanding about how java
stores integer. As all we know that for computer everything in binary (i.e. 0 and 1). numbers are
also represented with the help of their corresponding binary notation.
let say you to store 6 in a variable of byte type. binary representation of 6 is 110 that requires 3
bits of storage. our byte variable occupy 8 bits hence will store it as 00000110, means padding
remaining 5 bits with 0.
Negative Numbers are stored with the help of two’s complement representation. if you want to
store any negative number in memory go through following steps:
1. Find out binary representation of corresponding positive number.
2. Find out one’s complement of binary representation that you have from step one. simply
Invert all bits of that binary representation.
3. Now add binary one to binary representation that you obtained from step 2. that’s all
result of step 3 is representation of corresponding negative number.

for Example you have to store -6 in a variable of byte type. simply


step 1: binary representation of 6 is 00000110.
step 2. one’s complement of 110 is 11111001.
step 3. add binary 1 to 001 now it becomes 11111010.
your -6 is equivalent to 11111010.

Operator Result
~ Bitwise unary Not
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Shift left
>> Shift right
>>> Shift Right zero fill
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right Assignment

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


>>>= Shift right zero fill Assignment
<<= Shift left Assignment

Bitwise Unary Not (~):


It inverts all the bits of its operand. It is also called bitwite compliment.
let say we have a variable named b of byte type stores 8. binary representation of 8 is
00001000.
Currently b = 00001000
Applying bitwise complement to b will invert all bits, means bit that have one is now zero and
that have zero is now one so.
~b = 11110111

Bitwise AND (&):


Bitwise AND produces a one bit if all operands are one in all other cases it will produce zero.
let say we have a variable named a of byte type stores 9. binary representation of 9 is
00001001.
Currently a = 00001001
And we have another variable named b of byte type stores 14. binary representation of 14 is
00001110.
Currently b = 00001110

so a & b is
00001001 = 9
&00001110 = 14
--------------
00001000 = 8

Bitwise OR (|):
Bitwise OR produces a zero if all operands are zero. In all other cases it will produce one.
Again let say we have a variable named a of byte type stores 9. binary representation of 9 is
00001001.
Currently a = 00001001
And we have another variable named b of byte type stores 14. binary representation of 14 is
00001110.
Currently b = 00001110

so a | b is
00001001 = 9
| 00001110 = 14
--------------
00001111 = 15

Bitwise XOR (^):


Bitwise XOR produces a one if exactly one operand is one. In all other cases it will produce

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


zero.
Again let say we have a variable named a of byte type stores 9. binary representation of 9 is
00001001.
Currently a = 00001001
And we have another variable named b of byte type stores 14. binary representation of 14 is
00001110.
Currently b = 00001110

so a ^ b is
00001001 = 9
^00001110 = 14
--------------
00000111 = 7

Left Shift (<<):


Left shift "<<" operator shifts all bits of left operand to the left side by the number of bits
specified by its right operand. general form of left shift is
value << num
here num specifies the number of the number of positions to left shift the value. for each shift,
the high order bit is lost and and rightmost bit is filled with zero. if you are applying shift left to
integer type variable then for each shift you will always loose 32 bit. similarly for a long variable
you will loose 64 bit for each shift.

An Example:
class LeftShift {
public static void main(String args[]) {
int a = 16;
int b = (a << 1);

[Link]("a is " + a);


[Link]("b is " + b);
}
}

output of the following program is:


a is 16
b is 32

In the example given above binary representation of 16 in 32 bit format is


00000000 00000000 00000000 00010000
after shifting it left by one, it would produce
00000000 00000000 00000000 00100000
for b. which is equivalent to 32.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Left shift is used as an alternative of multiplication operation. but be careful before doing so. let
us take an another example
class LeftShiftPitfall {
public static void main(String args[]) {
int a = 2147483647;
int b = (a << 1);

[Link]("a is " + a);


[Link]("b is " + b);
}
}

Output of the above program is:

a is 2147483647
b is -2

In that example a have value 2147483647. binary representation of 2147483647 is


01111111 11111111 11111111 11111111
shifting if left by one position will produce result for b
11111111 11111111 11111111 11111110
here sign bit for b is 1 hence number would be treated as negative so it is -2.

Right Shift (>>):


Right shift ">>" operator shifts all bits of left operand to the right side by the number of bits
specified by its right operand. general form of left shift is
value >> num
here num specifies the number of positions to right shift the value. for each shift you will loose
the rightmost bit.

An Example:
class RightShift {
public static void main(String args[]) {
int a = 32;
int b = (a >> 2);

int c = 35;
int d = (a >> 2);

[Link]("a is " + a);


[Link]("b is " + b);

[Link]("c is " + c);


[Link]("d is " + d);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}

Output of the above program is

a is 32
b is 8

c is 35
d is 8

In the example given above binary representation of 32 in 32 bit format is


00000000 00000000 00000000 00100000
after shifting it right by two, it would produce
00000000 00000000 00000000 00001000
for b. which is equivalent to 8.

similarly binary representation of 35 in 32 bit format is


00000000 00000000 00000000 00100011
after shifting it right by two, it would produce
00000000 00000000 00000000 00001000
for d. which is equivalent to 8.

Each time you shift the value to the right. It divide the value by 2 and discard the remainder.
thus you may take advantage of right shift to perform high speed division.
whenever you are shifting a value to the right, leftmost bit is filled its previous value. that is
called sign extension because that property keep sign of number unchanged.

An Example:
class RightShiftPreserve {
public static void main(String args[]) {
int a = -8;
int b = (a >> 2);

[Link]("a is " + a);


[Link]("b is " + b);
}
}

Output of the above program is:

a is -8
b is -2

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


In the example given above binary representation of -8 in 32 bit format is
11111111 11111111 11111111 11111000
after shifting it right by two, it would produce
11111111 11111111 11111111 11111110
for b. which is equivalent to -2.

Unsigned Right Shift (>>>):


Unsigned right shift (also known as Right shift zero fill) is similar to right shift except one thing. It
does not exhibit sign extension. In case of right shift left most bit is lost and rightmost bit is filled
with its previous value for each shift. but in case of Unsigned right shift, rightmost bit is always
filled with zero without concerning its previous value.

An Example:
class UnsignedRightShift {
public static void main(String args[]) {
int c = -1;
int d = (c >>> 1);

[Link]("c is " + c);


[Link]("d is " + d);
}
}

output of the above program is:

c is -1
d is 2147483647

In the example given above binary representation of -1 is


11111111 11111111 11111111 11111111
performing unsigned right shift by one make it
01111111 11111111 11111111 11111111
which is equivalent to 2147483647.

Bitwise Assignment Operator:


Bitwise Assignment operators provide you ability to shorten the syntax of evaluating expression
and assigning result to a variable, same as Arithmetic Assignment Operator.

General form of bitwise assignment is:


variable operator= expression

like to right shift variable a by 2 you often write


a = a >> 2;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


with the help of bitwise assignment operators that can be re-written as
a>>=2;

both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.

An Example:
class BitwiseAssign {
public static void main(String args[]) {
int a = 9;
int b = 14;

a|=b;
[Link]("Bitwise OR Assignment: a is " + a);

a = 9;
a&=b;
[Link]("Bitwise AND Assignment: a is " + a);

a = 9;
a^=b;
[Link]("Bitwise XOR Assignment: a is " + a);

a = 8;
a>>=2;
[Link]("Right Shift Assignment: a is " + a);

a = -8;
a>>>=2;
[Link]("Unsigned Right Shift Assignment: a is " + a);

a = 8;
a<<=2;
[Link]("Left Shift Assignment: a is " + a);
}
}

Output of the above program is:

Bitwise OR Assignment: a is 15
Bitwise AND Assignment: a is 8
Bitwise XOR Assignment: a is 7
Right Shift Assignment: a is 2

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Unsigned Right Shift Assignment: a is 1073741822
Left Shift Assignment: a is 32

Summary Of Bitwise Logical Operators:

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

0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 0 1 0
1 1 1 1 0 0

Boolean Logical Operators:


Boolean logical operators are used to perform operation over boolean data type and result of
these operation is also a boolean value (i.e. true/false).
Operators Result
! Unary NOT
& Logical AND
| Logical OR
^ Logical Exclusive OR
&= AND Assignment
|= OR Assignment
^= XOR Assignment

Logical AND:
Logical AND produces true if all operands are true, in all other cases it will produce false.
let say we have a variable named a of boolean type stores true.
Currently a = true;
And we have another variable named b of boolean type stores false
Currently b = false;
so a & b is false because true & false = false.

Logical OR:
Logical OR produces true if any operands is true, if all operands are false then produce false.
let say we have a variable named a of boolean type stores true.
Currently a = true;
And we have another variable named b of boolean type stores false
Currently b = false;
so a | b is true because true | false = true.

Logical XOR:
Logical XOR produces true if exactly one operands is true, if all operands are true or all are
false then produce false.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


let say we have a variable named a of boolean type stores true.
Currently a = true;
And we have another variable named b of boolean type stores false
Currently b = false;
so a ^ b is true because true ^ false = true.

Logical Unary NOT(!):


Logical unary NOT produces invert value of operand. only booelan data type is supported.
let say we have a variable named a of boolean type stores true.
Currently a = true;
!a is false because invert of true if false.

An Example:
class Logical {
public static void main(String args[]) {
boolean a = true;
boolean b = false;

boolean c = a|b;
[Link]("a|b is " + c);

boolean d = a&b;
[Link]("a&b is " + d);

boolean e = a^b;
[Link]("a^b is " + e);

boolean f = !a;
[Link]("!a is " + f);
}
}

Output of the following program is:


a|b is true
a&b is false
a^b is true
!a is false

Summary of boolean logical operators:

A B A|B A&B A^B !A

False False False False False True


False True True False True True

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


True False True False True False
True True True True False False

Boolean Assignment Operator:


Boolean Assignment operators provide you ability to shorten the syntax of evaluating
expression and assigning result to a variable (same as Arithmetic Assignment Operator).

General form of arithmetic assignment is:


variable operator= expression

Let say we have two boolean variables named a and b. a have value true and b have value
false. to perform boolean OR of a with b and assign result to we often write
a = a|b;
with the help of boolean assignment operators that can be re-written as
a|=b;

both expressions are equivalent, but second one saves you a bit from typing additional
characters that is why these operators are known as ‘shorthand’ operators. also they are
implemented more efficiently by java run time system then their equivalent long forms.

An Example:
class BooleanAssign {
public static void main(String args[]) {
boolean a = true;
boolean b = false;

a|=b;
[Link]("a|=b is " + a);

a&=b;
[Link]("a&=b is " + a);

a^=b;
[Link]("a^=b is " + a);
}
}

output of the above program is:

a|=b is true
a&=b is false
a^=b is false

Conditional Operators:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Operators Result
&& Short Circuit AND
|| Short Circuit OR
?: Ternary if-then-else

Short Circuit AND (&&):


As we all know that boolean AND (&) operator evaluate expression to true if and only if all
operands are true. if any of them is false then expression is evaluated to false. In other words
we can say that if left hand side operand is false then value of right hand side operator does not
have any effect on final result. In that case our boolean AND (&) operator still look for operand
that is on right hand side even it does not affect result.
But our short circuit AND (&&) operator do not look for operand on right hand side if it is
sufficient to get result from left hand side operand.

Short Circuit OR (||):


As we all know that boolean OR (|) operator evaluate expression to true if any operand is true.
In other words we can say that if left hand side operand is true then value of right hand side
operator does not have any effect on final result. In that case our boolean AND (&) operator still
look for operand that is on right hand side even it does not affect result.
But our short circuit OR (||) operator do not look for operand on right hand side if it is sufficient to
get result from left hand side operand.

An Example:
class ShortCircuit {
public static void main(String args[]) {
int i = 0;
int j = 1;

if((j == 1) || (i == 1)){
[Link]("That is Short-circuit OR");
[Link]("No need to evaluate (i == 1)");
}

boolean a = false;
boolean b = false;

if(a && !b){


[Link]("That is Short-circuit AND");
[Link]("No need to evaluate !b");
}

if(!a && !b){


[Link]("That is Short-circuit AND");
[Link]("Now, evaluating !b");

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}
}

Output of type program given above is:

That is Short-circuit OR
No need to evaluate (i == 1)

That is Short-circuit AND


Now, evaluating !b

Ternary Operator (?:):


Ternary operator is used as alternative of if then else. general form of ternary operator is
expression1 ? expression2 : expression3;
Here expression1 can be any expression evaluated to a boolean value. If expression1 is
evaluated to true then expression2 is evaluated otherwise expression3 is evaluated.

An Example:
class TernaryDemo {
public static void main(String args[]) {
int i = 1;
int j = i==0?i:i+10;

[Link](" i is " + i);


[Link](" j is " + j);
}
}

Output of the above program is:

i is 1
j is 11

The Assignment Operator:


The assignment operator is the single equal ( = ). It has general form
var = expression;
Here variable must be compatible with the expression otherwise you must type cast expression
to data type of var.

Operator Precedence In Java:


Operator precedence in java is shown in the table given below.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Automatic Type Promotion In Expression:
Java automatically converts short and byte operand to int whenever evaluating an expression.

An Example:
class ATP {
public static void main(String args[]) {
byte a = 100;
byte b = 20;
byte c = 10;

int i = a*b/c;
[Link]("i is " + i);
}
}

in that example given above variable a and b are of data type byte. Expression a*b/c is
evaluated as (a*b)/c. a*b produces 2000 that is larger than what a byte variable can hold. that is
why operand a and b are promoted to int. This means subexpression a*b is evaluated using int,
not byte.

An Example:
class ATP2{
public static void main(String args[]) {
byte a = 20;
byte b = 2;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


//byte c = a/b; error
byte c = (byte)(a/b);
[Link]("c is " + c);
}
}

Output of the above program is:

c is 10

while the statement byte c = a/b; produces an error because while evaluating a/b both operands
a and b are promoted to int hence result is also an integer value. but variable that is left to the
assignment operator is byte hence target type is smaller in size so you have to type cast it
explicitly as we have done in next statement.

The Type Promotion Rules:


If your expression involve several data type then final result of expression will belong to largest
data type.

An Example:
class TypePromo {
public static void main(String args[]) {
byte b = 2;
short s = 5;
int i = 10;
float f = 11.2f;
double d = 111.23;
double result = ((b*f)/i) + f*s + d;
[Link]("result is " + result);
}
}

Output of the above program is:

result is 169.47000167846682

In the expression
double result = ((b*f)/i) + f*s + d;
(b*f) will produces result in float because float is larger than byte. output of that subexpression is
22.4. i.e (b*f) = 22.4.
22.4/i will produces result in float because float is larger than integer. output of that sub-
expression is 2.24. i.e ((b*f)/i) = 2.24
f*s will produces result in float because float is larger than short. output of that subexpression is
56.0. i.e f*s = 56.0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


and finally float + float + double will produces result in double because double is largest among
them.

Unit-V
Control Flow Statements

So far we have written so many java program and found a common observation that flow of
execution is top to bottom and instructions are executed in linear order, means instruction that
comes first (from top) in source file get executed first.

In that chapter we are going to study some special instructions that allow you to control flow of
execution. We can broadly classify these instruction in three categories.
1. Selection or Decision making
2. Looping or Iteration
3. Branching statements or Jump;

Let us have a closer look at each category.

Decision Making or Selection:


Decision making statement involves use of if, if-else, switch-case statements.
if :
That is most basic decision making statement. It tells your program to execute a certain section
of code only if a particular condition evaluates to true. General form of if statement is:
if(condition){
Group of statements (to be executed if condition is true);
}
In the above code segment Group of statements are executed if, condition that is provided

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


between pair of parenthesis is evaluated to true. otherwise that group of statements will be
bypassed by java run time system.

An Example:
class IfDemo {
public static void main(String args[]) {
int i = 20;
if(i%2 == 0){
[Link](i + " is an even number");
}
}
}

Output of program given above is

20 is an even number

In the example given above if remainder of i with 20 is equal to zero then statements written
within pair of parenthesis for if will be executed. If remainder not equal to zero (Let say for i =
21) then statements within pair of parenthesis for if will be bypassed.

One important point:


If we do not use curly braces with if block then scope of if block will be limited to just one
statement.

An Example:
class IfDemoWOBraces {
public static void main(String args[]) {
int i = 21;
if(i%2 == 0)
[Link](i + " is an even number");
[Link]("I will be executed every time");

}
}

Output of the above code segment is

I will be executed every time

Because we are not placing curly brackets with if block, hence scope of if block is limited to just
one statement that is [Link](i + " is an even number"); and statement
[Link]("I will be executed every time"); is out of its scope. simply it is like
if(i%2 == 0){

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link](i + " is an even number");
}
[Link]("I will be executed every time");

So no matter whether variable i holds an even number or odd number statement


[Link]("I will be executed every time"); will be executed every time you run that
program.

Nested if:
One if statement can be placed inside another if statement. if that are inside another if are called
nested if. programmer can make any number of nested if as per his requirement.

An Example:

class NestedIf {
public static void main(String args[]) {
int age = 80;
if(age >= 18){
[Link]("You are not minor");
if(age >= 65){
[Link]("Even you are a senior citizen");
}
}
}
}

Output of the above program is:

You are not minor


Even you are a senior citizen

In the example given above, we have nested if(age >= 65) into if(age >= 18). [Link] if will
only be checked for condition if and only if condition for outer if is evaluated to true.

if-else:
The if-else statement provides a another path of execution when an if clause evaluates to false.
General form of if-else is
if(condition){
Group of statements (to be executed if condition is true);
}else{
Group of statements (to be executed if condition is false);
}

Above general form is self explanatory no need to explain.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


An Example:
class IfElseDemo {
public static void main(String args[]) {
int age = 15;
if(age >= 18){
[Link]("You are not minor");
[Link]("You are free to take your decision");
}else{
[Link]("You are minor");
[Link]("Be careful! You need guidance");
}
}
}

Output of the above program is:

You are minor


Be careful! You need guidance

As you can observe when condition given within parenthesis is evaluated to false then code
segment written within else block is executed.

Similar for if statement given above If we do not use curly braces with if/else block then scope of
if/else block will be limited to just one statement.

One important point:


if-else blocks are always comes in continuation i.e. no statement is allowed between end of if
block and starting of else block.

An Example:
class BetweenIfElse {
public static void main(String args[]) {
int age = 15;
if(age >= 18){
[Link]("You are not minor");
[Link]("You are free to take your decision");
}
[Link]("I can’t come here");
else{
[Link]("You are minor");
[Link]("Be careful! You need guidance");
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

If you try to compile that code it will produce an error because we have placed a line
[Link]("I can’t come here"); between end of if block and start of else block, that is
not allowed.

if-else-if ladder:
General form of if-else-if ladder is:
if(condition){
group of statements;
}else if(condition){
group of statements;
}else if(condition){
group of statements;
}
.
.
.else{
group of statements;
}

The if statements are executed from the top to down as usual. As soon as one of the conditions
associated with the if is true, the group of statements written block of that if are executed, and
the rest of the ladder is simply bypassed. If none of the conditions is true, then group of
statement for final else will be executed. The final else acts as a default condition; that is, if all
other conditions fail, then the last else is performed. If there is no final else and all other
conditions are false, then no action will be performed.

An Example:
class IfElseLadder {
public static void main(String args[]) {
int score = 76;

if (score >= 60) {


[Link]("Hurray! first division");
} else if (score >= 48) {
[Link]("Second division! its okay");
} else if (score >= 36) {
[Link]("Thank god! third division");
} else {
[Link]("Alas! Repeat");
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

Output of the program given above is:

Hurray! first division

In the program given above, first condition is evaluated to true hence Hurray! first division is
printed and subsequent code is bypassed. if score is set to 30 then all condition would
evaluates to false and final else part will be executed so output will Alas! Repeat.

switch-case statement:
It is a multi-way branching statement. It provides facility to execute different part of code based
on value of expression. It is used as an alternative of large if-else-if ladder. Genaral form of
switch statement is:
switch(expression){
case value1:
statement sequence for value1
break;
case value2:
statement sequence for value2
break;
case value3:
statement sequence for value2
break;
.
.
case valueN:
statement sequence for valueN
break;
default:
default statement sequence
}

● A switch statement works for primitive data type byte, short, int and char.
● Each case must have a unique literals, duplicate values are not allowed.

An Example:
class SwitchCaseDemo{
public static void main(String args[]) {
int division = 1;

switch(division){
case 1:
[Link]("Hurray! first division");

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


break;
case 2:
[Link]("Second division. it's okay");
break;
case 3:
[Link]("Third division. just pass");
break;
default:
[Link]("Alas! repeat");
}
}
}

Output of the above program is:

Hurray! first division

In switch case value of expression is evaluated first and compared with available case literals. If
match found then statement sequence for corresponding case is executed. if no match i found
then statement sequence written for default is executed.

So in above program value of division is 1 that is matched with first case so output is Hurray!
first division. if value of division is other than 1, 2 and 3 then no match will found and statement
sequence for default will executed and output of that program will be Alas! repeat.

break is used to terminate statement sequence. It is an optional statement. If break is not used
to terminate statement sequence then statement sequence for subsequent cases including
default will be executed.

An Example:
class SwicthCaseWOBreak {
public static void main(String args[]) {
int division = 1;

switch(division){
case 1:
[Link]("Hurray! first division");
case 2:
[Link]("Second division. it's okay");
case 3:
[Link]("Third division. just pass");
default:
[Link]("Alas! repeat");
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}

Output of above program is:

Hurray! first division


Second division. it's okay
Third division. just pass
Alas! repeat

Although omitting break could be useful under certain situations.

An Example:
class OmittingBreak{
public static void main(String args[]) {
int division = 1;

switch(division){
case 1:
case 2:
case 3:
[Link]("Pass");
default:
[Link]("Fail");
}
}
}

Output of the above program is:

Pass

Whether you take division 1, 2 or 3 result will be displayed as Pass and for all other values it will
be Fail.

Nested Switch:
Just like nested if a switch statement can be nested within another switch.

An Example:
class NestedSwitch {
public static void main(String args[]) {
int division = 2;
char grade = 'D';

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


switch(division){
case 1:
[Link]("You are first division");
switch(grade){
case 'A':
[Link]("You have scored more than 90
marks");
break;
case 'B':
[Link]("You have scored more than 75
marks");
break;
case 'C':
[Link]("You have scored more than 60
marks");
break;
}
break;
case 2:
[Link]("You are second division");
switch(grade){
case 'D':
[Link]("You have scored more than 50
marks");
break;
}
break;
case 3:
[Link]("You are third division");
switch(grade){
case 'E':
[Link]("You have scored more than 40
marks");
break;
}
break;
default:
[Link]("Fail");
}
}
}

Output of the above program is:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


You are second division
You have scored more than 50 marks

No conflict arises between cases of outer if and nested if, because both have their separate set
of cases.

An Example:
class NestedSwitchDuplicateCase {
public static void main(String args[]) {
int outerswitch = 1;
int innerswitch = 1;

switch(outerswitch){
case 1:
[Link]("inside outer switch");
switch(innerswitch){
case 1:
[Link]("inside inner switch");
}
}
}
}

Output of the program given above is:

inside outer switch


inside inner switch

Comparison Between if-else and Switch-case:


● Switch can only check for equality while if-else can evaluate any type of boolean
expression.
● Switch cannot be used for float literals while if can be used for float literals.
● Switch case are often faster than equivalent if-else-if ladder. because compiler maintains
a table of all cases called “jump table”. whenever expression is evaluated its value is
checked for equality with the entries in jump table and corresponding statement
sequence is executed. Thus switch statement is much faster then equivalent if-else-if
ladder.

Looping or Iteration:
Iteration statements involve while, do-while and for loop.

while loop:
It is most basic loop statement supported by java. while loop repeat a block of statement while
its controlling condition is true. General form of while loop is:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


while(condition){
Sequence of statements
}

Condition can be any boolean expression. Sequence of statement written within scope of while
loop (also called body of loop) is executed until condition is evaluated to false. As condition
goes false, the control passes to the statement written just next to while loop block.

An Example:
class WhileDemo {
public static void main(String args[]) {
int loopCounter = 1;

while(loopCounter <= 10){


[Link]("Loop counter is " + loopCounter);
loopCounter++;
}
[Link] ("I am after loop");
}
}

Output of program given above is

Loop counter is 1
Loop counter is 2
Loop counter is 3
Loop counter is 4
Loop counter is 5
Loop counter is 6
Loop counter is 7
Loop counter is 8
Loop counter is 9
Loop counter is 10
I am after loop

In the code given above, loopCounter is initialized to 1 and variable loopCounter is checked
whether it is less than or equal to 10. Condition is true hence body of loop is executed so output
comes on screen is “Loop counter is 1” then loopCounter is incremented by one. as control
touches end of loop body, it goes back to condition, here again condition checking takes place
and if it is true then again body of loop is executed. finally when condition goes false for
loopCounter’s value 11 then control passes to instruction [Link] ("I am after loop");
so finally it prints I am after loop.

You can also create infinite loop like

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class WhileInfi {
public static void main(String args[]) {
while(true){
[Link] ("I am going to execute forever");
}
}
}

Output of the above program is

I am going to execute forever


I am going to execute forever
I am going to execute forever
.
.
.
prints I am going to execute forever infinite time

In the code segment given above we have place true instead of condition so obviously it will
never go false. Hence an infinite loop.

Similar to if statement, If we do not use curly braces to define scope of while block then scope
will be limited to just one statement.

do while loop:
As we have observe that in while loop condition is evaluated first if it goes true then body of loop
is executed but if condition is evaluated to false for first time then body of loop never get chance
to execute.

Now us consider a situation, when we make a call to customer care office, an audio file that hold
menu content is played and ask to enter choice. if we enter an invalid option then audio file is
played again else we go through next phase or we can say audio file is played at-least for once
no matter what choice we will enter when asked so.

To address such kind of situation we use do-while loop. General form of do-while loop is:
do{
Sequence of statement
}while(condition);

do-while loop executes body of loop first then check condition. if condition is evaluated to true
then body of loop is executed again else control goes to instruction that comes next to
while(condition) statement.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


An Example:
class doWhileDemo {
public static void main(String args[]) {
int loopCounter = 11;
do{
[Link]("loopCounter is " + loopCounter);
}while(loopCounter <= 10);
[Link]("I am after loop");
}
}

Output of the program above is

loopCounter is 11
I am after loop

In the example given above we have set value of loopCounter to 11 we have setted condtion
loopCounter <= 10. As we have discussed above in case of do-while loop, body of loop is
executed at-least once no matter whether he condition is going to false or true. so output comes
loopCounter is 11 and when condition is checked it is evaluated to false hence no repeated
execution of body takes place and control now comes to instruction that is next to
while(loopCounter <= 10); that is [Link]("I am after loop"); and prints I am after loop.

Similar to if statement, If we do not use curly braces to define scope of do-while block then
scope will be limited to just one statement.

for loop:
for loop provides a compact way of iteration. It is a powerful and flexible construct. general form
of for loop is:
for(initialization; condition; iteration){
Sequence of statement
}

Initialization express initialization of loop, it is executed only once as the loop begins. normally
used to initialize loop control variable.
Condition is check every time before entering into body of loop it must be a boolean expression
if condition is evaluated to true then body of loop executed else control passes to the instruction
that comes next to body of loop.
Iteration is executed each time after execution of body of loop. It is normally an expression that
changes loop control variable.

An Example:
class forDemo {
public static void main(String args[]) {

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


for(int loopCounter = 1; loopCounter <= 10; loopCounter++){
[Link]("loopCounter is " + loopCounter);
}
[Link]("I am after loop");
}
}

Output of the above program is

loopCounter is 1
loopCounter is 2
loopCounter is 3
loopCounter is 4
loopCounter is 5
loopCounter is 6
loopCounter is 7
loopCounter is 8
loopCounter is 9
loopCounter is 10
I am after loop

In the example given above, initialization (i.e. int loopCounter = 1) statement is executed in first
step, then condition (i.e. loopCounter <= 10) is checked in second step if condition is evaluated
to true, then body of loop is executed, then iteration (i.e. loopCounter++) is executed. Now
again control goes to second step, condition is checked and if condition is evaluated to true,
then body of loop is executed, then iteration (i.e. loopCounter++) and so on. Until condition does
not evaluated to false.

Here variable loopCounter is defined withing the scope of for loop hence it is not accessible
outside for for loop’s block.

One important point:


In for loop all three statements, initialization, condition and iteration are optional. we are free to
omit any of them or all three statements from loop.

class ForIniItr {
public static void main(String args[]) {
int loopCounter = 1;
for(;loopCounter <= 10;){
[Link]("loopCounter is " + loopCounter);
loopCounter++;
}
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Output of the program above is

loopCounter is 1
loopCounter is 2
loopCounter is 3
loopCounter is 4
loopCounter is 5
loopCounter is 6
loopCounter is 7
loopCounter is 8
loopCounter is 9
loopCounter is 10

Here we have omit initialization and iteration but loop control variable is initialized before start of
for loop and iteration is place inside loop body.

if we omit all three, then it will be an infinite loop.

An Example:
class ForInfi {
public static void main(String args[]) {
for(;;){
[Link] ("I am going to execute forever");
}
}
}

Output of the above program is

I am going to execute forever


I am going to execute forever
I am going to execute forever
.
.
.
prints I am going to execute forever infinite time

We haven’t place any condition to stop execution of loop body so it’s an infinite loop

Also it is possible to place multiple initialization and iteration in for loop using comma operator.

An Example:
class ForMultiIniItr {

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String args[]) {
for(int a= 4, b= 1; a > 0; a--,b++){
[Link]("a = " + a + " b = " + b);
}
}
}

Output of the above program is

a=4b=1
a=3b=2
a=2b=3
a=1b=4

Nested Loop:
A loop can be placed inside another loop. Programmer can make any number of nested loop as
per his requirement.

An Example
class NestedLoop {
public static void main(String args[]) {
for(int row = 4; row > 0; row--){
for(int col = 0; col < row; col++){
[Link]("*");
}
[Link]();
}
}
}

Output of program given above is

****
***
**
*

Branching statements or Jump:


Java provides three branching statements that are break, continue and return.

break:
break has two forms
1. Unlabeled: Normally we are using break in unlabeled form. we have already used it with
switch case to prevent execution of subsequent cases.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


it is also used for breaking loop.

An Example:
class BreakLoop{
public static void main(String args[]){
for(int i = 0; i <= 10; i++){
if(i == 5){
break;
}
[Link](“i is ” + i);
}
[Link](“Loop completed”);
}
}

Output of program given above is

i is 0
i is 1
i is 2
i is 3
i is 4
Loop completed

break can be used to terminate any type of loop ,mainly it is used to exit infinite loop.

An Example:
class BreakInfinite{
public static void main(String args[]){
int i = 0;
while(true){ //it’s an infinite loop
[Link](“I am in infinite loop”);
if(i == 5){
[Link](“Now infinite loop is going to break”);
break;
}
i++;
}
[Link](“Loop completed”);
}
}

Output of the code given above is:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


I am in infinite loop
I am in infinite loop
I am in infinite loop
I am in infinite loop
I am in infinite loop
I am in infinite loop
Loop completed

if break is used with nested loops, then it will break only loop inside which break is used.

An Example:
class InnerBreak{
public static void main(String args[]){
for(int i = 0; i<= 2; i++){
for(int j =0; j<= 2; j++){
[Link](“i is ”+i+“ j is “ + j);
if(j == i){
[Link](“Breaking inner loop”);
break;
}
}
}
}
}

Output of the program given above is

i is 0 j is 0
Breaking inner loop
i is 1 j is 0
i is 1 j is 1
Breaking inner loop
i is 2 j is 0
i is 2 j is 1
i is 2 j is 2
Breaking inner loop

2. Labeled: Labeled breaks are used to break deep structures and mainly used to break
inner loops an inner switch cases.

General form of labeled break is


break label;

Here, label is the name of a label that identifies a block of code. When this form of break

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


executes, control is transferred out of the named block of code. To name a block, just
place a label at the start of it. A label is any valid java identifier followed by colon. when
break with label name executes control goes to instruction coming next to the block.
An Example:
class LabeledBreak{
public static void main(String args[]){
A:{
B:{
C:{
for(int i = 0; i <= 5; i++){
if(i == 2){
break B;
}
[Link]("i is " + i);
} //closing for loop
[Link]("I won’t execute");
} //closing C block
[Link]("I won’t execute");
} //closing B block
[Link]("After block having label B");
} //closing A block
}
}

Output of the program given above

i is 0
i is 1
After block having label B

In the code segment given above, we have written a line break B; when that line get
executed, control jumps outside B block and start executing instruction that is next to
end of B block.

continue:
We have seen with break, it take control out of the block and executes instruction that is next to
block. We have another branching statement that is continue. it brings control at the start of
block, opposed to break that brings control at the end of block.

An Example:
class ContinueDemo{
public static void main(String args[]){
for(int i = 0; i <= 10; i++){
if(i%2 == 0){

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


continue;
}
[Link](“i is ” + i);
}
}
}

Output of program given above is:

i is 1
i is 3
i is 5
i is 7
i is 9

In the code segment given above we have placed continue inside if block,that checks whether
the given number is even or not, if number is even that control goes to start of for loop (meaning
to say at increment, not at initialization) and then checking condition with updated value and
again enter into block and do its execution.

So far we have seen that continue have its effect just for the loop in which it is used. Although it
is possible to extend its effect for outer loop using loop label. A loop label is a label that have a
loop in it, a loop label does not enclose its loop in curly braces.

An Example:
class LoopLabel{
public static void main(String args[]){
A:for(int i = 1; i <= 3; i++){
[Link]("i is " + i);
B:for(int j = 1; j<= 2; j++){
[Link]("j is " + j);
if(j%2 == 0){
continue A;
}
}
}
}
}

Output of the program given above is

i is 1
j is 1
j is 2

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


i is 2
j is 1
j is 2
i is 3
j is 1
j is 2

return:
Final statement that is used for branching is return. Similar to C/C++, return is used to terminate
execution of a method and return control back to the caller of method. return statement can be
used to terminate execution of a method with return a value as well as to without returning
anything.

An Example:
class ReturnDemo{
public static void main(String args[]){
boolean isReturn = true;
if(isReturn){
[Link]("Going back to caller");
return;
}
[Link]("I won't executed ever");
}
}

Output of the program given above is

Going back to caller.

In the code segment given above last print statement will never be executed because we have
placed return statement before it and that statement will execute because variable isReturn is
true.

One important point:


Be careful while using return statement, careless use of return may cause compiler to generate
unreachable code error.

An Example:
class CarelessReturn{
public static void main(String args[]){
[Link]("Going back to caller");
return;
[Link]("I won't executed ever");
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

In code segment given above, compiler will produce “Unreachable code” error, because return
statement will get executed in every time. We have placed no condition over its execution.

We will take a deep look at return statement in upcoming chapters.

Unit-VI
A Closer Look to Arrays

Array:
An array is a collection of similar typed variable that are referred to by a common name. Each
item in array is called element and each element is accessed by its numeric index. Numeric
index begins with zero and ends to one less than length of array.

One Dimensional Array:


Creating an array is two step process:
1. Declaration: General form of declaring an array is
type var-name[];
or
type[] var-name;
Here type define the data type of array. i.e. type of value that every element of array hold.
Square bracket indicates that variable holds an array. size of array is not part of declaration. and
var-name is any valid name of array.
e.g. int month[];
Above discussion so far is just declaration of an array still we have to allocate memory to it.

2. Constructing or allocating memory: Memory is allocated to an array using new operator.


General form of constructing an array is
var-name = new type[size];
here var-name is name of the array. new is an operator that provide memory to variable. type is
simply data type of array and size indicate no of elements that it can hold.
e.g. month = new int[10];
step 1 and step 2 can be combined as
type[] var-name = new type[size];

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


e.g. int[] month = new int[12];

Initializing An Array:
General form of initializing an array is
type[] var-name = {initializing values};
When initialization is used, no need to use new operator because memory is allocated implicitly
for total number of elements specified in initialization list.
e.g. int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

In the example given above month is an array of integer type with 12 elements and these
elements are initialized by value 31, 28, 31...........and so on.
first element of that array that is month[0] have value 31, second element month[1] have value
28. Last element of array that is month[11] have value 31.

As we have discussed in the above each element in the array is referred with a numeric index
and these index are continuous, so we can use loops to access array elements.

An Example:
class ArrayDemo{
public static void main(String args[]){
int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for(int i = 0; i <= 11; i++){
[Link]("Month " +(i +1)+ " have " + month[i] + " days");
}
}
}

Output of the program given above is:

Month 1 have 31 days


Month 2 have 28 days
Month 3 have 31 days
Month 4 have 30 days
Month 5 have 31 days
Month 6 have 30 days
Month 7 have 31 days
Month 8 have 31 days
Month 9 have 30 days
Month 10 have 31 days
Month 11 have 30 days
Month 12 have 31 days

One important point:


In C/C++, there exists have a big problem with array that is, both languages do not performs

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


bound checking. Means let say we have an array that have 5 element and if we write code to
access 6th element then no error would be reported either at compiler time or at run time. But
java performs bound checking that is, if we try to access any element that is outside range of
array then error message will be displayed at run time and java halts program immediately.

An Example:
class BoundCheck{
public static void main(String args[]){
int[] month = {31};
[Link]("month 2 have " + month[1] + " days");
}
}
In the code segment given above we have declared an array month that have just one element
and that element is at index 0. but in print statement we are accessing element, having index 1
means 2nd element of array. when we compile that program no error will be generated but at run
time program will display an error message.

Also java implements array as an object. To find size of an array, java provides inbuilt project
lenght, that returns total number of elements in array.

class ArrayLength{
public static void main(String args[]){
int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
[Link]("Array month have " + [Link] + " elements");
}
}

Output of program given above is:

Array month have 12 elements

The for-each loop:


Before moving to multi-dimensional array it is time to be familiar with one more type of loop that
is for-each loop. for-each loop is particularly useful for arrays.
General form of for loop is
for(type var:arr){
//body of loop
}

An Example:
class ForeachDemo{
public static void main(String args[]){
int[] marks = {18, 18, 17, 15, 10};
int sum = 0;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


for(int currentMarks : marks){
sum = sum + currentMarks;
}
[Link]("Sum is " + sum);
}
}

Output of the program given above is:

Sum id 78

In the code segment given above


for(int currentMarks : marks){
sum = sum + currentMarks;
}

is equivalent to

for(int i = 0; i < [Link]; i++){


int currentMarks = arr[i];
sum = sum + currentMarks;
}

By using foreach loop we don’t required to create and maintain a variable that deals with index
of array.
Multidimensional Array:
Like C/C++, Java also supports multidimensional [Link] we are taking example of 2-
dimensional array, similar rules are all applied for higher dimensions .Similar to one
dimensional, Creating a 2-D array is also two step process:
1. Declaration: General form of declaring a 2-D array is
type var-name[][];
or
type[][] var-name;
Here type define the data type of array. i.e. type of value that every element of array hold.
Square bracket indicates that variable holds an array. size of array is not part of declaration. and
var-name is any valid name of array.
e.g. int matrix[][];
Above discussion so far is just declaration of an array still we have to allocate memory to it.

2. Constructing or allocating memory: Memory is allocated to an array using new operator.


General form of constructing an array is
var-name = new type[row_size][col_size];
here var-name is name of the array. new is an operator that provide memory to variable. type is
simply data type of array and row_size indicate no of 1-D array and col_size indicates no of

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


elements in a 1-D array.
e.g. matrix = new int[3][4];
step 1 and step 2 can be combined as
type[] var-name = new type[row_size][col_size];
e.g. int[][] matrix = new int[3][4];

Initializing 2-D array:


To initialize a 2-D array, Simply put each 1-D array’s initializing values in the their own curly
braces separated by comma, and put entire set of curly braces in one pair of curly braces.

An Example:
class TwoDArrayIni{
public static void main(String args[]){
int matrix[][] = {
{31, 28, 31, 30},
{31, 30, 31, 31},
{30, 31, 30, 31}
};

for(int row = 0; row < 3; row++){


for(int col = 0; col < 4; col++){
[Link](matrix[row][col] + " ");
}
[Link]();
}
}
}

Output of the program above is

31 28 31 30
31 30 31 31
30 31 30 31

Java provides facility of creating array with uneven rows, means we can create an array that
have different number of elements in each row. To do that, just specify first dimension of array
and no. of element for each row can be specified separately later on.

An Example:
class UnevenArray{
public static void main(String args[]){
int matrix[][] = new int[3][];
matrix[0] = new int[2];
matrix[1] = new int[3];

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


matrix[2] = new int[4];

for(int row = 0; row < [Link]; row++){


for(int col = 0; col < matrix[row].length; col++){
matrix[row][col] = row + col;
}
}

for(int row = 0; row < [Link]; row++){


for(int col = 0; col < matrix[row].length; col++){
[Link](matrix[row][col] + " ");
}
[Link]("");
}
}
}

Output of the program given above is

01
123
2345

In the program given above matrix is a 2-D array. its first 1-D array have 2 elements, second 1-
D array have 3 and last 1-D array have 4 elements. We have just specified number of rows at
the time of declaration that is merged with memory allocation. but number of element for each
row are defined in subsequent lines.

finally using length property of array with 2-D array returns number of 1-D arrays that it have
and using it with 1-D array returns number of elements that it have. hence [Link] returns
3 while matrix[0].length returns 2.

Unit-VII
A Deep Look at Classes and its Members

At the time of starting, we have discussed object oriented concept in details, very first concept
that we were discussing was class. classes are base of object oriented programming. In
examples that we have seen so far, we were using it just to encapsulate main method because
in java, It is essential to put every concept that we want to implement inside class.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


One important point:
So far we have just created one class and place main method in that class. main method is not
necessarily part of a class we can create a class without main method.

It is time to take deep look on classes and know about all facilities that a class can provide us.

General form a class in java is:


class class-name{
//field,constructor,and method declarations
}
As we have already discussed, A class is a passive entity. A class does not have any physical
reality. We have to create object of class to create a physical entity.

General form of creating an object is


class-name obj-name = new class-name();

Here class-name is name of class whose object is being created, and obj-name is name of
object. we are free to choose any valid name for an object. new is an operator that is used to
allocate memory dynamically.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}

Save above code in [Link]

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp = new MobilePrice();

[Link] = 1000;
[Link]= 4.5f;
[Link] = 3.5f;

float totalPrice = [Link] + [Link] *


[Link] / 100 + [Link] * [Link] / 100;

[Link]("Total mobile price is " + totalPrice);


}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Save above code in [Link]

In the example given above we have created a class named MobilePrice that have three
variables. We have also created another class MobilePriceDemo that have main. In first line of
main, we have created object of class MobilePrice. Before moving ahead it would be beneficial
to take a deep look at object creation.

Object Creation:
Actually creating an object is two step process
Step 1: Creating a reference of class. General form of creating a reference is
class-name obj-name;
actually a reference is variable that point to an object. To create a reference of MobilePrice
class we just need to write
MobilePrice mp;
now our reference mp does not pointing to any object. It have value null.

Step 2: Allocating object and assign it to reference. General form is


obj-name = new class-name();
new operator simply allocate memory and return its address, that is assigned to obj-name.
To create an object of class MobilePrice, we just need to write.
mp = new MobilePrice();

For the sake of convenience, java allow us to merge both steps. we just need to write
class-name obj-name = new class-name();
and we have already use that form in example given above. that’s all about object creation in
java.

(Although step 2 contains one more step that is initialization, we will discuss about it later in
same chapter.)

The two step procedure can be understood with the help of figure given below.

(creating an object of MobilePrice class)

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


What is new Operator:
new is a operator provided by java that is responsible for allocating memory dynamically. new
operator take data type as an operand and allocate space equivalent to the size of data type
and return a reference to memory allocated.

General form of using memory using new operator is


obj-name = new class-name();

One thing to note about new is, it allocate memory at run time. But memory is finite, so
sometime it is not possible for new to allocate memory due to insufficient space. In such
situation a run time exception takes place (We will discuss about Exception Later in details).

An important point:
Java apply dynamic memory allocation for arrays and object not for primitive data types.
Reason behind implementing primitive data type not as an object is interest of efficiency.
because creating an object at run time generate a significant overhead and java require to
maintain attributes of each object separately. Java implement primitive data types simply to
avoid overhead and achieve speed.

Instance Variable:
In the starting chapters we have defined object as an instance of class & all variable that are
defined within a class are called instance variable. To access instance variable outside class &
static members (discussed later in details).We have to use dot(.) operator, that links object
name with instance variable name. General form for accessing instance variable using object is:
[Link]-variable-name

In the code segment given above we have written


[Link] = 1000;

to access instance variable manufacturingCost of object mp and assigned it 1000 or simply we


can say, that code segment tells compiler to assign value 1000 to copy of manufacturingCost
that is contained within mp object. similar for exciseDuty and serviceTax.
finally we have created a local variable (a variable that is defined withing a method) totalPrice of
float type in main and assigned final price to it.

compile both files and to run, simply write


java MobilePriceDemo
on console and then hit enter.

output of the program given above is

Total mobile price is 1080.0

Interesting to know, variable defined in a class are called instance variable because they are

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


separate to each instance of class or we can simply say them variable for each instance. means
if we have two different object of class MobilePrice then each of them have it’s own copy of
instance variables. Changing instance variable of one object should not affect instance variable
of another object.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;

[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;

float totalPriceForMp1 = [Link] + [Link] *


[Link] / 100+ [Link] * [Link] / 100;

float totalPriceForMp2 = [Link] + [Link] *


[Link] / 100 + [Link] * [Link] / 100;

[Link]("Total mobile price for mp1 is " + totalPriceForMp1);


[Link]("Total mobile price for mp2 is " + totalPriceForMp2);

[Link] = 1200;
[Link] = 2.3f;
[Link] = 3.7f;

totalPriceForMp1 = [Link] + [Link] *


[Link] / 100+ [Link] * [Link] / 100;

totalPriceForMp2 = [Link] + [Link] *


[Link] / 100 + [Link] * [Link] / 100;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]("Total mobile price for mp1 is " + totalPriceForMp1);
[Link]("Total mobile price for mp2 is " + totalPriceForMp2);

}
}

Output of the code given above is:

Total mobile price for mp1 is 1080.0


Total mobile price for mp2 is 1560.0
Total mobile price for mp1 is 1080.0
Total mobile price for mp2 is 1272.0

In the code given above we have created two object mp1 and mp2 of class MobilePrice and we
have assigned different value to each instance variable of mp1 and mp2. When we are
calculating total price for mp1 and mp2, final prices are calculated on basis of values of their
own instance variable.

In the next line when we have changed values of instance variables of mp2 then again
calculating mobile prices for both object, we get same price for mp1 but different for mp2
because changing values of instance variable for mp2 does not affect values of instance
variable for mp1.

Object Reference Assignment:


Consider following code segment
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = mp1;

If you are familiar with c++, then you might thinking that mp2 is now referring another object that
is similar to what mp1 is referring currently, because default object assignment in c++ create bit-
wise copy of object that is being assigned. mp1 and mp2 refer to different object and changing
instance variable of mp1 does not affect mp2.

But that is not true for java. whenever we are performing such kind of assignment, java does not
make bit-wise copy of object being pointed by assigning reference instead it just create a copy
of assigning reference. means after assignment we have another reference variable that points
to similar object currently pointed by assigning reference.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


(Assigning mp1 to mp2 does not create a new object, just both references start to point same object)

Hence if we make changes in values of instance variable using one reference variable then
changes will be effective for another reference because ultimately they are pointing to same
object.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = mp1;

[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;

float totalPriceForMp1 = [Link] + [Link] *


[Link] / 100+ [Link] * [Link] / 100;

[Link]("Total mobile price for mp1 is " + totalPriceForMp1);

[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;

float totalPriceForMp2 = [Link] + [Link] *


[Link] / 100 + [Link] * [Link] / 100;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


totalPriceForMp1 = [Link] + [Link] *
[Link] / 100+ [Link] * [Link] / 100;

[Link]("Total mobile price for mp2 is " + totalPriceForMp2);


[Link]("Total mobile price for mp1 is " + totalPriceForMp1);
}
}

Output of the program given above is:

Total mobile price for mp1 is 1080.0


Total mobile price for mp2 is 1560.0
Total mobile price for mp1 is 1560.0

In the code segment given above, in first line of main method we have created an object of
class MobilePrice that is mp1 and we have assigned into reference variable mp2. Now mp1 and
mp2 referring to same object.
Then we have assigned values to instance variable of mp1 and calculating total price for mp1
that is 1080.0 Now we have make changes in instance variable using mp2. because both
reference variables point to same location hence these changes are also applied to mp1. So
calculating total price for mp1 and mp2 provides same result.

Also when we assign null to reference mp2 then it will not affect mp1. because mp2 simply hold
null and mp1 points to object.

Array Of Object:
Similar to an array of primitive data type it is possible to create an array of object. Creating an
array of objects is a bit similar to creating an uneven array. It is a two step process.

1: Create an array of reference, general form of creating an array is


class-name obj-name[] = new class-name[SIZE];

In that step we are just creating array of reference so far we have not allocated memory for

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


objects.

2: Allocate memory for each object separately


obj-name[0] = new class-name();
obj-name[1] = new class-name();
.
.
obj-name[SIZE - 1] = new class-name();

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mpArray[] = new MobilePrice[2]; //creating array of reference
for(int i = 0; i < 2; i++){
mpArray[i] = new MobilePrice(); //Assigning memory to each individually
mpArray[i].manufacturingCost = 1000 + i*100;
mpArray[i].exciseDuty= 4.5f + i*1.0f;
mpArray[i].serviceTax = 3.5f + i*1.0f;
}

for(int i = 0; i < 2; i++){


float totalPrice = mpArray[i].manufacturingCost + mpArray[i].exciseDuty *
mpArray[i].manufacturingCost / 100 + mpArray[i].serviceTax *
mpArray[i].manufacturingCost/100;
[Link]("Total mobile price of mpArray[" + i + "] is " +
totalPrice);
}
}
}

Output of program given above is:

Total mobile price of mpArray[0] is 1080.0


Total mobile price of mpArray[1] is 1210.0

Method:
Now we are going to discuss methods. We all know that to in C language, we create functions
to perform a specific task and these functions are called according to requirement. Similar to

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


functions, OOP provides us facility to create function inside class called method. General form
of declaring a method is

return-type method-name(parameter list) {


//body of method
}

Here return-type defines type of value, returned by method. if a method does not return a value
then return-type must be void. In java it is essential to define return type of method.

method-name as term itself define, is simply name of method.

parameter-list is simply sequence of type and identifiers separated by comma. If a method do


not have any parameter, then simply place a blank pair of parenthesis after method-name.

One important point:


Everything defined within a class including variables and methods are called member of class.

As we have studied, to access an instance variable outside class, we write


[Link]-variable-name;
Similarly to call a method outside the class we have to use dot(.) operator. to call a method
simply write
[Link]-name(argument-list);

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

void calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100 +
serviceTax * manufacturingCost / 100;
[Link]("total price of mobile is " + totalPrice);
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

[Link] = 1000;
[Link] = 4.5f;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link] = 3.5f;

[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;

[Link]();
[Link]();
}
}

Output of the program given above is:

total price of mobile is 1080.0


total price of mobile is 1560.0

A method of a class is always called relative to an object of that class and once invocation takes
place, the calling object is known hence there is no need to use object again to accessing
instance variable.

Take a look at last two line of main.


[Link]();
[Link]();

First line calculate price for mp1 because calculatePrice() is called relative to mp1 and once
invocation takes place compiler knows about calling object hence variable that are used inside
calculatePrice belongs to mp1.

As that line segment executes then control goes to code defined inside calculatePrice method.
after statements inside calculatePrice have executed. control goes back to statement that
comes after [Link]().

Returning a value from method:


In Our previous example, we have printed final price of mobile inside method. but it is not a
good practice. We might need final price of mobile to perform some more operation, like
providing a certain discount on final price. To handle such kind of situation it is better to get final
price returned from method.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

[Link] = 1000;
[Link] = 4.5f;
[Link] = 3.5f;

[Link] = 1500;
[Link] = 2.5f;
[Link] = 1.5f;

float totalpriceFormp1 = [Link]();


float totalpriceFormp2 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


[Link]("Final price for mp2 is " + totalpriceFormp2);
}
}

Output of program given above is:

Final price for mp1 is 1080.0


Final price for mp2 is 1560.0

We must be careful for following points when returning a value


1. Value that is being returned must be compatible with return type specified by method. If
both type are not compatible then compiler will report an error.
2. Returned value must be stored in compatible variable.

Method With parameter:


Parameter make a method useful in larger variety of situation because using parameter they
can be operated with different-different values.

First It is better to understand difference between parameter and argument.


Parameter: A parameter is a variable defined by a method and receives a value when a method

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


is called.

Argument: An argument is a value that is passed when a method is called.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

void setPriceElement(int m, float s, float e){


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
}

float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

[Link](1000, 4.5f, 3.5f);


[Link](1500, 2.5f, 1.5f);

float totalpriceFormp1 = [Link]();


float totalpriceFormp2 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


[Link]("Final price for mp2 is " + totalpriceFormp2);
}
}

Output of program given above is:

Final price for mp1 is 1080.0


Final price for mp2 is 1560.0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


In the code segment given above we have defined parametrized method setPriceElement that
accept three parameter of int, float and float type. On execution of line
[Link](1000, 4.5f, 3.5f);

1000 is copied to local variable m, 4.5f is copied to local variable s and 3.5f is copied to local
variable e. Values of m,s,e are assigned to instance variables manufacturingCost, serviceTax
and exciseDuty respectively. because method setPriceElement is called for object mp1 hence
instanc variable that accessed inside method setPriceElement belong to object mp1. Similar
execution takes place for mp2.

Constructor:
Now let us Consider a situation, we have a file that have information of 25 mobile phones. we
have to create objects, each representing a mobile phone. We have to open that file and read
information of each mobile then create objects and then call a Parametrized method that
initializes state of each object with values stored in file. In the whole processing we have to call
Parametrized method for all 25 objects. Java provides us a better way to do so using
constructor. Constructor provides us ability to initialize object when they are created.

● A constructor have name same as class name.


● It should be defined inside the class hence It can access instance member directly
without using object.
● It is called automatically after object is created, before new operator completes.
● A constructor does not have an return type because implicit return type of a constructor
is object of class type itself.

General form of constructor is


class-name(parameter-list){
//body of constructor
}

A Constructor is mainly used for initialization.

In the previous example we have used setPriceElement method to initialize instance member of
object now we are going to do same opration using constructor. Initailly we are using simplest
form of constructor that is without parameters.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

MobilePrice(){
[Link](“Inside Constructor”);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


manufacturingCost = 1000;
serviceTax = 3.0f;
exciseDuty = 2.0f;
}

float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

float totalpriceFormp1 = [Link]();


float totalpriceFormp2 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


[Link]("Final price for mp2 is " + totalpriceFormp2);
}
}

Output of program given above is


Inside Constructor
Inside Constructor
Final price for mp1 is 1050.0
Final price for mp2 is 1050.0

In the code segment given above, On execution of line


MobilePrice mp1 = new MobilePrice();

following operation takes place


● Memory is allocated for an object of MobilePrice.
● Constructor is called and instance variables manufacturingCost, serviceTax and
exciseDuty of object created in step 1, are initialized to values 1000, 3.0f and 2.0f.
● The reference is returned by new operator and stored in mp1.

We have place empty pair of parenthesis after ’new MobilePrice’ to call constructor that do not
accept any parameter. We will study that topic in detail when we discuss constructor
overloading in subsequent chapter.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


for the next line of code
MobilePrice mp2 = new MobilePrice();
same steps would be repeated and both objects have there instance variable initialized with
common values. Hence calling calculatePrice bring same result for both objects.

One important Point:


Before the example that we have just discussed we didn’t use constructor in any example. If we
don’t create constructor in a class then java itself provides a constructor that initializes all
instance variable to their default values. But if we have provided constructor to a class, Java
remove its default constructor. Default values are as follows:

Data Type Default Value


byte 0
short 0
int 0
long 0
float 0.0f
double 0.0d
char ‘\u0000’
String null
boolean false

Parametrized constructor:
In the Example discussed above we are using constructor that do not accept any parameter
hence we are unable to initialize instance variable for each object uniquely. To address that
problem we can use parametrized constructor. passing argument to constructor is similar to
passing argument in method. Just we have to specify arguments at the time of object creation.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

MobilePrice(int m, float s, float e){


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
}

float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 3.5f, 1.5f);
MobilePrice mp2 = new MobilePrice(1500, 3.0f, 2.0f);

float totalpriceFormp1 = [Link]();


float totalpriceFormp2 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


[Link]("Final price for mp2 is " + totalpriceFormp2);
}
}

Output of program given above is:

Final price for mp1 is 1050.0


Final price for mp2 is 1575.0

In the program given above, we have defined parametrized constructor in MobilePrice class.
When we are creating object of class MobilePrice, we have to specify arguments for
constructor. In the first line of main we are passing arguments 1000, 3.5f and 1.5f. hence after
memory allocation instance variable manufacturingCost, serviceTax & exciseDuty are initialized
to 1000, 3.5f and 1.5f. finally a reference of allocated memory is assigned to mp1.
Similar operation will take place for creation of object mp2. because both objects have different
value for their own instance variables hence calling method calculatePrice for each of them
produce different result.

The finalize() Method:


If you are familiar with C++, you have used destructors to perform a certain action that should
be performed when an object goes out of scope or when you delete an object. Although java
does not support destructors but provides another way to do the same using finalize method.

General form of finalize method is:


protected void finalize(){
//body of finalize
}

Garbage collector does not claim an object as it goes out of the scope. It runs periodically,
checking for objects that are no longer referenced and finally claim memory location occupied
by unreferenced object. Whatever we want to perform at the time of reclaiming, we should write
in finalize method. like simply we can have situation in which we have an object that have

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


occupied a file an before that object get deleted we must want to close that file.

One thing to keep in mind is that we cannot determine when garbage collector is going to claim
an object hence we cannot confirm when finalize will be executed and even if it will be executed.
Using finalize is not a reliable solution.

The this keyword:


Java provides ‘this’ keyword that allow to refer to calling object inside class. Simply we can say
‘this’ is reference to object on which a method/constructor is called.

An Example:
MobilePrice(int m, float s, float e){
[Link] = m;
[Link] = s;
[Link] = e;
}

In the Code segment given above we have used ‘this’ keyword to access instance members of
calling object. although in the previous examples we don’t use ‘this’ because our compiler
already know which object calls it. In normal it is absolutely unnecessary to use ‘this’ but in
some situation it is very much useful.

Instance Variable Hiding:


Java allows us to create local variable for methods that have same name as instance variable
have. As we all know that local variable get precedence over instance variable hence using
same name for both local and instance variable hides instance variable.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

MobilePrice(int manufacturingCost, float serviceTax, float exciseDuty){


manufacturingCost = manufacturingCost;
serviceTax = serviceTax;
exciseDuty = exciseDuty;
}

float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 3.5f, 1.5f);

float totalpriceFormp1 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


}
}

Output of program given above is

Final price for mp1 is 0.0

In the example given above we have used same name for instance variable as well as local
variable of constructor. due to locality, variables that are defined inside constructor hides
instance variable. In that constructor we are assigning value of local variable manufacturingCost
to local variable manufacturingCost. Hence We are hiding instance variable manufacturingCost
by local variable manufacturingCost.

To overcome such problem ‘this’ keyword is a key solution.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

MobilePrice(int manufacturingCost, float serviceTax, float exciseDuty){


[Link] = manufacturingCost;
[Link] = serviceTax;
[Link] = exciseDuty;
}

float calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100+
serviceTax * manufacturingCost / 100;
return totalPrice;
}
}

class MobilePriceDemo{

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 3.5f, 1.5f);

float totalpriceFormp1 = [Link]();

[Link]("Final price for mp1 is " + totalpriceFormp1);


}
}

Output of program given above is

Final price for mp1 is 1050.0

Here using [Link] (on left hand side of assignment operator) specifies that we
are using instance variable of calling object and manufacturingCost (on right hand side of
assignment operator) is simply refer to local variable.

static Keyword:
So far we have learned about instance variable. Instance variable are specific for each instance
(object) of class. Java provides us facility to create variable that are not specific to objects of
class using static keyword.

To create a static variable just precede its declaration with static keyword. a static variable have
following characteristics
● A static variable belongs to a class, not to an objects.
● Because they are not specific to objects, hence only a single copy is maintained.
● Also static variable does not belong to object hence it can be accessed using class
name to which they belong. To access a static variable simply write
[Link]-variable-name;
Although It is possible to access a static variable using object name. using class name to
access is recommended.
● Java does not supports static local variable i.e. it is not possible to create a local variable
with static keyword.

Similar to static variable we can also create static method. To declare a method static just
precede its signature with static keyword. A static method have following characteristics
● A static method belongs to a class, not to an object.
● Because they are not specific to objects, hence can be called using class name to which
they belong. To call a static method simply write
[Link]-method-signature;
● Because static methods are not specific to objects, they can not access instance
variable of an object, but can access static variables. for the same reason static method
cannot call a non-static method without an object, but can call another static method.
● Because static methods are not specific to objects, hence ‘this’ keyword is not available,

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


and super keyword is also not available. (We will discuss super in subsequent chapters)

An Example:
class MobilePrice {
static int modelNo;
int mobilePrice;
float serviceTax;
float exiseDuty;

MobilePrice(int m, float s, float e){


modelNo = 1100;
mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

static int getModelNo(){


return modelNo;
}

static void setModelNo(int mn){


modelNo = mn;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}

public static void main(String[] args) {


MobilePrice mp1 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp2 = new MobilePrice(1000, 3.0f, 4.0f);
MobilePrice mp3 = new MobilePrice(1000, 1.0f, 5.0f);

//accessing static variable with class name


[Link]("Total price of mp1 having model no "+ [Link]
+" is " + [Link]());

//a static member can access static variable directly


[Link]("Total price of mp2 having model no "+ modelNo +" is " +
[Link]());

//a static member call another static method directly

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]("Total price of mp3 having model no "+ getModelNo() +" is " +
[Link]());

//only a single copy exists, hence changes reflect everywhere


[Link](1110);

[Link]("\nTotal price of mp1 having model no "+


[Link] +" is " + [Link]());

//accessing static member using object


[Link]("Total price of mp2 having model no "+ [Link] +" is " +
[Link]());

[Link]("Total price of mp3 having model no "+ getModelNo() +" is " +


[Link]());
}
}

Output of the program given above is

Total price of mp1 having model no 1100 is 1050.0


Total price of mp2 having model no 1100 is 1070.0
Total price of mp3 having model no 1100 is 1060.0

Total price of mp1 having model no 1110 is 1050.0


Total price of mp2 having model no 1110 is 1070.0
Total price of mp3 having model no 1110 is 1060.0

In the code given above we have created a static variable modelNo and a static method
getModelNo. In in subsequent lines we have accessed modelNo with different styles. Because
only a single copy of modelNo exists that is shared between all objects, hence changes made
reflect for all others.

Variables that are declared within a class without static keywords are specific to instance, hence
called instance variable of class. But variable that are declared with static keyword are specific
to class hence these variables are called class variables. For the same reason methods having
their signature preceded with static are called class methods.

We have studied about constructor that are called implicitly at the time of object creation and
mainly used to initialize instance variable of an object. Although constructors can also be used
to initialize class variables but java provides a better way to initialize class variables using static
block. A static block is executed only once when class is first loaded to JVM. General form of
static block is

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


static{
//body of static block
}
A static block is executed exactly once, at the loading of class.

An Example:
class MobilePrice {
static int modelNo;
int mobilePrice;
float serviceTax;
float exiseDuty;

static{
[Link]("Inside static block");
modelNo = 1100;
}

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

static int getModelNo(){


return modelNo;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}

public static void main(String[] args) {


MobilePrice mp1 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp2 = new MobilePrice(1000, 3.0f, 4.0f);
MobilePrice mp3 = new MobilePrice(1000, 1.0f, 5.0f);

//accessing static variable with class name


[Link]("Total price of mp1 having model no "+ [Link]
+" is " + [Link]());

//a static member can access static variable directly


[Link]("Total price of mp2 having model no "+ modelNo +" is " +

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]());

//a static member call another static method directly


[Link]("Total price of mp3 having model no "+ getModelNo() +" is " +
[Link]());
}
}
Output of program given above is:

Inside static block


Total price of mp1 having model no 1100 is 1050.0
Total price of mp2 having model no 1100 is 1070.0
Total price of mp3 having model no 1100 is 1060.0

final Qualifier:
Creating a program requires declaring constant identifiers. To declare a constant identifier
simply precede its declaration with final keyword. Doing so prevent content of that identifier from
being modified. We must initialize such identifier at the time of declaration.

In the previous example declare modelNo as static variable but that variable is changeable to
avoid any accidental change, simply precede its declaration with final and initialize it.

An Example:
class MobilePrice {
static final int MODEL_NO = 1100;
int mobilePrice;
float serviceTax;
float exiseDuty;

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

static int getModelNo(){


return MODEL_NO;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp2 = new MobilePrice(1000, 3.0f, 4.0f);
MobilePrice mp3 = new MobilePrice(1000, 1.0f, 5.0f);

//accessing static variable with class name


[Link]("Total price of mp1 having model no "+
MobilePrice.MODEL_NO +" is " + [Link]());

MODEL_NO = 10; // Error

//a static member can access static variable directly


[Link]("Total price of mp2 having model no "+ MODEL_NO +" is " +
[Link]());

//a static member call another static method directly


[Link]("Total price of mp3 having model no "+ getModelNo() +" is " +
[Link]());
}
}

Output of program given above is:


Total price of mp1 having model no 1100 is 1050.0
Total price of mp2 having model no 1100 is 1070.0
Total price of mp3 having model no 1100 is 1060.0

Command Line Arguments:


Command line arguments are used to pass information to a java program when it is running.
Command line arguments are passed by simply putting them after class name at time of running
a program. Command line arguments are stored in String array that is part of main method. To
access them simply refer to index of String array.

An Example:
class CommandLineDemo {
public static void main(String[] args) {
for(int i = 0; i < [Link]; i++){
[Link]((i+1)+ " command line argument is-" + args[i]);
}
}
}

Compile that code and To pass command line argument simply type
java CommandLineDemo all is well

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Output of code given above is:

1 command line argument is-all


2 command line argument is-is
3 command line argument is-well

To pass multiword string as a single argument simply enclose them in single/double quotes
java CommandLineDemo 'all is well'

Output of code in that case is

1 command line argument is-all is well

Unit-VIII
A Deep Look at Method and Constructor

In last chapter we have read about class, creating a method in a class, creating constructor etc.
Its time to take a deep look at methods, constructor and know about high level flexibilities
provided by java to both.

Method Overloading:
Consider a situation, you are asked by your trainer to make an assignment. Your Assignment is

”Create a program that add two integers, two floating point numbers and two characters. you
have to create separate function to perform each addition do not mesh all code inside main
function.”

One way to do is create three different methods like addInt, addFloat and addChar. and call
them separately. In that scenario you have to remember name of each method. although you
are performing same operation but just due to different types of parameter you have use
different name for each. Method overloading provides a smart way to deal with such kind of
problems.

Method overloading allow us to create more than one method in a class that have same name.
These method must differ in types of parameter they accept or number of parameter they

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


accept or both.

Return type does not play any role in method overloading. if more than one method have same
name, same number of parameters with same type but different return type, then compiler will
report an error.

An Example:
class Overload {
int add(int firstNumber, int secondNumber){
return (firstNumber + secondNumber);
}

float add(float firstNumber, float secondNumber){


return (firstNumber + secondNumber);
}

char add(char firstNumber, char secondNumber){


return (char)(firstNumber + secondNumber);
}
}

class OverloadDemo{
public static void main(String[] args) {
Overload ol = new Overload();

int intAddition = [Link](1,2);


float floatAddition = [Link](1.5f,2.5f);
char charAddition = [Link]('A',' '); // second argumentis space ascii code 32

[Link]("intAddition is " + intAddition);


[Link]("floatAddition is " + floatAddition);
[Link]("charAddition is " + charAddition);
}
}

Output of program given above is:

intAddition is 3
floatAddition is 4.0
charAddition is a

In that program given above we have defined three method each of them have same name that
is add. first version of add method accepts two integer parameter, second accept two float
parameter and third accept two character parameter. All three methods perform same addition

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


operation.

Look at the syntax of calling them inside main method, they are looking same. At the time of
calling, we just have to specify arguments. In other way we can say that we have implemented
“single interface multiple methods”, that is polymorphism. Because decision of calling specific
version is taken at compile time that is why we say method overloading is a way to implement
compile time polymorphism.

When overloaded methods are called, compiler matches number of argument and type of
argument to parameter, and based on that matching, specific version of method is called. In
above example we have call add method three times. first time we have called it with two
integer arguments hence out of three available versions, first is matched exactly hence it is
called. for the second time when float values are passing as an arguments then second version
is called.

If java compiler do not find exact match then automatic type promotion play its role.

An Example:
class Overload {
int add(int firstNumber, int secondNumber){
return (firstNumber + secondNumber);
}

double add(double firstNumber, double secondNumber){


return (firstNumber + secondNumber);
}

char add(char firstNumber, char secondNumber){


return (char)(firstNumber + secondNumber);
}
}

class OverloadDemo{
public static void main(String[] args) {
Overload ol = new Overload();

int intAddition = [Link](1,2);


double doubleAddition =[Link](1.5f,2.5f);//argument:float, parameter:double
char charAddition = [Link]('A',' '); // second argumentis space ascii code 32

[Link]("intAddition is " + intAddition);


[Link]("doubleAddition is " + doubleAddition);
[Link]("charAddition is " + charAddition);
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

Output of code segment given above is

intAddition is 3
doubleAddition is 4.0
charAddition is a

Here in second call of add, we are passing float values while we haven’t define any version of
add that accept float as a parameter. here float is automatically promoted to double and second
version of add is called.

Constructor Overloading:
Similar to method overloading, java allow us to overload constructors also. We may have some
situation when we do not want to initialize all instance variable of an object. We may want to
initialize one or two instance variable. Now Look at example that we have discussed in
parameterized constructor, we have passed three arguments in constructors. In that case
creating an object without passing three argument is an error. Constructor Overloading provides
us facility to deal with such situation.
Similar to method overloading, more than one version of constructor should either have different
number of parameter or different types of parameter.

An Example:
public class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;

MobilePrice(){
mobilePrice = 0;
serviceTax = 0.0f;
exiseDuty = 0.0f;
}

MobilePrice(int m){
mobilePrice = m;
serviceTax = 0.0f;
exiseDuty = 0.0f;
}

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1000);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);

[Link]("Total price for mp1 is " + [Link]());


[Link]("Total price for mp2 is " + [Link]());
[Link]("Total price for mp3 is " + [Link]());
}
}

Output of code given above is

Total price for mp1 is 0.0


Total price for mp2 is 1000.0
Total price for mp3 is 1050.0

In the example given above we have defined three versions of constructor. first version do not
have any parameter. Second have one parameter and third have three parameters. At the time
of object creation arguments are matched to parameters, and based on that matching
constructors are called. for
MobilePrice mp1 = new MobilePrice();
first constructor that do not accept any parameter is called. and for
MobilePrice mp2 = new MobilePrice(1000);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);
second and third versions are called.

Passing Object as a Parameter:


So far we have passed primitive data type as an argument. It is possible to pass an object as an
argument in java. Object are passed by call by reference mechanism.

An Example:
class MobilePrice {
int mobilePrice;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


float serviceTax;
float exiseDuty;

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

boolean haveSamePrice(MobilePrice mp){


float totalPrice = calculatePrice();
float totalPriceForMp = [Link]();
if(totalPrice == totalPriceForMp){
return true;
}
return false;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1250, 2.0f, 1.9f);
MobilePrice mp2 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp3 = new MobilePrice(1000, 3.0f, 2.0f);

[Link]("mp1 and mp2 have same price? " +


[Link](mp2));
[Link]("mp2 and mp3 have same price? " +
[Link](mp3));
[Link]("mp3 and mp1 have same price? " +
[Link](mp1));
}
}

Output of code given above is

mp1 and mp2 have same price? false


mp2 and mp3 have same price? true

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


mp3 and mp1 have same price? false

In the Example given above we have created a method haveSamePrice. That method takes an
object of MobilePrice as a parameter. Objects are passed just same inbuilt data type are
passed.

We can also pass object to constructor. Passing object as an argument is particularly useful
when we want to create an object that is same as an already existing object.

An Example:
class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

MobilePrice(MobilePrice mp) {
mobilePrice = [Link];
serviceTax = [Link];
exiseDuty = [Link];
}

boolean haveSamePrice(MobilePrice mp){


float totalPrice = calculatePrice();
float totalPriceForMp = [Link]();
if(totalPrice == totalPriceForMp){
return true;
}
return false;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;
}
}

class MobilePriceDemo{

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1250, 2.0f, 1.9f);
MobilePrice mp2 = new MobilePrice(mp1);

[Link]("mp1 and mp2 have same price? " +


[Link](mp2));
}
}

Output of the program given above is

mp1 and mp2 have same price? true

In the Example given above we have defined an another version of constructor that accept
object of MobilePrice class as a parameter. In main function we are passing object mp1 as a
parameter when creating object mp2. In constructor we have initialized all instance variables of
mp2 with values of instance variable mp1. hence comparing prices for these two objects return
true.

Returning Object:
In the previous example, We have seen that an object can be passed as an argument similar to
other data-type. An object can also be returned from a method.

An Example:
class MobilePrice {
int mobilePrice;
float serviceTax;
float exiseDuty;

MobilePrice(int m, float s, float e){


mobilePrice = m;
serviceTax = s;
exiseDuty = e;
}

MobilePrice getNewObject(){
MobilePrice temp = new MobilePrice(mobilePrice+1000,serviceTax,exiseDuty);
return temp;
}

float calculatePrice(){
float totalPrice = mobilePrice + mobilePrice * serviceTax / 100 + mobilePrice *
exiseDuty / 100;
return totalPrice;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}
class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice(1000, 2.0f, 3.0f);
MobilePrice mp2 = [Link]();

[Link](" Total price of mp1 is " + [Link]());


[Link](" Total price of mp2 is " + [Link]());
}
}

Output of the program given above is:

Total price of mp1 is 1050.0


Total price of mp2 is 2100.0

In the Example given above, we have defined a method getNewObject(), that method create a
new object of MobilePrice class and return it. Returning an object is similar to returning a
primitive data type, To collect returning object we just have to create a reference of that class.

One Important Point:


Primitive data types are always call by value hence changes made in parameter does not affect
arguments. While objects are passed by reference hence changes made in parameter affects
arguments.

Recursion:
Simply recursion is defined as a process of repeating an item in a self-similar way or defining
something in the term of itself.. In the terms of function we can say when a function call to itself
than it is known as recursive function.

An Example:
class Fact{
int factorial(int factNo){
if(factNo == 1){
return 1;
}
int result = factorial(factNo-1)*factNo;
return result;
}
}

class FactDemo {
public static void main(String[] args) {

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Fact f = new Fact();
[Link] ("Factorial of 3 is " + [Link](3));
[Link] ("Factorial of 2 is " + [Link](2));
[Link] ("Factorial of 4 is " + [Link](4));
}
}

Output of the given above is:

Factorial of 3 is 6
Factorial of 2 is 2
Factorial of 4 is 24

Whenever a method is called, Space is allocated for its parameters and local variables and as
control return from method, all parameters and local variables stored in stack are destroyed and
memory occupied by them is free for further use.

Recursion allow us to create code that are are simple and cleaner but it generate significant
number of method calls that create larger number of local variables and parameters which may
lead to run out of space. It is also slower than equivalent iterative code.

A closer look at access control:


In previous chapters, we have discussed about encapsulation. that is

“The wrapping up of data and associated function together in a single unit (called class) and
keeps both safe from outside interference and misuse is known as encapsulation.”

So far we have discussed so many examples and in each example we are able to access
variables as well as methods outside the class using object. An uncontrolled access may lead to
misuse of data. To avoid such misuse we may allow access of data only through a set of
methods, means no user can directly access data he can only access methods. Avoiding direct
access of data make your class behave like a black box, the data and inner working is not
available for tempering.

Encapsulation contains one more attribute that is access control. Through access control we
can define which part of program can access members of a class. Java provides four kind of
access specifiers first is private access specifier. Data & methods that are declared as private
in a class are accessible only up to that class. Any Code defined outside that class cannot
access private members. second is protected access specifier, we will discuss it in next
chapters in short we can say that any variable declared as protected is accessible in
subclasses. Third is No-modifier that is also known as default modifier, it is applied when we do
not specify any access specifiers among private public and protected. Variable and methods
that have default access specifiers are accessible with its package (we will discuss about
package in upcoming chapters, till then consider it equivalent to public). Fourth & final is public

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


access specifier. variables and methods that are declared as public are accessible everywhere
means any code that is defined outside class can access public variables and methods.

An Example:
class MobilePrice {
private int manufacturingCost;
private float serviceTax;
private float exciseDuty;

void setMobilePrice(int m, float s, float e){


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
}

void calculatePrice(){
float totalPrice = manufacturingCost + exciseDuty * manufacturingCost / 100 +
serviceTax * manufacturingCost / 100;
[Link]("total price of mobile is " + totalPrice);
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice();

[Link] = 1000;//error! manufacturingCost is private

[Link](1000,2.5,3.5);//okay No modifier means accessible outside


class
[Link](1000,3.5,3.5);

[Link]();
[Link]();
}
}

Output of program given above is

total price of mobile is 1060.0


total price of mobile is 1070.0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Unit- IX
Inheritance

Inheritance:
As we have already discussed in previous chapters, Inheritance is the process by which one
object acquire properties of another object. In that chapter we will take a deep look at how java
implements inheritance.

Before moving to implementation of inheritance we have to understand about basic terminology.

Super class: A class from which another class is derived is called super class.
Sub class: A class that is derived from a superclass is called sub class.

General form of class declaration that inherits a superclass is


class subclass-name extends superclass-name{
//body of class
}
Here extends is a keyword that denote that we are going to create an specific implementation of
super class.

An Example:

class A{
int firstNumber,secondNumber;

void setNumbers(int f, int s){


firstNumber = f;
secondNumber = s;
}

void showNumbers(){
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}

class B extends A{
int thirdNumber;

void setNumber(int t){


thirdNumber = t;
}

void showThirdNumber(){
[Link]("thirdNumber is " + thirdNumber);
}

void average(){
[Link]("Average is " + (firstNumber + secondNumber +
thirdNumber) / 3);
}
}

public class InheritanceDemo {


public static void main(String[] args) {
A bs = new A();
[Link](100,200);
[Link]();

[Link]();

B cd = new B();
[Link](150);
[Link]();

[Link]();

[Link]();
}
}

Output of program given above is:

firstNumber is 100
secondNumber is 200

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


thirdNumber is 150

Average is 50

In the code segment given above, class A is our superclass and b is our sub class. as we can
see in the code of class B, member of class A are also accessible because class B is child class
of A. In simple words we can say that class B is re-using fields and methods of class A.

One important point:


Like C++, java does not support multiple inheritance. It is not possible to create a subclass that
have more than one superclass.

Member access & inheritance


In the code segment given above, sub-class is able to access all members of its super-class.
Although it is possible to control access of a superclass member in java using access specifiers.
To prevent access of instance or class member of a superclass in sub class, simply declare
them private. Instance or class members that are declared as private are only accessible in their
own classes, not anywhere else including their subclass.

An Example:

class A{
private int firstNumber;
private int secondNumber;

void setNumbers(int f, int s){


firstNumber = f;
secondNumber = s;
}

void showNumbers(){
//ok because private members are accessed in the their own class
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);
}

int getAddition(){
return (firstNumber + secondNumber);
}
}

class B extends A{
int thirdNumber;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


void setNumber(int t){
thirdNumber = t;
}

void showThirdNumber(){
//Error! trying to access private members outside their class
[Link]("firstNumber is " + firstNumber);
[Link]("secondNumber is " + secondNumber);

[Link]("thirdNumber is " + thirdNumber);


}

void average(){
//Error! tyring to access private member outside their class
[Link]("Average is " + (firstNumber + secondNumber +
thirdNumber) / 3);

//ok
[Link]("Average is " + (getAddition() + thirdNumber) / 3);
}
}

public class InheritanceDemo {


public static void main(String[] args) {
A bs = new A();
[Link](100,200);
[Link]();

[Link]();

B cd = new B();
[Link](150);
[Link]();

[Link]();

[Link]();
}
}

Output of program given above is:

firstNumber is 100

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


secondNumber is 200

thirdNumber is 150

Average is 50
In the program given above, we have declared firstNumber & secondNumber as private
members of class A. As we have discussed in previous chapter, private member is only
accessible in their own class. Trying to access these members int showThirdNumber() and
average() leads to error. To get addition of firstNumber & secondNumber, we have created a
method getAddition() in class A, that returns addition of them.

Superclass reference & child class object:


Java allow a reference variable of a Superclass to point a subclass object that is derived from
same superclass.

An Example:
class A{
int firstNumber;
int secondNumber;

void setNumber(int f, int s){


firstNumber = f;
secondNumber = s;
}

int getAddition(){
return (firstNumber + secondNumber);
}
}

class B extends A{
int thirdNumber;

void setThirdNumber(int t){


thirdNumber = t;
}

void showThirdNumber(){
[Link]("thirdNumber is " + thirdNumber);
}

int average(){
return (firstNumber + secondNumber + thirdNumber) / 3;
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

public class SuperReference{


public static void main(String[] args) {
A a = new A();

[Link](10, 20);
[Link]("Addition of numbers for object a is " + [Link]());
[Link]();

B b = new B();

//sub class have access to members of superclass


[Link](1, 2);
[Link](3);
[Link]("Addition of numbers for object b is " + [Link]());
[Link]("Average of numbers for object b is " + [Link]());
[Link]();

//reference c of class A points to object of class B


//now both c and b point to same object
A c = b;

[Link]("Addition of numbers for object b is " + [Link]());


[Link]();
//Error superclass do not have any knowlegde about sub class' instance //method
//[Link]("Average of numbers for object b is " + [Link]());

//reference d of class A now point to new object of class A


A d = new B();

[Link](5, 6);
[Link]("Addition of numbers for new object of B is " +
[Link]());
//Error superclass do not have any knowlegde about sub class' instance
//variable
[Link]("Third numbers for object d is " + [Link]);
}
}

Output of program given above is:

Addition of numbers for object a is 30

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Addition of numbers for object b is 3
Average of numbers for object b is 2

Addition of numbers for object b is 3

Addition of numbers for new object of B is 11

A Realistic Example:
Now its time to take a Realistic Example of using inheritance. So far in previous code we have
used three parameters to calculate price of a mobile that are manufacturingCost, serviceTax
and exciseDuty. Let us consider a scenerio when a new tax has been imposed on mobile price
(say sales tax) in a particular area and now we have two options to implement it in code. first
one is modify the code that we have already created and second is simply apply inheritance, to
reuse already available code. Obviously second choice is better. Not take a look how we can
implement it.

An Example:
class MobilePrice {
int manufacturingCost;
float serviceTax;
float exciseDuty;

MobilePrice() {
manufacturingCost = 1000;
serviceTax = 2.5f;
exciseDuty = 1.5f;
}

MobilePrice(int m, float s, float e) {


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
}

float getMobilePrice(){
return manufacturingCost + manufacturingCost * (serviceTax + exciseDuty)/100;
}
}

class MobilePriceWithSaleTax extends MobilePrice{


float saleTax;

MobilePriceWithSaleTax(){
manufacturingCost = 1000;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


serviceTax = 2.5f;
exciseDuty = 1.5f;
saleTax = 2.0f;
}

MobilePriceWithSaleTax(int m, float s, float e, float st) {


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
saleTax = st;
}

float getMobilePriceWithSaleTax(){
return manufacturingCost + manufacturingCost * (serviceTax + exciseDuty +
saleTax)/100;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1500, 1.7f, 3.3f);

[Link]("Price of mp1 without sale tax is " + [Link]());


[Link]("Price of mp2 without sale tax is " + [Link]());
[Link]();

MobilePriceWithSaleTax mpst1 = new MobilePriceWithSaleTax();


MobilePriceWithSaleTax mpst2 = new MobilePriceWithSaleTax(2000, 1.3f, 1.7f,
1.5f);

[Link]("Price of mpst1 with sale tax is " +


[Link]());
[Link]("Price of mpst2 with sale tax is " +
[Link]());
}
}

Output of program given above is:

Price of mp1 Price of mp2 without sale tax is 1040.0


Price of mp2 Price of mp2 without sale tax is 1575.0

Price of mpst1 with sale tax is 1060.0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Price of mpst2 with sale tax is 2090.0

In the Example discussed above we class MobilePriceWithSaleTax have all attibutes of


MobilePrice. we do not need to define duplicate code of MobilePrice. With the help of once we
have defined a superclass any number of sub classes can be created with the help of
inheritance.

super:
Preceding example that we have discussed above is not implemented efficiently because our
sub class constructor have to explicitly initialize instance members of superclass. In that
scenario we have to grant access of every instance member of superclass to subclass in order
to initialize them. Building code with that approach leave no way to hide instance member of a
superclass that violate encapsulation that is primary concept of OOP.

That approach also leads to duplicating same code again and again that unnecessarily increase
length of program and make it a bit difficult to manage.

To overcome from that situation java provide us super keyword, that have following purpose.

To Call superclass constructor:


super is used to call a constructor of a superclass from subclass. general form of calling
superclass constructor is
super(parameter-list);

One thing to keep in mind is that super must be first statement inside subclass constructor and if
super is not used inside subclass constructor, default constructor of a superclass is called
implicitly. Hence if a superclass only have parameterized constructor then not using super along
with required parameter to call superclass constructor inside sub class constructor cause error.

An Example:
class MobilePrice {
private int manufacturingCost;
private float serviceTax;
private float exciseDuty;

MobilePrice() {
manufacturingCost = 1000;
serviceTax = 2.5f;
exciseDuty = 1.5f;
}

MobilePrice(int m, float t) {
manufacturingCost = 1000;
serviceTax = t;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


exciseDuty = t;
}

MobilePrice(int m, float s, float e) {


manufacturingCost = m;
serviceTax = s;
exciseDuty = e;
}

int getManufaceuringCost(){
return manufacturingCost;
}

float getServiceTax(){
return serviceTax;
}

float getExcizeDuty(){
return exciseDuty;
}

float getMobilePrice(){
return manufacturingCost + (manufacturingCost * (serviceTax +
exciseDuty))/100;
}
}

class MobilePriceWithSaleTax extends MobilePrice{


float saleTax;

MobilePriceWithSaleTax(){
super();
saleTax = 2.0f;
}

MobilePriceWithSaleTax(int m, float t) {
super(m,t);
saleTax = t;
}

MobilePriceWithSaleTax(int m, float s, float e, float st) {


super(m,s,e);
saleTax = st;
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


float getMobilePriceWthSaleTax(){
return getManufaceuringCost() + (getManufaceuringCost() * (getExcizeDuty() +
getServiceTax() + saleTax))/100;
}
}

class MobilePriceDemo{
public static void main(String[] args) {
MobilePrice mp1 = new MobilePrice();
MobilePrice mp2 = new MobilePrice(1500, 1.7f, 3.3f);

[Link]("Price of mp1 is " + [Link]());


[Link]("Price of mp2 is " + [Link]());
[Link]("”);

MobilePriceWithSaleTax mpst1 = new MobilePriceWithSaleTax();


MobilePriceWithSaleTax mpst2 = new MobilePriceWithSaleTax(2000, 1.3f, 1.7f,
1.5f);

[Link]("Price of mpst1 is " + [Link]());


[Link]("Price of mpst2 is " + [Link]());
}
}

Output of program given above is:

Price of mp1 is 1040.0


Price of mp2 is 1575.0

Price of mpst1 is 1060.0


Price of mpst2 is 2090.0

Accessing hidden instance member of a superclass inside subclass:


Let say we have a superclass named A and we have declared a instance variable intVar, now
we have created a subclass of class A named B and declared a variable inside it with same
name that is intVar. now there is no way to access superclass’ instance variable intVar inside
subclass B because B class already have variable intVat. In simple words we can say that
superclass’ instance variable is hidden by a sub class variable due to same name.

super is useful in that situation, To access hidden instance variable of a class inside subclass
simply precede it by with super keyword and dot operator.

An Example:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class A{
int i = 0;
int j = -1;
void getInA(){
[Link]("Inside A : i is " + i);
}
}

class B extends A{
int i = 10;

void getInB(){
[Link]("Inside B : i is " + i + " super.i is " + super.i);
}
}

class C extends B{
int i = 100;
int j = -2;
void getInC(){
[Link]("Inside C : i is " + i + " super.i is " + super.i);
[Link]("Inside C : j is " + j + " super.j is " + super.j);
}
}

class SuperDemo {
public static void main(String[] args) {
C c = new C();
[Link]();

B b = new B();
[Link]();

A a = new A();
[Link]();
}
}

Output of code given above is:

Inside C : i is 100 super.i is 10


Inside C : j is -2 super.j is -1
Inside B : i is 10 super.i is 0
Inside A : i is 0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


As we can see in example given above we have created a superclass A that have an instance
member i with value 0 and from that superclass we have derived a subclass named B and
having an instance member having name i with value. To access B’s instance variable i inside
class B we simply have to write name of instance variable but to access instance variable i of
superclass A we simply need to write super.i. Similar syntax will be followed for class C.
Inside main we have created an instance of class C and called method getInC(). That method
have used i and super.i. i simply refer to instance variable of class C and super.i refer to
instance variable of its immediate superclass B. hence we are getting output

Inside C : i is 100 super.i is 10

Similar action takes place for next method calls.


One point to remember in above example is, class A is also superclass of class C but super will
refer to its immediate superclass in order to avoid ambiguity in multilevel hierarchy. similar
situation may arive in case of method (superclass and sub class have same method prototype)
super is again useful in such situation (discussed later in that chapter).

Order of Constructor Calling:


Let say we have a class A that is superclass another class that is class B. Similar to that we
have another class C that is sub class of class B. Now a question may arise in your mind that
when we are creating instantiating class C then which constructor is called first?? constructor of
class C or class A.

As we have discussed in previous example that super must be first statement inside sub class
constructor. Reason for placing super at start of subclass constructor is that constructor must be
called in the order of derivation that is from superclass to sub class. If we are using not super to
call superclass constructor then default (constructor with out parameter) constructor of
superclass is called implicitly.

An Example:
class A{
A(){
[Link]("Hello I am in A");
}
}

class B extends A{
B(){
[Link]("Hello I am in B");
}
}

class C extends B{

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


C(){
[Link]("Hello I am in C");
}
}

class ConstructorOrder {
public static void main(String[] args) {
C cobj = new C();
}
}

Output of code given above is:

Hello I am in A
Hello I am in B
Hello I am in C

If we simply replace default constructor of a A by a parameterized constructor


A(int i){
[Link]("Hello I am in A");
}

and try to compile that code, it will produce an error because we have neither called
parameterized constructor using super keyword nor provided default.

Method Overriding:
When a subclass contains a method that have same name and parameters as its superclass
have, then method defined in sub class is said to override method of its superclass. When an
overridden method is called in sub class then sub class always called its own method i.e
superclass method simply become hidden.

An Example:
class A{
int superInstnace;

A(int si){
superInstnace = si;
}

void getInstance(){
[Link]("Inside super class A");
[Link]("superInstance is " + superInstnace);
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class B extends A{
int subInstance;

B(int si){
super(si*2);
subInstance = si;
}

void getInstance(){
[Link]("Inside sub class B");
[Link]("subInstance is " + subInstance);
}

void callGetInstance(){
getInstance();
}
}

class OverRidingDemo {
public static void main(String[] args) {
B bobj = new B(10);
[Link]();
[Link]();
[Link]();
}
}

Output of code given above is:

Inside sub class B


subInstance is 10

Inside sub class B


subInstance is 10

In the example given above we have created a method in superclass A, having name
getInstance and do not accept any parameter and have also created a method in class B having
same prototype. when we are trying to call it from object of class B or inside B it always call
subclass version of method getInstance() hence superclass version is simply hidden. To call
superclass version of getInstance() simply use super keyword inside class B.

An Example:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class A{
int superInstnace;

A(int si){
superInstnace = si;
}

void getInstance(){
[Link]("Inside super class A");
[Link]("superInstance is " + superInstnace);
}
}

class B extends A{
int subInstance;

B(int si){
super(si*2);
subInstance = si;
}

void getInstance(){
[Link]();
[Link]();

[Link]("Inside sub class B");


[Link]("subInstance is " + subInstance);
}
}

class OverRidingDemo {
public static void main(String[] args) {
B bobj = new B(10);
[Link]();
}
}

Output of code given above is:

Inside super class A


superInstance is 20

Inside sub class B


subInstance is 10

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


● One thing to note here is that no restriction is applied on position of super in case of
calling superclass method i.e. it is perfectly alright to place [Link]() in
between some code of class B’s getInstance().

Co-variant return type:


One thing about that a programmer should take care especially. In case of method overriding, if
a superclass have a method that returns an object, and if sub class override that method then
sub class’ method either have same return type or sub type of return type specified in
superclass.

An Example:
class A{
int i = 0;
}
class B extends A{
int j = 0;
}

class SprClass{
A getInstance(){
[Link]("Inside class SuperClass");
return (new A());
}
}

class SbClass extends SprClass{


B getInstance(){
[Link]("Inside class SubClass");
return (new B());
}
}

class CovariantDemo{
public static void main(String a[]){
SbClass sbc = new SbClass();
SprClass spc = new SprClass();
A a = [Link]();
B b = [Link]();
[Link](”i is ” + a.i);
[Link](”i is ” + b.j)
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Output of code given above is:

Inside class SuperClass


Inside class SubClass
i is 1
j is 12

In the code given above we have created superclasses that are A and SprClass that have
subclasses B and SbClass. We have created a method getInstance() in class SprClass that
returns an object of A and override that method in SbClass that returns an object of B. it is ok to
do so because B is subtype of A. but if alter that code slightly exchange return type for both,
then compiler will produce error.

An Example:
class A{
int i = 0;
}

class B extends A{
int j = 0;
}

class SprClass{
B getInstance(){
[Link]("Inside class SuperClass");
return (new B());
}
}

class SbClass extends SprClass{


A getInstance(){
[Link]("Inside class SubClass");
return (new A());
}
}

class CovariantDemo{
public static void main(String args[]){
SbClass sbc = new SbClass();
SprClass spc = new SprClass();

A a = [Link]();
B b = [Link]();

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]("i is " + a.i);
[Link]("i is" + b.j);
}
}

In Code segment given above we have provided just exchanged return type of both and when
we are trying to compile them we are getting error. To correct that code we have to exchange
return type in class SprClass and SbClass.

Dynamic Method Dispatch:


Dynamic method dispatch is the mechanism by which call to an overridden method is resolved
at run time. It is one of the most powerful concept that tells how run time polymorphism is
implemented in java.

Let us start our discussion with a statement that superclass reference variable can point to child
class object. Java uses that concept to resolve overridden method calling at run time. Java
determines which version of that method to execute based upon the type of the object being
referred to, at the time the call occurs. Thus, this determination is made at run time. When
different types of objects are referred to, different versions of an overridden method will be
called. Decision of calling a specific implementation of same interface is made at run time on the
basis of object being referred.

Thus if superclass have a method that is also overridden by subclass then when different types
of objects are pointed by superclass reference variables then different version of methods are
executed.

An Example:
class A{
void overRided(){
[Link]("Inside overRided of class A");
}
}

class B extends A{
void overRided(){
[Link]("Inside overRided of class B");
}
}

class C extends B{
void overRided(){
[Link]("Inside overRided of class C");
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class DMD {
public static void main(String[] args) {
A aobj = new A();
[Link]();

B bobj = new B();


[Link]();

C cobj = new C();


[Link]();

[Link]("View effect of Dynamic Method Dispatch");

A temp;

temp = cobj;
[Link]();

temp = bobj;
[Link]();

temp = aobj;
[Link]();
}
}

Output of code given above is:

Inside overRided of class A


Inside overRided of class B
Inside overRided of class C
View effect of Dynamic Method Dispatch
Inside overRided of class C
Inside overRided of class B
Inside overRided of class A

In the code segment given above in first three calls of overRided method, object and reference
variables belong to same class hence they call their own methods but in last three cases calling
of specific implementation takes place on the basis of object being referred and that decision is
taken at run time.

Real Life Example of Method Overriding:


Cosider a situation, A college provides course for student let say B. Tech. Each student of that

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


college must have to pay tution fee. To do that in programming we are creating a class that is
EnggStudent as follow:

class EnggStudent{
int tutionFee;

EnggStudent(int tutionFee){
[Link] = tutionFee;
}

int getFee(){
return tutionFee;
}
}
Also college provide bus facility and hostel facility for students. Student either take bus facility or
hostel facility. To do so we have created subclass of EnggStudent that is
DayScholerEnggStudent, it represent a student that take bus facility.

class DayScholerEnggStudent extends EnggStudent{


int busFee;

DayScholerEnggStudent(int tutionFee, int busFee){


super(tutionFee);
[Link] = busFee;
}

int getFee(){
return (tutionFee + busFee);
}
}

To represent hosteler students we have created subclass of EnggStudent that is


HostelerEnggStudent.

class HostelerEnggStudent extends EnggStudent{


int hostelFee;

HostelerEnggStudent(int tutionFee, int hostelFee){


super(tutionFee);
[Link] = hostelFee;
}

int getFee(){
return (tutionFee + hostelFee);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}
}

and creating a class that contains main method (also known as main class).

class DmdDemo{
public static void main(String args[]){
EnggStudent es = new EnggStudent(55000);
HostelerEnggStudent hes = new HostelerEnggStudent(55000,42000);
DayScholerEnggStudent des = new DayScholerEnggStudent(55000,13200);

[Link]("Total fee of an engineering student without any facility is " +


[Link]());
[Link]("Total fee of an engineering student with hostel is " +
[Link]());
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());

es = hes;
[Link]("Total fee of an engineering student with hostel is " +
[Link]());
es = des;
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());
}
}

compiling and running that program produces output

Total fee of an engineering student is 55000


Total fee of an engineering student with hostel is 97000
Total fee of an engineering student with bus facility is 68200
Total fee of an engineering student with hostel is 97000
Total fee of an engineering student with bus facility is 68200

Now college have decided to conduct certification courses for III year students and let student to
join that course by their choice. For sake of simplicity we are created another subclass of
EnggStudent that is CertifiedEnggStudent as follow.

class CertifiedEnggStudent extends EnggStudent{


int certificationFee;

CertifiedEnggStudent(int tutionFee, int certificationFee){


super(tutionFee);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link] = certificationFee;
}

int getFee(){
return (tutionFee + certificationFee);
}
}

and we have make changes in main class

class DmdDemo{
public static void main(String args[]){
EnggStudent es = new EnggStudent(55000);
HostelerEnggStudent hes = new HostelerEnggStudent(55000,42000);
DayScholerEnggStudent des = new DayScholerEnggStudent(55000,13200);
CertifiedEnggStudent ces = new CertifiedEnggStudent(55000,6000);

[Link]("Total fee of an engineering student is " + [Link]());


[Link]("Total fee of an engineering student with hostel is " +
[Link]());
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());
[Link]("Total fee of an engineering student with certification course is
" + [Link]());

es = hes;
[Link]("Total fee of an engineering student with hostel is " +
[Link]());
es = des;
[Link]("Total fee of an engineering student with bus facility is " +
[Link]());
es = ces;
[Link]("Total fee of an engineering student with certification course is
" + [Link]());
}
}

Now one interesting thing to note here is that to run that program we just have to compile files
that contain CertifiedEnggStudent class and main class that is DmdDemo. We dont have to
make any alteration and compiling previosly written classes that are DayScholerEnggStudent,
EnggStudent and HostelerEnggStudent. That is main advantange of Dynamic method dispatch.

Output of code given above is:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Total fee of an engineering student is 55000
Total fee of an engineering student with hostel is 97000
Total fee of an engineering student with bus facility is 68200
Total fee of an engineering student with certification course is 61000
Total fee of an engineering student with hostel is 97000
Total fee of an engineering student with bus facility is 68200
Total fee of an engineering student with certification course is 61000

With the help of method overriding we can allow a subclass to define a general interface and its
implementation at its own level that is common to its all derivatives, along with allowing
derivatives to create their specific implemented. Thus in simple words we can say method
overriding allow us to implement 'Single interface, multiple methods' aspect of polymorphism.

Abstract classes:
Sometime we find our self in situation when it is not possible for a superclass to provide a
meaningful implementation of a method or simply we can say that subclasses want to fulfill a
similar a role in different ways through different implementation. One way to handle such
situation is to provide a meaning less implementation of a method in superclass and let
subclasses to implement them according to their own need, that approach is simply helpful in
debugging but not a very useful solution in case of deployment. Another approach to handle
such situation is creating abstract methods. An abstract method is a method whose
implementation is not provided in superclass just declaration is provided and subclass of that
class must provide implementation of abstract method.
general form of abstract method is:

abstract method-name(parameter-list);

An class that contains abstract method must be declared as abstract. To declare a class
abstract simply place abstract keyword before class declaration. Although it is possible that an
abstract class have some methods with implementation. An abstract class can not be
instantiated i.e. it is not possible to create an object of that class using new keyword. Although it
is possible to create a reference of an abstract class. Any class that extends an abstract class
must implement all abstract method of its superclass or becomes abstract itself.

An Example:

abstract class A {
abstract void abstractMethod();

void concreteMethod(){
[Link]("I am inside concreteMethod of class A");
}
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class B extends A{
void abstractMethod(){
[Link]("I am inside concrete implementation of abstractMethod in
class B");
}
}

abstract class C extends A{


/*
* no implementation is provided for abstractMethod
* hence that class C must be abstract
*/

void anotherConcreteMethod(){
[Link]("I am inside anotherConcreteMethod of C");
}
}

class AbstractDemo {
public static void main(String[] args) {
//error unable to instantiate class A because it is abstract
//A a = new A();

//okay to create a reference


A a;
a = new B();

[Link]();
[Link]();
}
}

Output of code given above is:

I am inside concrete implementation of abstractMethod in class B


I am inside concreteMethod of class A

In the code that we have given above we have created reference of class A and that reference
is able to point object of class B because superclass reference variable can point to child class
object. With that approach java implements run time polymorphism.

A real Time Example of Abstract class:


Consider an example of two dimensional shape, a two dimensional object have height and
width. but it is impossible to have a generic formula that provides area of a two dimensional

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


shape. every two dimensional shape have its own formula to calculate area. It is better to
declare area as an abstract method in its class and let its subclass to implement that method.

abstract class Figure {


double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

// area is now an abstract method


abstract double area();
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}

// override area for rectangle


double area() {
[Link]("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

// override area for right triangle


double area() {
[Link]("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Triangle t = new Triangle(10, 8);

Figure figref; // this is OK, no object is created

figref = r;
[Link]("Area is " + [Link]());
figref = t;
[Link]("Area is " + [Link]());
}
}

Output of code given above is:

Inside Area for Rectangle.


Area is 45.0
Inside Area for Triangle.
Area is 40.0

final Qualifier and inheritance:


In previous chapter we have used final keyword to create named constant, Apart from that final
qualifier have two more use that are as follows.

Using final to Prevent Overriding:


To disallow a method from being overridden simply specify final as a modifier at the start of
declaration. Method declared as final cannot be overridden doing so will result an error.

An Example:
class A{
final void unOverRided(){
[Link]("I am final, don’t override me");
}
}
class B extends A{
void unOverRided(){
[Link]("I am final, don’t override me");
}
}

class UnOverRidingDemo{
public static void main(String args[]){
A a = new A();
[Link]();

a = new B();

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]();
}
}

Compiling that program using command javac [Link] will report an error.

Some points about final methods


1. final methods cannot be overridden hence call to such method can be resolved at
compile time that limits overhead on JVM and provide a slight performance boost.
2. Compiler is free to inline call such methods because compiler knows is they can not be
overridden and small final method calls are replaced with their code by java compiler to
avoid costly overhead associated with them.

Using final to Prevent Inheritance:


Sometime you to want prevent a class from being superclass of another. To do so simply
precede their declaration with final. Declaring a class final make all its method final. It is easy to
say that no class can be declared as final as well as abstract because an abstract class is not
complete in itself, it relies on its subclass while preceding their declaration with final prevent
creating its subclass.

An Example:
final class NoSubClass{
int i;
NoSubClass(){
i = 10;
}
}

class SubClass extends NoSubClass{ //error

Unit-X
packages & Interfaces
Packages:
Consider a scenario in which a large number of programmers are working on a project and they
are getting run out of meaningful names because they are putting all their classes in common
namespace. Also all code is accessible for everyone that may cause accidental alteration.

To avoid such situations packages are the provided in java to:

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Managing namespace:
To group related classes & avoid name collision. Simply we can say that packages are
container for class that is used to keep class name space [Link] are
mechanism for partitioning the class name space into more manageable chunks. A package is
simply naming management mechanism.

Provide Visibility Control:


With the help of packages a programmer can make their own code isolated from other
programmers, packages provide ability to control visibility of class i.e. a programmer may keep
a certain set of classes private to their own package, a certain set of classes that are visible
outside packages to everywhere and a certain class members that are accessible to subclasses
defined outside the packages.

Creating a package:
Simply one thing that we have to understand is, To create a package we must create a folder, or
folder for an operating system is equivalent to packages for JVM.

To put a class in a packages simply put following statement before starting of class

package pkgname;

Here pkgname is placeholder for package name. for any class to be part of a package its .class
file must be stored in directory having name as pkgname. pkgname is case significant, folder
name is same as pkgname. A package may have many classes.

Java allow to create a hierarchy of packages. To do so separate packages names with .(dot).
general form of package hierarchy is

package pkg1.[pkg2.[pkg3]];

Locating packages and setting CLASSPATH:


As we have already discussed in previous section that packages for java are equivalent to folder
for an operating System. Now A key question arises here How do we let our JVM know about
location of package. There are two possible answers :

1. By default JVM looks for a package inside current working directory.


2. We can set environment variable CLASSPATH that contains location of package.

An Example:
Create a folder with name mypack then create a file [Link] inside mypack. Now
type following statement

package mypack;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


in [Link], It must be first statement inside the file. That statement make
[Link] part of mypack. Then simply write program.

package mypack;

class PackageDemo{
public static void main(String args[]){
[Link]("A short Example of package");
}
}

To compile that program simply move inside mypack directory from terminal and type
javac [Link]

Now first method to run that program is let JVM look for mypack in current directory. To do so
simply move to parent directory of mypack and type fully qualified name of class. Fully qualified
name contains package name and classname separated by dot.
java [Link] emo

In that method we must be in parent directory of package. To run that program from other
location we have to set CLASSPATH environment variable. To do so simply type following
command on terminal
set CLASSPATH=absolute path of package’s parent directory (Inclusive)

Now we can run our java program from any location of computer because JVM read location of
package from CLASSPATH environment variable.

Access Control & Packages:


So far we have study about just one access modifier that is private, methods and variables that
are declared as private are accessible only in their own class. A class contains data and code
while a package contains class and other subordinate packages. Java packages provide a fine
control over visibility of classes. To do so three more access modifiers are provided. that are
protected, public and no modifier. Anything that we want to make visible everywhere (inside as
well as outside package) must be declared as public. Anything that we want to make visible
outside package but only in subclasses must be declared as protected. If a method or variable
is not preceded with any access modifier (i.e. no modifier), it should be visible in its own
package no matter accessing class is subclass or not. That is default access level and also
known as package-private. All that details can be summarized in table given below.

Private No Modifier Protected Public

Same class Yes Yes Yes Yes

Same package No Yes Yes Yes

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


subclass

Same package No Yes Yes Yes


Non-subclass

Different package No No Yes Yes


subclass

Different package No No No Yes


Non-subclass

Importing packages
There are two ways so that you can use the public classes stored in package.
1. Using the fully-qualified class name to access class. To create an object of class (say A)
that is stored in a package (say mypack) we will simply write
mypack.A obj-name = new mypack.A([actual-arguments]);

2. Using import keyword: Using fully-qualified name each time requires a lot of typing, To
save a programmer from that, java provides import keyword. import keyword allow to
include entire package or specific class(es) of a package in program. After importing
them no need to use fully-qualified name. General form of import statement is
import package-name.[subpackage-name].(classname|*);

using * tells compiler to add all members of packages. While only if a small number of
classes are required then it is better to import them by their names.

Importing a large number of packages with * may increase compilation time of a


program. It is good practice to import classes according to requirement rather than
importing entire package. Although importing packages with * do not affect run time
performance.

An Example:
//Filename: [Link], Folder: p1

package p1;
public class A{
private int privateVar;
int packagePrivate;//no modifier is here
protected int protectedVar;
public int publicVar;

public A(){
privateVar = 10;
packagePrivate = 20;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


protectedVar = 30;
publicVar = 40;
}
}

//Filename: [Link], Folder: p1

package p1;
class B extends A{
B(){
[Link]("Inside class B");
//[Link]("privateVar is " + privateVar);
[Link]("packagePrivate is " + packagePrivate);
[Link]("protectedVar is " + protectedVar);
[Link]("publicVar is " + publicVar);
}
}

//Filename: [Link], Folder: p1

package p1;
class C{
C(){
A aObj = new A();
[Link]("\nInside class C");
//[Link]("privateVar is " + [Link]);
[Link]("packagePrivate is " + [Link]);
[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
}
}

//Filename: [Link], Folder: p1

package p1;
class Demo{
public static void main(String args[]){
B bObj = new B();
C cObj = new C();
}
}

//Filename: [Link], Folder: p2

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


package p2;
public class A{
public A(){
[Link](“Inside class A of package p2”);
}
}

//Filename [Link], Folder: p2

package p2;
class D extends p1.A{
D(){
[Link]("Inside class D");
//[Link]("privateVar is " + privateVar);
//[Link]("packagePrivate is " + packagePrivate);
[Link]("protectedVar is " + protectedVar);
[Link]("publicVar is " + publicVar);
}
}

//Filename: [Link], Folder: p2

package p2;
import p1.A;
class E{
E(){
A aObj = new A();
[Link]("\nInside class E");
//[Link]("privateVar is " + [Link]);
//[Link]("packagePrivate is " + [Link]);
//[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
}
}

//Filename: [Link], Folder: p2

package p2;
class Demo{
public static void main(String args[]){
D dObj = new D();
E eObj = new E();
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

//Filename: [Link], Folder: p3

package p3;
import p2.*;
import p1.*;
class F{
public static void main(String args[]){
p1.A aObj1 = new p1.A();
[Link]("Inside class F");
//[Link]("privateVar is " + [Link]);
//[Link]("packagePrivate is " + [Link]);
//[Link]("protectedVar is " + [Link]);
[Link]("publicVar is " + [Link]);
p2.A aObj2 = new p2.A();
}
}

Let say we have placed all three folder p1,p2 & p3 in a common folder (say mypack). To
compile all classes of p1, open terminal and go inside p1 directory then write
javac *.java

Now to compile classes of folder p2 simply move inside p2 directory from terminal. if we directly
use command
javac *.java
then compiler will report us errors because it does not found classes of p1. By default compiler
looks for classes of p1 in current directory that is p2. To let compiler know about correct location
of p1 we have to set CLASSPATH.

To set CLASSPATH On Windows simply write


set CLASSPATH=absolute path of package’s parent directory

To view currently setted path simply write


set CLASSPATH

To restore default path


set CLASSPATH=

To set CLASSPATH on Ubuntu simply write:


export CLASSPATH=absolute path of package’s parent directory

To view currently setted path simply write


echo $CLASSPATH

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


To restore default path
unset CLASSPATH

Similarly compile classes of p3 & we can run that program by using fully qualified name of main
class(es).

Interfaces:
Interfaces are similar to classes but all methods defined inside interface are abstract method i.e.
they are lacking body. Other than methods, an interface can only have static final members.
Similar to abstract class it is not permitted to create an object of an interface but it is okay to
create reference of an interface.

Interface allow us to create a standard and public way of specifying the behavior of a
class. An interface specify what a class must do regardless how to do it. In simple words we can
say that an interface allow us to define contract and hide implementation, thus we can say
interface support encapsulation. Interface allow to change implementation without affecting
contract to caller.

Interfaces support dynamic method dispatch. With the help of interface caller does not need
implementation at compile time It only need interface, because object association is made to
interface at run time.

If a class implements an interface, it has to implement all methods of that interface. A single
class can implements any number of interfaces and a single interface can be implemented by
any number of classes. If a class implements an interface but fails to define all method of
interface, then class must be declared as abstract class.

Defining an Interface:
General form of interface is
access-specifier interface interface-name{
static final data-type var-name1 = value;
static final data-type var-name2 = value;
.
.
static final data-type var-nameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
.
.
return-type method-nameN(parameter-list);
}

Only two access specifiers are allowed, no-modifier or public. if interface do not have any

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


access specifier then it will be visible only to its package but if an interface is declared with
public all variables and methods of it implicitly become public. interface-name is name of
interface between access specifiers and interface-name there is interface keyword. all variables
declared inside interface are by default static and final although it is allowed to precede their
declaration with these keywords. All methods declared inside interface do not have body they
are just followed by semicolon.

Implementing an Interface:
To implement an interface, a class should include implements clause in class definition, and
provide implementation of all methods that are defined in a interface. General form of a class
implementing an interface is:
access class class-name [extends superclass] implements interface-name1 [,interface-
name2 [,..]] {
//class body with all methods body of interface(s)
}

Here access is either public or default. It is perfectly okay for a class to implement more than
one interface. To do so, just separate interfaces with comma. Implementing more than one
interface provide facility of multiple inheritance. Signature of methods in interfaces and in its
implementing class must be same.

One important Point:


Whenever a class implements a method of an interface. It must have public access specifier in
implementing class.

An Example:
interface Demo {
int getValue();
}

class A implements Demo {


int i;

A() {
i = 20;
}

public int getValue() {


return i;
}

int returnSquare() {
return (i*i);
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public static void main(String args[]) {
A a = new A();
[Link](“Class A implements Demo interface”);
[Link](“Value of i is ” + [Link]());
[Link](“Square of i is ” + [Link]());
}
}

Output of code given above is:

Class A implements Demo interface


Value of i is 20
Square of i is 400

In the example given above we have create an interface named as Demo and a class named A
that implement interface Demo and provide implementation of method getValue. class A have
one more methods that is returnSquare(). It is allowed for a class that implement interface(s) to
have their own members.

Dynamic Method dispatch and Interfaces:


Whenever we are creating a new interface, we are creating a new reference type. It is perfectly
acceptable to create a reference of an interface, but instantiating an interface is not allowed. As
we have already discussed that a super class reference variable can point to child class object
same apply for interfaces and its implementing classes. A reference of an interface can point to
an object of its implementing class, Whenever method of an interface is called with the help of a
reference variable, then calling is performed on the basis of object pointed by reference. Thus
decision of calling a correct version of method is taken at run time. It allow classes to be created
later than the code which calls method of that class.

An Example:
interface Demo {
int getValue();
}

class A implements Demo {


int i;

A() {
i = 20;
}

public int getValue() {


return i;

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


}

int returnSquare() {
return (i*i);
}
}

class B implements Demo{


int j;

B(){
j = 40;
}

public int getValue() {


return j;
}

int returnCube(){
return (j*j*j);
}
}

class C{
public static void main(String args[]) {
Demo a = new A();
[Link]("Class A implements Demo interface");
[Link]("Value of i is " + [Link]());
A aobj = new A();
[Link]("square is " + [Link]() + "\n");

Demo b = new B();


[Link]("Class B implements Demo interface");
[Link]("Value of i is " + [Link]());
B bobj = new B();
[Link]("square is " + [Link]());
}
}

Output of code given above is:

Class A implements Demo interface


Value of i is 20
square is 400

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Class B implements Demo interface
Value of i is 40
square is 64000

In the example given above we have created one more class B that implements interface Demo.
In class C we have created reference variables of interface Demo and that variable is pointing to
object of class A. When we are calling methods of getValue() then implementation of class A get
executed similarly another reference variable of interface that is b, is pointing to object of class
B when calling method getValue() from that, implementation of class B is executed. decision of
calling correct version is taken at run time. Thus Interfaces helps to implement run-time
polymorphism in java. Although reference variable of interface do not have any knowledge of
additional members of its implementing class. To access additional members of class we can
not use reference variables of interface, we have to create object of implementing class with
reference of same.

Partial Implementation of an interface:


If a class implements an interface but fail to provide implementation of each method of
implementing interface then it must be declared as interface.

An Example:
interface Demo{
void getValue();
}

abstract class Incomplete{


int i;

Incomplete(){
i = 10;
}

void show(){
[Link](“i is ” + i);
}
}

Variables in interfaces:
Let say we have created an interface that has no methods in it but it has some variables with
initial values. All variables in an interface are static and final, if such interface is implemented by
several classes then all these variables will be available to all classes. Because interface do not
have any methods hence implementing class does not bother to implement anything. Creating
such interfaces are similar to create a header file with constants in C/C++.

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


An Example:
interface Demo{
boolean YES = true;
boolean NO = false;
}

class A implements Demo{


int i;

A(int i){
this.i = i;
}

boolean isNumberPositive(){
if(i > 0){
return YES;
}
return NO;
}
}

class B implements Demo{


int i;

B(int i){
this.i = i;
}

boolean isNumberNegative(){
if(i < 0){
return YES;
}
return NO;
}
}

class C{
public static void main(String a[]){
A adi = new A(-10);
B bdi = new B(-10);

[Link]("Do class A have positive number? " +


[Link]());
[Link]("Do class B have negative number? " +

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


[Link]());
}
}

Output of code given above is:

Do class A have positive number? false


Do class B have negative number? true

Interfaces and inheritance:


Just like one class can inherit another class using extends keyword, an interface can also
inherits another interface. According to rule of inheritance if an interface inherits another
interface then child interface have all methods and variables of parent interface. If a class
implements child interface then it must provide implementation for both interfaces’ method.

An Example:
interface Constant{
boolean YES = true;
boolean NO = false;
}

interface A{
boolean isGreater();
}

interface B{
boolean isLesser();
}

interface C extends A,B,Constant{


boolean isEqual();
}

class D implements C{
static int i, j;

D(int ii, int jj){


i = ii;
j = jj;
}

public boolean isGreater(){


return ( i > j ? YES : NO);
}

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


public boolean isLesser(){
return ( i < j ? YES : NO);
}

public boolean isEqual(){


return ( i == j ? YES : NO);
}

public static void main(String args[]){


C cobj = new D(20,30);
[Link]("i is greater than j? " + [Link]());
[Link]("i is smaller than j? " + [Link]());
[Link]("i is equal to j? " + [Link]());
}
}

Output of code given above is:

i is greater than j? false


i is smaller than j? true
i is equal to j? false

From example given above interface C inherits A,B and Constant. Interfaces supports multiple
inheritance means one interface can inherits more than one interface at a time.

One important point:


Interface allow a two unrelated class to implement common behaviors because they are
independent to any class or defined independently. Also interfaces provides flexibility to add
functionality later on according to requirement without tempering existing code.

Nested classes:
So far we have learned about classes that are defined directly within a package. such classes
are also known as top level classes. Java provides us facility to define classes inside another
class, such classes that are defined inside another are called nested classes. Let say we have a
class A, that is defined directly inside a package and we have another class B that is defined
inside class A. class B is simply known as nested class and class A is known as enclosing
class. class B can access all members of class A but class A does not have any knowledge
about class B.

Nested classes in java can be defined as classified into following types.

static nested classes:


A nested class that have static modifier applied to it. Such classes need to create object of outer

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


class to access members of encapsulating class because they have static qualifier. static
nested classes are rarely used.

Non-static nested class:


Non-static inner classes can be further classified as follow:

Inner class:
Inner classes are defined inside another class but do not have static modifier with it. Such
classes have access to all members of their encapsulating class and they don’t need object for
accessing. Such classes are specific to each object.

Local class:
These are the classes that are defined a block of a class. Similar to a local variable, such
classes are local to block hence they are not visible outside their block. A local can access all
parameters and local variables of its block only if they are declared final.

An Example:
package p2;

class A{ // top level class of package p2


int i = 1;
static int j = 0;

class B{ //Nested Class


int m = 12;
int n = 13;

void showVar(){
[Link]();
[Link]("Inside inner class");
[Link]("i is " + i);
[Link]("j is " + j);
[Link]("m is " + m);
}
}

void showijn(){
[Link]("Inside top-level class");
[Link]("i is " + i);
[Link]("j is " + j);
//[Link]("n is " + n);
}

void localMethod(){

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


B b = new B();
[Link]();
int k = 0;
final int l = 10;

class C{ // local class


void prinrVars(){
[Link]();
[Link]("Inside local class");
[Link]("i is " + i);
[Link]("j is " + j);
[Link]("l is " + l);
//[Link]("k is " + k);
}
}

C c =new C();
[Link]();
}
}

class D{
public static void main(String args[]){
A a = new A();
[Link]();
[Link]();

[Link]();
[Link]("Creating inner class object");

A.B b1 = [Link] B();


[Link]();
}
}

Output of code given above is:

Inside top-level class


i is 1
j is 0

Inside inner class


i is 1
j is 0

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


m is 12

Inside local class


i is 1
j is 0
l is 10

Creating inner class object

Inside inner class


i is 1
j is 0
m is 12

in the code segment we have placed so many java code in single line comments, removing
commenting from these code will produce compile time errors.

We have also created object of inner class B in main method. General from of doing so is:
OuterClass outerClass = new OuterClass();
[Link] innerClass = [Link] InnerClass();

Another type of local class is anonymous class, these are classes that are defined inside a
block but do not have any name. we will discuss about them later.

Creating Jar file:


JAR (Java ARchive) is an archive file format that is used to combine many Java class files and
associated other file (text, images etc) into one file. Such file format are easier to deploy.

General syntax for creating a jar file is


jar cf jar-file-name input-file(s)

Here
● c indicates that we want to create a jar file.
● f indicate that output will go to a file rather then to a console.
● jar-file-name is the name of resulting file, by convention jar-file-name should have .jar
extension but it is not mandatory.
● input-file(s) is a space separated list of files that we want to add in directory. To add all
files of directory we can pass * as an arguments.

other arguments that can be passed along with cf are

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


Options Description

v Produces verbose output on standard output stream while the jar file
is being built. It tells name of file that are added to jar.

0 (zero) Produces uncompressed jar file

M Indicate that default manifest should not be produced

m Used to include manifest information from existing file. To do so


command will be
jar cmf manifest-file jar-file-name input-file(s)

-C To change directory during execution of a command

An example
Consider package p1 that we have discussed in example of packages. To create a jar file and
run our program with jar file we have to JVM know about main class. To do so we have to
create a file name as mainClass (without any extension, in parent directory of p1) and put
following content in it
Main-Class: [Link] (with a carriage return)

after doing so simply run following command


jar cmf mainClass [Link] p1

To view content of [Link] simply run following command


jar tf [Link]

When we create a JAR file, it automatically receives a default manifest file. There can be only
one manifest file in an archive, and it always has the pathname
META-INF/[Link]

When we create a JAR file, the default manifest file simply contains the following:
Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)

These lines show that a manifest's entries take the form of "header: value" pairs. The name of a
header is separated from its value by a colon. The default manifest conforms to version 1.0 of
the manifest specification and was created by the 1.6.0 version of the JDK

To run program from jar file simply write


java -jar [Link]

Output of command given above will be


Inside class B
packagePrivate is 20

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]


protectedVar is 30
publicVar is 40

Inside class C
packagePrivate is 20
protectedVar is 30
publicVar is 40

To extract a jar file simply


jar xf jar-file-name

Notes By: Er. Agrawal || Ph: +91-9983412349 || E-mail: agrawalsaysjava@[Link]

You might also like