0% found this document useful (0 votes)
9 views72 pages

Java Notes

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

Java Notes

java notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 72

PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),

IN JAVA UNIT I Assistant Professor of CSE, MJCET


1

History of Java

Before learning about Java, first let us know the history of Java. Before 1990,
Sun Microsystems use to maintain two departments, the first department
was known as Sunsoft which was used to deal only with the development of
new software and the other department use to deal with development of
hardware components like processors. The processor developed by Sun is
known as Spark processor. This processor is based on an architechture
known as RISC architechture.
In the year 1990, Sun Microsystems received a software
project by name Green Project (some books say as Stealth project)
from some client. The purpose of this project was to develop software for
consumer electronic devices like televisions, refrigerators, toasters,
microwave ovens, washing machines etc. As we already know that
developing software consists of many stages or phases i.e. Analysis,
Design, Coding, Testing and Maintenance. The job of coding the software
was given to James Gosling. At that time, the languages used to develop
softwares was C and C++. But James Gosling knew that C, C++ comes under
system dependent languages category i.e. he has to develop different
softwares for different electronic devices. In other words, for refrigerators
there was be separate software, for washing machine there was be separate
software, for ovens there was be separate software i.e. for different
electronic devices there must exists different softwares. Then he thought
that there is a need to develop a new language that can solve the problem of
system dependency.
So, he started to develop a new language, which was initially
known as Oak (It is the name of the tallest tree in America. It is said that
there was an Oak tree, in the cottage where James started developing a new
language). Later the name changed to Java. This language could
successfully solve the problem of system dependency. Here we can conclude
that Java was introduced to develop software that can run on any electronic
device. It is said that Java was introduced in the year 1991 by James Gosling,
but was announced to public in the year 1995 in a conference. In the
year 1996, the first version of Java i.e. JDK 1.0 was released.
During 1990s, Internet and World Wide Web became popular
because they can be accessible from any computer. Then they started
thinking what will be the effect of Java on Internet. By keeping this in mind,

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
2

they were successful in making impact of Java on Internet. The various java
programs that can work on Internet were applets and servlets.

Creation of Java:

Before understanding the importance of Java to Internet, let us understand


the disadvantages of previous languages like C and C++ with respect to
Internet.
If user wants to write a program in C
language, then the extension of the file will be .c that is if the name of the
program is add, then the name of the file is add.c . This means add.c is a
program, that contains source code of add program written in C Language.
When we compile this program, then a file by name add.obj is created. This
file add.obj contains an intermediary code known as object code. When we
execute this object code, then we will get a file known as add.exe that
contains executable code and this code contains machine code which is
created based on the Instruction Set of the CPU and the type of operating
system used in the computer on which the program was compiled. An
Instruction Set is defined as a group of instructions that are
understandable by the CPU that is, different processors will have different
Instruction Sets. So, the instructions recognized by the Pentium processor
will not be understandable by the Celeron processor and vice versa.
Similarly, the instructions recognized by the Celeron processor will not be
understandable by the Spark processor.
In other words, it means that the executable code is totally
dependent on the nature of hardware and the operating system present in
the computer. It means that the executable file(here add.exe) is platform
dependent. If user takes this executable file, and runs on a system that has
same hardware and different operating system, then it does not get
executed. Moreover this file does not get executed on a system that has
different hardware and different operating system or different hardware and
same operating system. To be more specific, this file will be executed only
on that system that is having same hardware and same operating system as
the computer on which it was compiled.
To be more general, if user develops a program and
compiles a program on X processor and Y operating system, then the
program can successfully gets executed on a computer with X processor and
Y operating system only. In other words, if the processor is changed and the

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
3

operating system is changed then the above code never gets executed.
These programs are known as system dependent programs or platform
dependent programs. Hence C and C++ are known as system dependent
languages or platform dependent languages.

Now let’s understand the impact of C and C++


programming languages on Internet. An Internet is defined as collection of
many computers spread all around the globe. It means that the computers
that spread all around the globe have different operating system and
different processors. So, if we develop a software on C or C++, and if we
give the .exe file of the software, then this file cannot run on other system
that have different processor and different operating system, due to the code
being system dependent. So, it is not advisable to develop software in C and
C++ for Internet. It means that we need a language, whose code is platform
independent or system independent and that can run on any system present
on the Internet. Then they introduced a language known as Java that
could overcome the disadvantages of previous languages like C and C++.
If user wants to write a program in Java
language, then the extension of the file will be .java that is if the name of the
program is add, then the name of the file is add.java . This means add.java
is a program, that contains source code of add program written in Java
Language. If user compiles this program, then a file by name add.class gets
generated. This file contains a code known as byte code. This is known as
byte code, because in this code the size of each instruction is 1 byte i.e. 8
bits. It is important to know that the byte code is totally different from
machine code. A machine code is a code that can be understandable by the
CPU. In other words, the byte code that is generated by the Java Compiler
cannot be understandable to the microprocessor. When it is not
understandable by the microprocessor then where is the question of being
executed. Then they introduced a program known as JVM.
JVM stands for Java Virtual Machine. JVM is defined as a system program,
whose job is to convert the byte code into machine code. In other words, the
job of JVM is to convert byte code into understandable machine code so that
it can be easily understandable by the CPU. This machine code is taken by
the CPU that will execute it and displays the result. This paragraph explains
us that how a java program gets compiled and how it gets executed.
Now, lets us understand the importance of Java on
Internet. JVM is a system program that is different for different operating

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
4

system. In other words, the JVM working for Windows operating system is
different from the JVM working for Linux operating system. As we know that
whenever user compiles a java program, it generates a code known as byte
code. This code is system independent or platform independent. A byte code
that is generated on a computer that is having windows operating system
and Pentium processor can run on a computer that is having Sun Solaris
operating system and Spark processor. In other words, a byte code
generated on one computer having X operating system and Y hardware can
run on a computer that is having Y operating system and X hardware. To be
more specific, a byte code generated on a computer that is having any
operating system and any processor can run on a computer that is having
any operating system and any hardware. This concept made Java to be
known as Platform Independent Language.
If we consider an Internet, that contains millions
of computers having different operating system and different processors and
if we want to run the java byte code, then user can expect same result on all
the systems. If user wants to develop a software using Java programming
language, and wants to send this software to some other person in some
other part of world, then the user can just send .class file containing of byte
code and that person can download this file( .class file) from internet and can
execute this file without any problem. Hence we can conclude that java is
suitable for developing software on the internet.

Importance of Java to Internet:


Due to rise of Internet and World Wide Web, Java introduced a new type of
programs known as Applets and Servlets. Moreover Java also addressed
some strong issues associated with Internet like Security and Portability.

Applets:

An Applet is defined as a java program that is designed to be transmitted


over the Internet and can execute on a web browser. The job of this program
is to display the data that is provided by the Server.

Servlets:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
5

Servlets are defined as a java program that gets executed on the server side
of the Web Connection.

Byte Code:

A byte code is defined as a code that gets generated when a java program
gets compiled. In other words, whenever user wants to compile a program
with the help of a system program known as Java Compiler, then its job is to
convert the java source code into byte code. This code is named as byte
code, because the size of each instruction is 1 byte that is equal to 8 bits.
Practically, this byte code is present in a file known as .class file. This code
that is being generated neither depends on the operating system nor on the
processor that is present in the computer, on which the program was
compiled. This byte code can be executed on any computer that is having
different operating system and different processor. JVM software for Windows
operating system is different from the JVM software for Linux operating
system that is different from the JVM software for Sun Solaris operating
system. This new concept of byte code made Java famous to be known as a
Platform Independent Language. The below diagram shows how a byte
code gets generated.

Java Buzzwords or Features of Java:

When James Gosling developed Java, he kept a conference in his company


Sunsoft, now known as Sun Microsystems and introduced a new language
Java by saying the features of Java to the employees of the company and
then later to the world. The various features of Java are:

1. Simple
2. Object Oriented
3. Secure
4. Portable

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
6

5. Interpreted
6. Architechture Neutral
7. Multithreaded
8. Distributed
9. Dynamic
10. High Performance

The above features that made Java as a popular language are explained
below:

Java is Simple

For a learner or a programmer the most difficult concepts in C and C++ are
pointers, structures, unions. Pointers are useful in some applications, but if
they are not used properly they result in unpredictable and undetectable
results. The most confusing concepts in C++ is operator overloading. Hence
Java has removed all complex issues making it more simple. Moreover Java
was designed to be easy for the professional programmers so that they can
learn and can use it efficiently. If a person is very good at C++, then learning
Java becomes very easy i.e. at that time when Java was introduced, many
programmers were working with C++.

Java is Object Oriented


Much of the syntax of Java is based on the earlier object oriented language
like C++. Moreover the language Java is founded over the Object Oriented
Paradigm. It is said that Java is more Object Oriented than C++, because
variables and the methods never exists outside the boundary of the class.

Java is Interpreted

Java is said to be Interpreted i.e. java programs are compiled into a code
known as byte code for an imaginary machine known as virtual machine. Any
machine that supports java programs provides a simulator known as
interpreter that could read byte code and convert it into machine code and
then execute them to give output. This interpreter is known as Java Virtual
Machine. So the job of JVM is to convert byte code to machine code and then
to execute this machine code to give output. So, by doing this the
performance of Java gets degraded i.e. it leads to slower execution.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
7

Recent innovations in the java world, lead to increase in the


performance of interpreters by introducing a system program with in JVM.
This system program is known as JIT Compiler i.e. Just-In-Time Compiler.
The job of JIT Compiler is to convert the byte code into machine code and
relieving the JVM from doing this job.

Java is Robust

Java is said to be Robust, because java programs never crash if there are any
software and hardware errors. The reason is that Java follows exception
handling. A java program has some statements and if these statements lead
to some error like division by zero, file operation that can attempt to read
data from non-existent source, then it will generate an exception instead of
performing an erroneous operation.
Another reason why Java is said to be robust, is automatic
memory management. In case of C and C++, it is the responsibility of the
programmer to write the functions in their programs that are used to release
the memory that was used by the variables and object of the program. But in
case of Java, the programmer need not feel burden of releasing the memory
but it is the responsibility of a special program known as Garbage Collector
is to detect and release the memory that is no longer used by the currently
running program.
The above two features Exceptional Handling and use of
Garbage Collector simplifies the programmer’s task and makes programs
more reliable.

Java is Architechture Neutral

As we know, that the byte code generated by the Java Compiler, is neither
dependent on the computer architechture of the system (where it was
generated) nor the operating system of the computer. Computer
Architechture means the various components of the computer are connected
to each other. In some books, architechture is nothing but the processor and
the other components of the computer connected to each other to work with
each other to perform a simple task. The processors can be Intel, AMD or
Spark.
With this feature, there is a famous
saying on Java: “write once, run anywhere, any time, forever”.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
8

Java is Multithreaded

Java was the first programming language that introduced the concept of
multithreaded i.e. they can be multiple threads in a single program so that
they can perform many things simultaneously. Creating multiple threads, is
known as multithreading.

Java is Distributed

Java is said to be distributed because of a feature known as RMI (Remote


Method Invocation). If this feature is there, then we can access the files of a
remote system on our local system, and making user to feel that the user is
working on a local system. These features were also provided by previous
languages like C and C++, but Java made it more easy.

Java is Portable
If a Java program gives same results on any machine regardless of the type
of operating system and the type of computer architechture, then it is said to
be portable.

Java is Dynamic

Before Java, people used to write web pages with the help of HTML. But
viewing, data with the help of HTML gives an impression of static data
getting displayed on a web browser. But with the help of applets,
dynamically interacting programs with animations were made, on internet.

Java is High Performance

The problem with previous JVM was slow execution. This made java programs
low performance. To increase their performance, a system program by name
JIT Compiler was introduced in JVM that increased the performance of Java
and that made JIT Compiler and JVM to work together.

OOP Principles:

The three principles of Object Oriented Programming are:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
9

1. Encapsulation
2. Inheritance
3. Polymorphism

Encapsulation:

It is defined as a mechanism that associates the code and the data into a
single unit to and keeps them safe from external interference and misuse. In
other words, it is a wrapper that wraps code and data into one unit.
Practically, this is implemented with the help of a
construct known as a class. A class is defined as a template that has a
structure and behaviour that is shared by a group of objects. Each object of a
class contains structure and behaviour of a class i.e. why sometimes objects
are known as instance of a class. A class contains variables and methods.
These are known as members of the class. Variables of a class explains the
structure of a class, where as methods of a class explains the behaviour of a
class. In Java, they are known as methods where as in C and C++ they are
known as functions.
With the help of encapsulation we can protect the data present in
instance variables and method body. But this can be implemented with the
help of access specifiers. They are three access specifiers as shown below:
 public
 private
 protected

If a member of a class is declared as public , then object of any class can


access it. But if the member of a class is declared as private, then the object
of that class can only access i.e. objects of other class cannot access it. But,
if the member of the class is protected then the sub class object can only
access it. Member of a class include the variables and methods of that class.

Inheritance:

Inheritance is defined as a process in which one object acquires


characteristics and behaviour of another object. To understand clearly, let us
consider two objects like father and son. In normal world, we can see that

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
10

the features of a son are much similar of that his father. This concept is
known as Inheritance.
In Programming, the basic definition of
inheritance is Reusability. The concept of inheritance was first introduced by
a programming language known as Smalltalk. If Java is using inheritance
concept, then they are two types of classes i.e. sub class and super class. A
sub class is a more specialized versions of a class, which inherit attributes
and behaviors from their parent class. In other words, this sub class contains
attributes and behaviours of parent class and it has capability to define on its
own.
With in a class hierarchy, it is also possible for
subclasses to override any methods that they have inherited, and they can
create unique implementations for these methods. Moreover, if user wants to
change the body of a method in a sub class that is inherited from the super
class, then it is possible with the help of a concept known as “Method
Overriding”.

Polymorphism

Polymorphism is a Greek word that says “many forms”. Polymorphism is


defined as an ability of objects belonging to different data types to
respond to calls of methods of the same name, each one according to an
appropriate type-specific behavior. This concept can be implemented
either using Method Overloading or Method Overriding.

Introduction to Variable concept in Java:

A variable is defined as a storage area that is used to store data. Each and
every variable has a scope and a lifetime. Let us consider a small example. If
user is interested to write a program i.e. addition of two numbers, say 2 and
3. Then there is a necessity to store the above values. Here the variable
comes into being. We use variable to store this values i.e. 2 is stored in one
variable and 3 is stored in another variable.
If user wants to use a variable, while writing a java program, then it is
mandatory to declare that variable before it is used.

Declaring a Variable:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
11

Being a java programmer, if you want to say the operating system to reserve
some space in the main memory in order to store some data, then it is
possible with the help of a statement known as declaring a variable .The
syntax to declare a variable is

datatype identifier = value;

The datatype explains the type of data that can be stored in that memory
location. The identifier is defined as the rules that are used to name a
variable. To be more specific, identifier is the name that we use with in the
program that refers to that memory location where the data is stored.
Whenever user refers this identifier in the program, the operating system will
look up the memory address that corresponds the identifier and accesses the
memory address. This concept is known as resolving. Now the last part is
nothing but the right hand side of the assignment operator can be the value
or an expression.

Identifier

Identifier is nothing but some rules that define the name of a variable or a
class or an interface or a method or an array or an object. The name that the
programmer wants to select must represent the nature of data that is stored
in the corresponding memory location. The below are some restrictions that
must be applied while choosing an identifier:

1. An Identifier cannot begin with a number


2. An Identifier cannot contain spaces.
3. An Identifier must not be a keyword.

While using an identifier, it must be noted that it must be unique with in the
block where it is declared i.e. programmer cannot declare two variables with
same name within the same block otherwise it will lead to a compile time
error. However the programmer can declare same identifier in different
blocks.

Writing a java program

HelloWorld.java

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
12

Let's look into our first program. Save the following text into the file called
HelloWorld.java

class Hello

public static void main(String args[])

System.out.println("Hello World");

We examine that there is a class called Hello. Since Hello is the only class in
the file, it is called the main class. In order to make your program runnable,
you should have a function called main which is defined as:

public static void main(Strings[] args)

The explanation is as follows:

The public qualifier tells you that the function main is callable from outside.

Then the next qualifier is static. We will study about static in near future.

Then, void tells you that the function main returns nothing to the system.

Then the function's name, main.

Then String[] args denotes the argument passed into the program.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
13

Arguments are nothing but the options or switches you would mention when
invoking programs.

As in case of C language we use printf() and in case of C++ we use cout


statement, like wise in case of Java you can consider System.out.println as a
statement that is used to print some text on the screen. Note that the text
has to be surrounded by the double quotes. In this case, "Hello World!" is
being printed, without the quotes of course. Remember that almost every
command in Java ends with a semicolon(;).

NOTE:

The main class name has to be the same as the program file name.
Otherwise, your Java program won't compile. In this example the class name
is Hello. The program file has to be Hello.java. You have to pay attention
that this naming convention is CASE SENSITIVE it means that
naming your file into helloworld.java WON'T work.

How to Compile Java Program

If user wants to compile a java program, then it is possible with the help of a
command known as javac. This command internally calls Java Compiler,
which will create a new file that contains the byte code version of the
source code and the name of the file will be same as source code file with an
extension of .class .Don't forget to change the directory to the directory
where your Java program resides. Also, make sure that your JDK installation
is correct.

javac Hello.java

When the above program gets executed, they are two expectations. The first
is it produces a file called Hello.class, it means that your compilation is
successful. The second is gives compile time errors, if they exists with in the
program, then no .class file gets created. It must be noted that a .class
file gets created, if and only if they are no compile time errors.

How to Run Java Program

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
14

To run it, under Windows or UNIX, type the following:

java Hello

On writing the above line, it must be noted that there must be no .class
extension. When the above command gets executed, internally the java
command will call for JVM that will convert the byte code into suitable
machine instructions that can be understandable by the processor present in
the system on which the program is getting executed. After converting the
processor will act on that statements and then user can see output. Some
times if there is some error during execution or runtime, then instead of
displaying output, it displays user understandable messages known as
Exceptions.

NOTE:

In case of C and C++ programming languages, when a program gets


executed, a file by name .exe gets generated. But in case of Java, there is
no file by name .exe gets generated.

Commenting Your Program

It is said to be a good practice, if you write comments beside the source code
of the program. In real time industry, you cannot find software or program
without comments. Sometimes, it is useful to make some note about your
program. Not only making you clear about what's going on your program,
but also making others able to read your program based on the comments of
your program. The compiler will completely ignore your comment, however.
In Java, there are three ways of commenting:

Double slash comment.

Example:
// Put your comments here
After you put the double slash (//), everything else behind it is considered as
comment.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
15

Embracing comment.

Example:
/*
My comment is here
Neat huh?
*/
If your comment is pretty long, it is better to embrace it with /* and */.
Everything within it is considered as a comment.

Java doc comment.

It is similar to above, except:


/**
My comments here will be put into
documentation by Javadoc program
*/
It is embraced with /** and */. Notice the double star. Your comments within
it will be documented by the Javadoc program, an automatic documentation
maker from Java SDK package.

Type Conversion and Casting:

TypeCasting is defined as conversion of one data type into another datatype.


As we know, that they are two types of data types in Java. The first is known
as Fundamental or Primitive Data Type and the second is known as
Reference or Advanced Data Type. TypeCasting is only possible between
fundamental data types or between Advanced Datatypes. This is to made
sure, that TypeCasting is not possible between Fundamental and Advanced
Datatype and viceversa.

If programmer or developer wants to perform TypeCasting


between fundamental datatypes, then it is possible with the help of an
operator known as type-cast operator. And, if the developer wants to
perform, typecasting between Advanced Datatype then it is possible with the
help of a concept known as Wrapper Classes.(that is not in your syllabus)

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
16

TypeCasting in Fundamental or Primitive Datatypes:

If programmer wants to convert one primitive datatype into another primitive


datatype, then it can be done with the help of two ways:

1. Widening or Implicit TypeCasting

2. Narrowing or Explicit TypeCasting

The primitive datatypes are categorized into two categories as higher types
and the second is lower types. The higher types includes datatypes that
contains a large number and their size is also large. The lower type include
datatypes that contains a small number and their size is also small. The size
of the datatype means amount of memory allocated to the variable
belonging to that datatype. For example, in case of character datatype, the
memory allocated will be 16-bits where as in case of long datatype, the
memory allocated will be 64-bits. In typecasting, we can convert a higher
type to lower type and viceversa. But we cannot convert boolean datatype
into either higher type or lower type.

byteshortcharintlongfloatdouble

Lower type includes byte,short,character.

Higher type includes int,long,float,double.

Widening:

It is defined as a type casting that converts a lower type to a higher type. In


other words, it is defined as a type casting that converts a lower datatype
into higher datatype. In case of Widening, there is no loss of data i.e. data is
not lost during the casting operation. If programmer wants to perform
casting, then it is the programmer’s responsibility to use an operator known
as cast operator. The cast operator includes opening of the circular brace
and closing of circular brace and in the middle it contains data type that user
is interested to cast. But in case of widening, if the programmer is not using
any cast operator, then there is no compile time error. In other words, Java
Compiler takes it as its responsibility to perform typecasting, without

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
17

expecting it from the programmer. That is why, it is also known as Implicit


typecasting.

Let us consider an example, to understand the concept of


widening. Let us consider a lower data type as integer and the higher data
type as float and let us perform typecasting as shown below:

public class WideningProg{


public static void main(String args[]){
int num=102;
double d;
d=num;
System.out.println (d);
}
} // The output is 102.0
When the above code is executed, the output is 102.0
The above code does not give any compile time error, though we did not
provide, any cast operator. The reason is Java Compiler will do it internally.
The above program can also be written as shown below:

public class WideningProg1 {


public static void main (String args[]){
int num=102;
double d;
d= (double) num; /*Here (double) is cast operator that
converts any value into double*/
System.out.println (d);
}
} // The output is 102.0

Narrowing:

It is defined as a type casting that converts a higher type to lower type. In


other words, it is defined as a type casting that converts a higher data type
into lower data type. In case of Narrowing, there is loss of data i.e. there
always exists, data getting lost during the casting operation. If programmer
wants to perform casting, then it is the programmer’s responsibility to use an
operator known as cast operator. The cast operator includes opening of the

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
18

circular brace and closing of circular brace and in the middle it contains data
type that user is interested to cast. In case of narrowing, if the programmer
is not using any cast operator, then there is a compile time error. In other
words, Java Compiler does not take any responsibility to perform
typecasting. In other words, the typecasting responsibility must be taken by
the programmer itself. That is why, it is also known as Explicit
typecasting.

Let us consider an example, to understand the concept of


narrowing. Let us consider a higher data type as double and the lower data
type as integer and let us perform typecasting as shown below:

public class NarrowingProg1 {


public static void main(String ar[]){
double d =12.45;
int i;
i=d;
System.out.println(i);
}
}
When the above code is executed, we get compile time error as we did not
provide, any cast operator. It means that it is mandatory for the user to
provide cast operator as shown below:

public class NarrowingProg2 {


public static void main(String ar[]){
double d =12.45;
int i;
i= (int) d; /*Here (int) is cast operator that converts any value into
integer*/
System.out.println (i);
}
} // The output is 12

Practice Codes:

public class WideningProg{


public static void main(String args[]){

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
19

char ch='A';
int num;
num = ch;
System.out.println(num);
}
}
Class

Before going to class, let us review a concept known as Encapsulation. We


have studied that Encapsulation is one of the most important concepts in
Object Oriented Paradigm. Encapsulation says that wrapping of variables and
methods into one unit. Technically, if user wants to implement this concept,
then it can be implemented with the help of a class or an interface.
In Java, a class is defined as collection of
variables and methods. The variables represent the features of a class and
the methods represent the behaviour of a class. The syntax of a class is
shown below:

class ClassName {

The above consists of a keyword as class followed by the ClassName. The


ClassName can be anything i.e. it must be an identifier. Practically, the name
of a class must reflect the type of code that is present in the class. A class
can consist of the following members as shown below:
1. Instance Variables
2. Local Variables
3. Instance Methods
4. Static Variables
5. Static Methods
6. Static Variables
7. public static void main(String a[]) method
8. Constructors

When a class gets loaded into JVM, there exists some priority to execute the
above mentioned members. The priority is listed in ascending order as
shown below:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
20

1. Static Variables
2. Static Methods
3. Static Block
4. public static void main(String a[]) method
5. Instance Variables
6. Constructors
7. Instance Methods
8. Local Variables

Let us understand the concept of a class with the help of an example as


shown below:

access_specifier keyword class ClassName {


int x,y;
void display(){
System.out.println("This is example");
}
}

In the above class, we can see two members . The first is instance variables
i.e. we have two instance variables and the second is instance method. The
two instance variables are x and y and the instance method is
display method. So, we can conclude that any variable present in a class is
known as instance variables and any method present in a class is known as
instance method. The access specifier can be public, protected and
default. If the programmer has not mention the access-specifier while writing
the program, then the access specifier is default access specifier. The only
access specifier that cannot be used is private. If private access specifier is
used then we will get a compile time error as Illegal access specifier. The
keyword field can contain keywords like final and abstract. Depending on
the type of environment, the keyword can be either final or abstract. The
ClassName must reflect the type of code that is written inside the class.
Method
As we know, that the job of a method is to represent functionality or
behaviour of a class. In Java, a method consists of 6 parts as shown below:
1. Access Specifier
2. keyword

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
21

3. Return Datatype
4. Method Name
5. Parameters
6. Method Body

The syntax of a method is :

access_specifier keyword return_datatype method_name parameters {


----------------
----------------
}

Access Specifier:

The first field is the access specifier. The access specifier defines or controls
the access of the method, i.e. it explains how it can allow other objects to
access this method. They are various access specifiers in Java. Let us
consider only two in order to understand the concept. If we consider access
specifier as public, then any object can access this method. But if we
consider access specifier as private, then only the object that is present in
the class where the method body is present can access i.e. objects from
other class cannot access this method.

Keyword:

The second field is optional. They are many types of keywords available i.e.
depending on the type of environment keywords gets varied. The keywords
are static, final, abstract and so on. If user wants to make a method as static,
then the developer has to write this keyword static before the name of the
method. If the method is static, then it has its own importance and own
meaning. But if the method is final, then it has its own meaning. In other
words, depending on the type of requirement, different type of keyword is
used.

Return Datatype:

The third field is return datatype. As we know that a method contains some
code and if this code gets executed, it performs some task. Each and every

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
22

method has to return some value to a calling function. A method returns a


value with the help of a statement known as return statement. If a method
returns an integer value, then the return datatype will me int, but if a
method returns a floating value, then the return datatype will be float or
double and so on i.e. return datatype in the method signature always
depends on the return statement. But if there is no return statement or if the
method is not returning any value, then the return datatype will be void.

Method Name:

The fourth field is method name. The Method Name is used to identify a
method. The name of the method must reflect the type of code developer is
writing with in the body of the method.

Parameters

The fifth field is parameter or parameter list. A parameter list consists of a


series of parameters declaration separated by commas. A parameter
declaration is similar to variable declaration.

Method Body

The sixth component is method body. It contains definition of a method. A


method body contains some statements that when executed performs some
task.
In the method body, there exist some variables.
These variables are known as local variables. In other words, variables
present in the method are known as local variables. The method can be
either main method or non-main method.

Constructor

It is difficult to allocate the values of instance variables of a class , each time


when an instance gets created. There exists one more way to allocate values
i.e. during creation of instance variable i.e. with the help of a constructor.
A Constructor is defined as a method, which is used to
initialize the instance variables. A constructor has the following
characteristics:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
23

1. The constructor name must be same as the name of the class in which
it is present.
2. A constructor must not have any return datatype i.e. a constructor will
never return a value, nor even void. If user writes a return datatype,
then it may lead to compile time error.
3. A constructor may or may not have parameters.
4. A constructor is called and executed only once per object. In other
words, if user creates an object, then constructor is called. If user
creates 10 objects, then the constructor is called 10 times.

As soon as the new operator gets executed, memory is created on heap. The
size of memory that gets created on heap depends on number of instance
variables and instance methods present in a class. After execution of new
operator, JVM will call for the constructor. After finding the constructor, JVM
will execute the constructor, and the values present in the objects gets
initialized.
In short , a constructor is defined as a method
that is automatically invoked when an instance of a class is created.

They are 4 types of constructors. They are:

1. Default Constructor
2. Zero Parameter Constructor
3. Parameterized Constructor
4. Copy Constructor

Default Constructor:

If the developer doesn’t define a constructor, then the JVM will provide a
default constructor or do-nothing constructor. The job of this constructor is to
assign null values to instance variables present in the object. If the variables
are of type integer, then it assign value as 0, and if the variables are of type
float or double, then it assign value as 0.0f and 0.0 and if the value are of
type String, then it assign value as null.

The below code explains the concept of a default constructor:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
24

public class DefaultConstructor {


int x;
float y;
void display(){
System.out.println("The value of x is:"+x);
System.out.println("The value of y is:"+y);
}
public static void main(String[] args) {
DefaultConstructor dc = new DefaultConstructor();
dc.display();
}
}

In the above example, the developer has define a class known as Default
Constructor. This class is having two instance variables, one instance method
and one main method i.e. public static void main(String args[]). When the
first statements in main method, gets executed a reference variable by
name dc is created on the stack, and then the new operator creates a
memory on the heap. After creating the memory, the JVM will search for the
constructor. But in the program, the developer has not written the body of
zero parameter constructor. In this case, the JVM will not give any run-time
error, but internally calls for a constructor known as Default Constructor. It
means that default constructor is called , if the developer has not provided
the body of zero parameter constructor. But if we assume, that the user has
provided the body of zero parameter constructor then the JVM will not call
Default Constructor.
Zero Parameter Constructor:

A Zero Parameter Constructor is defined as a constructor that consists of


zero parameters. The body of this constructor is written by the programmer
or the developer.

The below code illustrates the concept of a zero parameter


constructor:

public class ZeroPC {


int x,y;
ZeroPC(){

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
25

x=6;
y=9;
}
public static void main(String[] args) {
ZeroPC zpc = new ZeroPC();
System.out.println(zpc.x);
System.out.println(zpc.y);
}
}

When the above program gets executed, the JVM will search for the Zero
Parameter Constructor. In this program, the developer has provided a zero
parameter constructor, which is executed and the values that are present
with in the zero parameter constructor gets initialized to instance variables
that are present on the heap. But if user has not provided the zero
parameter constructor, then the JVM will call default constructor.

Copy Constructor:
A copy constructor is one which takes only one argument i.e. a reference to
an object of same class to which the constructor belongs.

The Copy Constructor is not in the syllabus. If there is time, this


topic will be covered in future.

Parameterized Constructor:

A Parameterized Constructor is defined as a constructor that consists of one


or more parameters. The body of this constructor is written by the
programmer or the developer.

The below code explains the concept of a parameterized


constructor:

class Person{
int age;
String name;
}

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
26

Person(int i,String s){


age = i;
name = s;
}
void talk(){
System.out.println("My name is:"+name);
System.out.println("My age is:"+age);
}
}
public class ParaConstructor {
public static void main(String[] args) {
Person p1 = new Person(34,"Sachin");
p1.talk();

}
}
When the above program gets executed, the JVM will see whether the
programmer has provided the body of the parameterized constructor. In this
program, we using two parameterized constructor. As the programmer has
supplied the body of the parameterized constructor, the JVM during
execution of the program will initialize the values of instance variables with
the values that are provided by the programmer. But if the programmer does
not provide the body of parameterized constructor, then there will be
compile time error stating the body of parameterized constructor is not
defined. It must be noted that, the JVM will not call any default constructor.
In other words, a default constructor is called by JVM , if the programmer
does not supply the body of zero parameter constructor only.

Constructor Overloading

Constructor Overloading is similar to Method Overloading with a difference of


the constructors that are overloaded. The below program illustrates the
concept of constructor overloading:

public class ConstructorOverlaoding {


int x,y;
ConstructorOverlaoding(){
x=9;

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
27

y=12;
}
ConstructorOverlaoding(int a){
x=a;
}
ConstructorOverlaoding(int a,int b){
x=a;
y=b;
}
public static void main(String[] args) {

ConstructorOverlaoding co = new ConstructorOverlaoding();


System.out.println(co.x);
System.out.println(co.y);

ConstructorOverlaoding co1 = new ConstructorOverlaoding(8);


System.out.println(co1.x);
System.out.println(co1.y);

ConstructorOverlaoding co2 = new ConstructorOverlaoding(1,23);


System.out.println(co2.x);
System.out.println(co2.y);
}
}

Method Overloading or Polymorphism

The word polymorphism was introduced by the people of Greek. The word
poly means many and morphism means forms i.e. many forms. This term is
used by the developers to describe a method to have multiple definitions.
Java implements this theoretical concept, by enabling
programmers to overload a method. A programmer overloads a method by
defining two or more methods using the same name, but differs in their
signatures either in type of parameters or in the number of parameters. The
reason of using method overloading is it make easier to use methods for a
programmer because the programmer doesn’t have to remember a lot of
method names. The only thing the programmer must remember is the
method name and number of parameters it holds.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
28

The below example illustrates the use of Method


Overloading as shown below:

public class MethodOverloading {


void test(){
System.out.println("No parameter method is called");
}
void test(int a){
System.out.println("One parameter method is called");
System.out.println("The value of the parameter is"+a);
}
void test(int a, int b){
System.out.println("Two parameter method is called");
System.out.println("The two parameters are:"+a+" "+b);
}
public static void main(String[] args) {
MethodOverloading mo = new MethodOverloading();
mo.test();
mo.test(12);
mo.test(2, 3);
}
}

this keyword:

A method of a class can access instance variables of the class as well as


other methods that are present with in the class. The variables that are
present in a method are known as local variables. The variables that are
present in a class are known as instance variables.

But if user has used same name for both local and
instance variable and if user wants to access the instance variable, then it is
possible with the help of this keyword.
By doing this, we can inform the JVM to access the value
of current instance variable. The below program is used to illustrate this
keyword.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
29

public class This {


int x=10;
void main() {
int x=5;
System.out.println(x);
System.out.println(this.x);
}
public static void main(String ag[]){
This th = new This();
th.main();
}
}

Use of final with data:If a variable is declared as final, then the value
of the variable can never be altered. That is , with the help of final keyword,
we can make the value of a variable as constant. If anyone wants to change
the value, then it leads to compile time error. The syntax to declare a
variable as final is:

final datatype variable_name = value;

The below program illustrate the concept of final with variables that contains
data:

public class Final {


final int x =10;
public static void main(String[] args) {
Final f = new Final();
System.out.println(f.x);
f.x=19; // leads to compile time error
}
}

Recursion:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
30

Java supports concept of Recursion. The process in which a method calls


itself is known as Recursion and the method is known as Recursive method.

The below program illustrate the concept of recursion as shown below:

public class Factorial {


int fact(int n){
if(n == 1)
return 1;
else
return n*fact(n-1);
}
public static void main(String[] args) {
Factorial f = new Factorial();
System.out.println("The value of factorial is "+f.fact(5));
}
}

Garbage Collection:

The JVM's heap stores all objects created by an executing Java program.
Objects are created by Java's "new" operator, and memory for new objects is
allocated on the heap at run time. Garbage collection is the process of
automatically freeing objects that are no longer referenced by the program.
This frees the programmer from having to keep track of when to free
allocated memory, thereby preventing many potential bugs and headaches.

The name "garbage collection" implies that objects that are no longer
needed by the program are "garbage" and can be thrown away. A more
accurate and up-to-date metaphor might be "memory recycling." When an
object is no longer referenced by the program, the heap space it occupies
must be recycled so that the space is available for subsequent new objects.
The garbage collector must somehow determine which objects are no longer
referenced by the program and make available the heap space occupied by
such unreferenced objects.

In addition to freeing unreferenced objects, a garbage collector may also


combat heap fragmentation. Heap fragmentation occurs through the course

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
31

of normal program execution. New objects are allocated, and unreferenced


objects are freed such that free blocks of heap memory are left in between
blocks occupied by live objects.

Why garbage collection?

Garbage collection relieves programmers from the burden of freeing


allocated memory. Assigning this responsibility to the JVM has several
advantages. First, it can make programmers more productive i.e. in
programming languages that do not support the concept of automatic
garbage collection, it becomes a headache to the programmer to spend
hours to find out how to solve elusive memory problems. When programming
in Java the programmer can use that time more advantageously.

A second advantage of garbage collection is that it helps ensure program


integrity. Garbage collection is an important part of Java's security strategy.
Java programmers are unable to accidentally (or purposely) crash the JVM by
incorrectly freeing memory.

Fortunately, very good garbage collection algorithms have been developed,


and adequate performance can be achieved for all but the most demanding
of applications. Because Java's garbage collector runs in its own thread, it
will, in most cases, run transparently alongside the execution of the
program. Moreover, if a programmer really wants to explicitly request a
garbage collection at some point, System.gc() or Runtime.gc() can be
invoked, which will fire off a garbage collection at that time.

Garbage collection algorithms

Any garbage collection algorithm must do two basic things. First, it must
detect garbage objects. Second, it must reclaim the heap space used by the
garbage objects and make it available to the program. Garbage detection is
ordinarily accomplished by defining a set of roots and determining
reachability from the roots. An object is reachable if there is some path of
references from the roots by which the executing program can access the
object. The roots are always accessible to the program. Any objects that are
reachable from the roots are considered live. Objects that are not reachable

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
32

are considered garbage, because they can no longer affect the future course
of program execution.

In a JVM the root set is implementation dependent but would always include
any object references in the local variables. In the JVM, all objects reside on
the heap. The local variables reside on the Java stack, and each thread of
execution has its own stack. Each local variable is either an object reference
or a primitive type, such as int, char, or float. Therefore the roots of any JVM
garbage-collected heap will include every object reference on every thread's
stack. Another source of roots are any object references, such as strings, in
the constant pool of loaded classes. The constant pool of a loaded class may
refer to strings stored on the heap, such as the class name, superclass
name, superinterface names, field names, field signatures, method names,
and method signatures.

Any object referred to by a root is reachable and is therefore a live object.


Additionally, any objects referred to by a live object are also reachable. The
program is able to access any reachable objects, so these objects must
remain on the heap. Any objects that are not reachable can be garbage
collected because there is no way for the program to access them.

The JVM can be implemented such that the garbage collector knows the
difference between a genuine object reference and a primitive type (for
example, an int) that appears to be a valid object reference. However, some
garbage collectors may choose not to distinguish between genuine object
references and look-alikes. Such garbage collectors are called conservative
because they may not always free every unreferenced object. Sometimes a
garbage object will be wrongly considered to be live by a conservative
collector, because an object reference look-alike referred to it. Conservative
collectors trade off an increase in garbage collection speed for occasionally
not freeing some actual garbage.

Two basic approaches to distinguishing live objects from garbage are


reference counting and tracing. Reference counting garbage collectors
distinguish live objects from garbage objects by keeping a count for each
object on the heap. The count keeps track of the number of references to
that object. Tracing garbage collectors, on the other hand, actually trace out
the graph of references starting with the root nodes. Objects that are

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
33

encountered during the trace are marked in some way. After the trace is
complete, unmarked objects are known to be unreachable and can be
garbage collected.

What Is Stack?

Each Java virtual machine thread has a private Java virtual machine stack,
created at the same time as the thread. A Java virtual machine stack or stack
stores frames. It holds local variables and partial results, and plays a part in
method invocation and return. Because the Java virtual machine stack is
never manipulated directly except to push and pop frames, frames may be
heap allocated.

The Java virtual machine specification permits Java virtual machine stacks
either to be of a fixed size or to dynamically expand and contract as required
by the computation. If the Java virtual machine stacks are of a fixed size, the
size of each Java virtual machine stack may be chosen independently when
that stack is created. A Java virtual machine implementation may provide the
programmer or the user control over the initial size of Java virtual machine
stacks, as well as, in the case of dynamically expanding or contracting Java
virtual machine stacks, control over the maximum and minimum sizes.

The following exceptional conditions are associated with Java virtual machine
stacks:

 If the computation in a thread requires a larger Java virtual machine


stack than is permitted, the Java virtual machine throws a
StackOverflowError. That is , if the program requires more number of
locations in stack, and if the stack is not having the space then it may
throw an error known as StackOverflowError.
 If Java virtual machine stacks can be dynamically expanded, and
expansion is attempted but insufficient memory can be made available
to effect the expansion, or if insufficient memory can be made
available to create the initial Java virtual machine stack for a new
thread, the Java virtual machine throws an OutOfMemoryError

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
34

To avoid above errors, internally JVM will shift the local variable from the
stack to method area, that is one of the blocks maintained by JVM.

What Is Heap?

In case of stack, each and every thread will have its own stack. But this
option is not with heap. The heap that is maintained by the JVM is shared by
all the threads. It means, that only one heap is present in the JVM. The heap
is the runtime data area from which memory for all class instances.

The heap is created when a Java Virtual Machine starts up. Heap storage for
objects is reclaimed by an automatic storage management system known as
a garbage collector. Objects are never explicitly deallocated. The heap may
be of a fixed size or may be expanded as required by the computation and
may be contracted if a larger heap becomes unnecessary. The memory for
the heap does not need to be contiguous. In other words, it totally depends
on the type of algorithm that is followed by JVM. Some algorithms, allocate
memory in terms of continuous fashion and some in indexed fashion.

The following exceptional condition is associated with heap is:

If a computation requires more heap than can be made available by the


automatic storage management system, the Java virtual machine throws an
OutOfMemoryError

The JVM maintains the following Data Area (Memory). In other words, the
memory in JVM is divided into 5 areas as shown below:

1. Method Area
2. Heap Area
3. Java Stacks
4. PC Registers
5. Native Method Stacks

Out of the above five memory blocks that are present in JVM, we have
discussed only two which will be required to us.

Basic Concept of Inheritance:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
35

Inheritance is considered to be one of the most important concept in Object


Oriented Paradigm. In short, it is defined as code reusability. Practically code
contains variables, methods and blocks. In Java, inheritance is defined as a
concept in which new classes can be produced or derived from existing
classes. The newly created class acquires all the features of the existing
class. Features includes variables and methods of the existing class. The
above concept is used , when a programmer wants some code, which is
already written by some other programmer. In Java terminology, a class that
is giving its features to other classes is known as super class and the class
that does inheriting is known as sub class. In other words, we can define a
subclass as a specialized version of super class.
If user wants to inherit the features of a class into his
class, then it is possible with the help of extends keyword. In other words,
the subclass must contain the extend keyword followed by the name of the
class. The syntax of super class and sub class is shown below:

class SuperClassName{
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
}

class SubClassName extends SuperClassName{


--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
--------------------------------
}

In the above program, the sub class will get the variables and methods of the
super class also. You can understand this line, after understanding the basic
program on inheritance.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
36

Write a program to illustrate the basic concept of Inheritance

class A{
int x=12;
int y=13;
void Add(){
System.out.println("The result of Add method is "+(x+y));
}
}
class B extends A{
int z=16;
void Addition(){
System.out.println("The result of Addition is "+(x+y+z));
}
}
public class Inheritance {
public static void main(String[] args) {
A a1 = new A();
a1.Add();
B b1 = new B();
b1.Addition();
b1.Add();
}
}

In the above program we can notice that, there are three classes. The first is
class A, the second in class B and the third is class C. The class A is known as
super class, the class B is known as sub class the class C is known as
independent class. In class C, we are creating an object of class A as well as
we are creating an object of class B. Now let us consider the following
statements as shown below:

A a1 = new A();

When the above statement gets executed, a reference variable by name a1


gets created on the stack. When the new operator gets executed, memory

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
37

gets allocated on the heap. The amount of memory that gets allocated
depends on number of instance variables and instance methods that are
present with in a class. In class A, we have two instance variables x and y
and one instance method known as Add. It must be noted that a1 is a
reference variable of super class A.

B b1 = new B();

It must be noted that b1 is a reference variable of class B. When the above


statement gets executed, a reference variable by name b1 gets created on
the stack. On the execution of the new operator, memory gets allocated on
the heap. The amount of memory that gets allocated on the heap depends
on the instance variables and instance methods present in class B as well as
the instance variables and instance methods present in class A, which is a
super class to class B. In class B, we have three instance variables x , y and z
and two instance methods Add() and Addition() .In other words , with the
help of reference variable b1 we can access the variables x , y and z as well
as we can access methods Add() and Addition().

Member Access Rules:

As we know that the sub class object can access the variables and methods
of a super class. But the condition is the access specifiers for the variable
and methods present in the super class must be either public, protected or
default. But, there must be not private. If the variables and methods of a
super class are private, then the sub class object cannot access the variables
and methods of a super class because the variables and methods that are
declared as private, cannot be accessed outside the class in which they are
defined. Let us understand the concept of private access specifier with the
help of a program as shown below:

class A1{
private int x=10;
void display(){
System.out.println(x);
}
}
public class privateprogram extends A1 {

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
38

public static void main(String[] args) {


A1 a2 = new A1();
a2.x=10;
}
}

In the above program there exists two classes, the first is super class A1 and
the second is sub class privateprogram. The members that are present in
class A1 are instance variable x and instance method display(). The access
specifier of the instance variable is private and the access specifier for
display() method is default. The sub class is privateprogram that contains a
method known as main method. In this method we are creating an object of
class A1. The reference variable to class A1 is a2. With the help of a2 , now I
want to change the value of x, which is an instance variable in class A1. If we
want to change the value, we will get compile time error because we are
accessing the variable in another class, which leads to error as we cannot
access the variable outside the class A1.

Forms of Inheritance

They are different types of inheritance in Java are:


1. Single level Inheritance
2. Multi level Inheritance
3. Multiple Inheritance

Single level Inheritance

It is defined as an inheritance that consists of only one sub class, in a


hierarchy of classes. We can understand the concept of single level
inheritance, with the help of a small example. If some one says that he/ she
lives in a single storey building, it means that building consists of ground
floor and first floor. Likewise, single level inheritance consists of one super
class and one sub class only. To understand the concept of single level
inheritance, let us consider the following example as shown below:

class A{
int x=12;

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
39

int y=13;
void Add(){
System.out.println("The result of Add method is "+(x+y));
}
}
class B extends A{
int z=16;
void Addition(){
System.out.println("The result of Addition is "+(x+y+z));
}
}
public class Inheritance {
public static void main(String[] args) {
A a1 = new A();
a1.Add();
B b1 = new B();
b1.Addition();
b1.Add();
}
}
In the above example, we can notice that there exists only one super class
and one sub class.

Multi level Inheritance

It is defined as an inheritance that consists of more than one sub class, in a


hierarchy of classes. We can understand the concept of multi level
inheritance, with the help of a small example. If some one says that he/ she
lives in a multi storey building, it means that building consists of ground
floor, first floor, second floor and more than that. Likewise, multi level
inheritance consists of more than one super class and more than one sub
class . To understand the concept of multi level inheritance, let us consider
the following example as shown below:

class A{
int x=12;
int y=13;

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
40

void Add(){
System.out.println("The result of Add method is "+(x+y));
}
}
class B extends A{
int z=16;
void Addition(){
System.out.println("The result of Addition is "+(x+y+z));
}
}
class C extends B{
int w=19;
void Addition1(){
System.out.println("The result of Addition1 is"+(x+y+z+w));
}
}
public class Inheritance {
public static void main(String[] args) {
A a1 = new A();
a1.Add();
B b1 = new B();
b1.Addition();
b1.Add();
C c1 = new C();
c1.Addition();
c1.Add();
c1.Addition1();
}
}

In the above program, we can notice that there exists more than one sub
class and more than one super class, depending on the type of combinations.

Multiple Inheritance
Multiple Inheritance is a type of inheritance that makes a sub class to access
variables and methods from more than one super class at a time. Normally,
in case of C++, multiple inheritance is possible with the help of extends
keyword but where as in Java, multiple inheritance with the help of extends

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
41

keyword generates a compile time error. That’s why multiple inheritance in


Java is possible with the help of implements keyword. Here we have to
create more than one interface and then write an implementation class, that
can borrow features from more than one interface at a time i.e. after
implements keyword we have to write more than two interface names. The
following program explains the concept of multiple inheritance in a clear
way:

interface A{
void m1();
}
interface B{
void m2();
}
class C implements A,B{
public void m1(){
System.out.println("Method of Interface A");
}
public void m2(){
System.out.println("Method of Interface B");
}
}

public class MutipleInher {


public static void main(String[] args) {
C c1 = new C();
c1.m1();
c1.m2();
}
}

In the above program we can notice that class C is getting features from
more than one interface at a time. This concept is known as Multiple
Inheritance, which is solved with the help of interfaces concept.

Using final with inheritance

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
42

As we know that final is one of the types of access specifier or access


modifier that can be used for a variable, method and a class. If we use final
for a variable , then the value present in the variable becomes constant i.e. if
the value is changed then it leads to compile time error. One more thing, if
variables are declared as final then it is compulsory that variables must be
initialized during declaration only. If you initialize the variable in the next
line, then it may lead to compile time error.
Today, we will see how to use final for a method and for a
class. final access specifier when used for a class or a method in concept of
inheritance has its own effect.

Final with class:

If we use final access specifier for a class, and if the program that contains
classes is using inheritance, then we get compile time error. In other words,
if we write final access specifier for a super class , and if we try to create sub
classes then we get a compile time error saying that classes cannot be
inherited. It means that if we declare super class as final, then we cannot
create a sub class for that class. if we do so, then a compile time error gets
generated.

Final with method:

If we use final access specifier for a method, and if the program is following
inheritance concept and if user wants to over ride the method then we will
get a compile time error. In other words, if we write final access specifier for
a method that is present in the super class and if we try to over ride the
same method with in a sub class, then we get a compile time error as final
methods cannot be overridden i.e. we cannot write methods having same
signature as that of a methods in super class with in a sub class.

Method Overriding: As we have studied that there exists a concept known


as Polymorphism in Object Oriented Paradigm. It states that same method
can perform different operations at different time. Technically they are two
types of polymorphism. The first is known as static polymorphism or Method
Overloading and the second is known as dynamic polymorphism or Method
Overriding.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
43

Method Overriding will occur only in case of


inheritance i.e. if the program is using inheritance, then we can get a
problem of method overriding. In case of Method Overloading, the name of
the method will be same but the number of parameters with in the method
gets changed. But in case of Method Overriding, the name of the method is
same as well as the number of parameters are also same. Some times, if
program is following a concept known as inheritance, and if the super class
as well as sub class contains a method having same name and same number
of parameters and same return datatype, then we say that the method
present in sub class is over riding the method present in super class.
Suppose, we are creating an object of sub class, and if we want to call a
method with the help of dot operator, then the method present in sub class
only gets executed and the method present in super class never gets
executed. It means that during execution of the program, JVM is giving more
priority to the method present in sub class than the method present in super
class. So, in short we say that the method present in sub class is over riding
the method present in super class.
To understand the above concept, lets write program as
shown below:

class A{
void display(){
System.out.println("Method display of class A is called");
}
}
class B extends A{
void display(){
System.out.println("Method display of class B is called");
}
}

public class MethodOverriding {


public static void main(String[] args) {
B b1 = new B();
b1.display();
}
}

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
44

In the above example , we can notice that they are three classes. The first is
class A , which is a super class . The second is class B, which is a sub class
and the third is MethodOverriding. We can notice that there is a method by
name display() that is present in super class as well as sub class has same
method name, same return datatype and same number of parameters. But if
we create an object of sub class, and if we call display() method, then
display() method of class B is called, but if I want to call display() method of
class A, which is a super class here, then we cannot call the display() method
which is present in super class with the help of object of class B. Here we are
getting this problem because the name of the method is same in both super
class and sub class. So, if I want to call display() method of super class, then
I have to use a keyword known as super which calls a method or variable
present in the super class.

Usage of super keyword:

As we have studied that there exists a keyword known as this. It is mainly


used in situations when the name of instance variable and the name of a
local variable is same that too in the same class. But if the situation is that
the program is using a concept known as inheritance and if the name of the
method and the name of the variable is same in both sub class and super
class, then to access the variables and methods of the super class, we use a
keyword known as super keyword. We can use super keyword with a
variable and with the method.

super keyword with method:

class A{
void display(){
System.out.println("Method display of class A is called");
}
}
class B extends A{
void display(){
System.out.println("Method display of class B is called");
super.display();

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
45

}
}

public class MethodOverriding {


public static void main(String[] args) {
B b1 = new B();
b1.display();
}
}

If we want to call the display() method of super class, then it is mandatory


that we have to write the statement as super.methodname() in any sub class
method, so during execution of the program, JVM will call the method that is
present in the immediate super class.

super keyword with variable:

class A{
int x=5;
}
class B extends A{
int x=13;
void dis(){
System.out.println(x);
System.out.println(super.x);
}
}
class C{
public static void main(String args[]){
B b1 = new B();
b1.dis();
}
}

In the above program, we can notice that the program is using a concept
known as inheritance. In this program, there exists three classes. Among
three classes, we have one class A, which is known as super class, we have

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
46

one more class B, which is known as sub class and we have one more class
C, which is neither a sub class nor super class, but is said to be an
independent class. We can also notice, that there is a variable by name x in
super class A and another variable by name x in sub class B. In class C, we
created an object of class B , and with the help of this object if we access the
variable x, then the x present in class B only gets executed. In other words,
with the help of sub class object , we cannot access the variable x that is
present in super class. In order to access the variable x present in super
class, we have to use a keyword super with the name of the variable. Here
we write

System.out.println(super.x); in a method of a sub class.

When the above statement gets executed, the variable present in super
class is called.

Packages:

A Package is defined as collection of classes, interfaces and sub packages. A


class is defined as collection of variables and methods. The variables can be
either static variables or instance variables and the methods can be either
instance methods or static methods. As we know that, encapsulation is a
concept in Object Orientation Paradigm, which is technically implemented
with the help of classes and interfaces. An interface is defined as a construct
that consists of variables and methods. The variables with in a interface is
known as interface variables and the methods in an interface is known as
abstract methods. A sub-package is defined as a package present with in a
package. It also contains classes and interfaces.

Types of Packages

They are two types of packages that exists in Java programming language.
They are:
1. Predefined Package
2. User Defined Package

Predefined Package:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
47

It is defined as a package whose classes and interfaces are already defined


by the Java Developers. These packages are defined already by the
developers keeping in mind of the programmers that can use the methods
present in the classes and interfaces of a particular package whenever it is
required. For example if the programmer is designing an application that
require connectivity to the database, then we require some methods that
can be used to access or retrieve the data from the database and some
methods that are used to store the data into database. These methods are
present in the class that is present in a predefined package known as
java.sql. In other words, if user is writing a program on JDBC, then the user
need not bother about what methods those are required but just use the
package java.sql by importing it with in the program. Like wise, Java
developers have developed some packages that can be used whenever it is
required by their application or program. There are many predefined
packages, but the most important are:

1. java.lang
2. java.awt
3. java.net
4. java.sql
5. java.util
6. javax.swing

User defined Packages:


A user defined package is defined as a package, whose classes and
interfaces have to be written by the users or the programmers. In other
words, as we know a class consists of concrete methods where as interface
consists of abstract methods. In case of User Defined Package, in case of
classes, it is the responsibility of the user to write the functionality of
concrete methods, and in case of interface it is responsibility of the user is to
write the name of the abstract method.

Creation of Packages

To create a user-defined package, a keyword package is used as shown


below:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
48

package packagename;

It must be noted that whenever user wants to write a class with in a


package, then with in a notepad or editor we can write only one class at a
time. Writing more than one class with in a notepad will lead to compile time
error, when the first statement is package creation statement. But, if we are
omitting that statement, then no compile time error gets generated. The
syntax to write a class with in a package is as shown below:

package packagename;

class classname{
---------------------
---------------------
---------------------
---------------------
}

The above code can be written either in a notepad or java editor or any
editor. It must be noted that the name of the notepad or file, must be same
as the name of the class that is present with in the file. This class must be a
single class i.e. if we write more than one class with in a same file, then a
compile time error gets generated. But, if user wants to include one more
class with in a package, then the user has to open new notepad or java
editor, write the first statement as package creation statement , followed by
the name of the class and save the name of the file as same as the name of
the class.

Write a java program that is used to create a package that is having only two
classes.

Step1: Creating Addition class in a package known as student.

package student;
public class Addition{
int i,j;
public Addition(int a,int b){

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
49

i=a;
j=b;
}
public void display(){
System.out.println("The added value is:"+(i+j));
}
}

Step2: Creating Substraction class in the same package known as student.

package student;
public class Substraction{
int i,j;
public Substraction(int a,int b){
i=a;
j=b;
}
public void display(){
System.out.println("The added value is:"+(i-j));
}
}
The above step1 must be written in separate notepad and the step2 must
also written in separate notepad. In the above step1 and step2 we can notice
that when user is writing a class with in a package, then it is compulsory that
the class must be public, the methods with in the class must be public, the
constructors with in the class must be public.

Compilation of Packages

The compilation of a package is different from the compilation of a java


program. The syntax to compile a package is shown below:

javac –d <directory path> Classname.java

-d: it is an option of javac, that is used to create a directory or a folder.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
50

<directory path> : It includes the location at which the directory must be


stored. In other words, if there is (.) then it represents current working
directory or present working directory.

When user press enter key, then a directory with the name that is present in
the package gets created and this directory is stored in a location that has
been specified in the directory path and the .class file is stored in this
directory.

Accessing a Package:

If user wants to access a package, then the user has to write a java program
that can access the methods that are present in the class that are present in
the package. This java program, must contain a statement that is used to
access a package. The statement is nothing but import statement. With the
help of import statement, the java program can access the methods that are
present with in the class and these classes are present in the package.

Write a java program that is used to access a package that is having only
two classes.

import student.Addition;
import student.Substraction;
class Pack{
public static void main(String sun[]){
Addition a1 = new Addition(2,3);
a1.display();
Substraction s1 = new Substraction(10,4);
s1.display();
}
}

The above java program is written in a notepad, whose name is same as the
name of the class. Here the class name is Pack i.e. the name of the notepad
is Pack.java . When the above program gets compiled with the help of javac
command, a .class file gets generated and when the above program gets
executed with the help of java command, then we can see the output.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
51

Importing a Package:

If the programmer wants to access a package, whether the package is user


defined or predefined, then it is possible with the help of a statement known
as import statement. They are two types of import statements in Java:
1. Implicit import or static import
2. Explicit import or general import

Implicit import or static import:

The syntax of implicit import statement is

import packagename.*;

If the programmer wants to include all classes and interfaces of a


subpackage then the syntax is

import packagename.subpackagename.*;

If the programmer writes implicit import statement, then during the


execution of the program, it is the responsibility of the JVM to load all the
classes and interfaces that are present with in a package only. It is to be
made it clear that, classes and interfaces of sub packages are not loaded
into the main memory. Though the user or programmer requires only two
classes and no interfaces in their program also, the JVM will load all classes
and interfaces. This lead to delay in execution of the program and
there is effect on the efficiency of the program. To increase the
efficiency of the program and the fast execution of the program, it is
recommended that the programmer use explicit import. More over this
type of import statements are only used in academics but never used in real
time.
Let us consider an example to understand the
concept of implicit import. The following examples are:

import java.awt.*;

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
52

When the above statement gets executed, all classes and interfaces of
package awt are loaded into the main memory, though the user is
interested only in some methods or some classes.

import java.awt.event.*;

When the above statement gets executed, all classes and interfaces present
in the sub-package event are loaded in the main memory, though the user is
interested only in some methods or some classes.

As in the above cases, we can notice that the classes and interfaces that the
user is not interested are also getting loaded into main memory. (It must be
noted that the word interested reflects to the methods that are
present in the classes and interfaces that are not required to the
program or application that user is writing).
So, if the programmer is interested only in loading of the methods
(present in the classes and interfaces), that are present in the application,
and if the programmer wants no delay during the execution of the program,
then it is advisable to go for explicit import or general import.

Explicit import or general import:

The syntax of explicit import statement is

import packagename. classname.methodname;

If the programmer wants to include all classes and interfaces of a


subpackage then the syntax is

import packagename.subpackagename. classname.methodname;

If the programmer writes explicit import statement, then during the


execution of the program, it is the responsibility of the JVM to load only the
method that is specified in the statement. In other words, in case of explicit
import other methods that are not specified are not loaded into main
memory. In this case there is no delay in execution of the program
and the efficiency of the program also increases. More over this type of
import statements are only used in real time.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
53

Let us consider an example to understand the


concept of implicit import. The following examples are:

import java.awt.event.ActionEvent;

When the above statement gets executed, only the methods that are present
in the class ActionEvent are loaded on to the main memory. So in this way
we can save the time i.e. the execution time and this increases the efficiency
of the application or the program that is developed by the user. .all classes
and interfaces present in the sub-package event are loaded in the main
memory, though the user is interested only in some methods or some
classes.

Define Interface
As we have studied a concept known as Encapsulation in Object Oriented
Paradigm. It states that wrapping of variables and methods into one unit.
This is done just to provide security to data that is present in variables and
security to information that is present in the method. Technically, the
concept of encapsulation is implemented with the help of classes and
interfaces. As we know that a class is defined as a collection of variables and
methods. The methods that are present in a class is known as concrete
methods.
An interface is defined as collection of
abstract methods and interface variables. If an interface contains concrete
methods, then java compiler generates a compile time error. An abstract
method is defined as a method that does not contain body. In other words an
interface consists of only method prototypes. Since, these methods are
incomplete methods, that’s the reason we cannot create objects for
interfaces. The methods present in the interface are public and abstract. In
other words, the access specifier that is used for the methods present in an
interface is public , so that these interfaces can be accessed from anywhere.
The keyword abstract, says java compiler that these methods don’t have
body. These abstract methods present in the interfaces are terminated by
semicolon. If semicolon is missing , then we get a compile time error.

The syntax to create an interface is:

interface interface_name{

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
54

public abstract return_datatype methodname();


--------------------------------
--------------------------------
--------------------------------
--------------------------------
}

Their can exist only one abstract method or any number of abstract
methods. Number of abstract methods in an interface depends on the type
of program, a programmer is writing.

Implementation Class
The class that take the responsibility of defining the body of the abstract
methods in an interface is known as implementation class. Moreover, this
class can define their methods of their own. The syntax of implementation
class is

class ClassName implements interfaceName{


-----------------------------------------
-----------------------------------------
-----------------------------------------
-----------------------------------------
}

An implementation class is define as a class that contains keyword as


implement followed by the name of an interface. It is mandatory that any
class, which acts as implementation class must define bodies of all abstract
methods that are present in the interface, for which the class has taken
responsibility. Let us understand with the help of an example. If an interface
has 3 abstract methods, and if the implementation class has define only 2
abstract methods, then during compilation of the java program, Java
Compiler will generate compile time error.

Interface Reference

As we have studied that it is not possible to create objects to an interface.


So, we can create a reference to an interface. This reference is known as

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
55

Interface Reference. An interface reference is written in an implementation


class. An interface reference has ability to access only those methods that
are present with in the interface but cannot access those methods that are
not present in the interface but defined in implementation class. In this case,
the programmer has to create an object that has ability to access any
method present with in the implementation class. Any method means
whether the method is present in the interface or not.

The syntax of interface reference is:

interfacename interfacereference = new ConstructorofImplementationclass

Write a program to create an interface and access this interface


using interface reference.

interface Inter {
void addTwo(int a,int b);
void addThree(int a,int b,int c);
}
class Arith implements Inter{
public void addTwo(int a,int b){
System.out.println("The result of two values "+(a+b));
}
public void addThree(int a,int b,int c){
System.out.println("The result of three values "+(a+b+c));
}
}
class Arithmetic{
public static void main(String ag[]){
Inter i = new Arith();
i.addTwo(2, 3);
i.addThree(6, 8, 9);
}
}

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
56

Interface Variables:

Variables present in a class is known as instance variables, where as


variables present in an interface is known as interface variables. The syntax
of interface variables is :

public final static datatype variablename;

It must be noted that interface variables can be accessed without creating


either object or interface reference because interface variables are static by
nature. If programmer wants to change the value of interface variable with
an implementation class, then the java compiler will generate a compile time
error because interface variables are final in nature. To be more specific,
interface variables are by default public, final and static. In other words, if
the programmer as not mention public, static and final keywords while
declaring a variable, then the java compiler will not give any compile time
error. It means that Java Compiler will consider each and every variable with
in an interface as public, final and static.

Write a program to illustrate the concept of interface variables

interface InterfaceVariables{
int x=10;
}
class Interf1 implements InterfaceVariables{
public static void main(String args[]){
Interf1 in = new Interf1();
System.out.println(in.x);
//in.x=112;
}
}

When the above program gets executed, we get output as 10. But, if we
remove the single comment, then if we save and then compile the program,
we get compile time error as saying that we cannot assign a value
to variable x.

Interface can be extended:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
57

As we have seen in Unit III that a class can inherit another class with the help
of extends keyword. Likewise, we can inherit an interface from another
interface. The syntax holds good as same as the class. When a class
implements an interface, that inherits another interface, it becomes
mandatory for the implementation class to implement the methods that are
present in the interface and the methods that have been inherited from
other interface. With this concept, we can implement Multiple Inheritance in
the indirect way.

Write a program that illustrates the concept of extension of the


interface.

interface A{
void d1();
}

interface B extends A{
void d2();
}

class C implements B{
public void d1(){
System.out.println("Method of Interface A is called");
}

public void d2(){


System.out.println("Method of Interface B is called");
}
}

class InterfEx{
public static void main(String args[]){
C c1 = new C();
c1.d1();
c1.d2();
}
}

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
58

In the above program, we can notice that, there are two interfaces namely A
and B. We can notice that interface A contains only one method. There is
another interface by name B, which has two methods one of its own and the
another method is inherited from the interface A as we are using a keyword
known as extends. After writing the interface, we are creating a class
known as implementation class, whose responsibility is write the body of the
abstract methods that are declared with in the interface. It is mandatory that
this implementation class must contain the bodies of the abstract methods
that are present in the interface B. If any one of the method body is missing,
then a compile time error gets generated. We are creating one more class
that contains main method. In this method, we are creating objects of
implementation class so that we can call the methods that are present in the
implementation class.

Introduction
Exception is a run-time error which arises during the execution of java
program. The term exception in java stands for an exceptional event. It
can be defined as abnormal event that arises during the execution and
normal flow of program.
Types of Errors in Java :
They are two types of errors in java. They are discussed below:
1.Compile-time Error-Compile -time Error are those error which occurs
when you don't follow the syntax of the code or do wrong in writing a code
of the Programming language. The Compiler detect the syntax -error in the
code of the Programming language during its execution. For example in
normal java coding ,you need your every statement to be terminated with
semicolon(;).if you don't follow the rule, this will give you Compile-time
error.
2.Run -time Error-Run-time error are the error which arises during the
execution of a program. For example. The program runs out of the
memory, result in Run-time error.

Exceptional Hierarchy

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
59

Object Class is the base class of the exception hierarchy. Object class is the
super class of Throwable class.Throwable class is the super class of all the
exceptional class and error class. It must be noted that methods like
printStackTrace() is defined in this class. Moreover the Throwable class is
present in a package known as java.lang.

Types of Exceptions-

Exceptions in java are categorized into two. The first is known as Checked
Exception and the second is known as Un-Checked Exception as discussed
below:

1. Checked Exception-These exceptions occur during compilation of the


program. These exceptions are raised by the java compiler. They are lot of
reasons for a checked exception to occur i.e. they occurs due to invalid user
input, problem in the network connectivity database connection). This also
arises when we forget to import the packages. For Example

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
60

java.sqlexception, java.ioexception.The Exception problem can be overcome


by implementing Try-Catch block which u see in Example in exception.

2. Unchecked Exception-These exceptions occur during execution of the


program or during run time of the program. In other words, these exceptions
are raised by the JVM but never raised by the Java Compiler during
compilation of the program. For example, Dividing any number by zero is an
unchecked exception.

Why an Exception Occurs (or)

What happens when an Exception Occurs.

An exception is defined as an event when occurs leads to abnormal


termination of the program. Whenever an exception occurs, firstly an
exception object gets created on a block known as Exception Stack, which
is one of the blocks of JVM. This information to create an exception object
is forwarded by the method (in which exception has occurred) to JVM.
Moreover, this method provides detail information to the JVM. The detail
information includes Name of the exception, the description of the
exception and the location of the program at which exception has
occurred. Secondly, the job of JVM is to search for the exception handler
with in the user program. An Exception handler is defined as a code, whose
job is to handle the exception that has been generated. If user has
provided the exception handler with in the program, then JVM will execute
that exception handler, other wise the default exception handler gets
executed. If default exception handler gets executed, it prints the all the
details of exception on the console.
import java.io.*;
public class Excep{
public static void main(String args[]) throws IOException{
int a=0,b=0,c=0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter a value");
a=br.read();
System.out.println("Enter b value");
b=br.read();

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
61

c=a/b;
}
}
C:\New Folder>javac Excep.java

When the above program gets compiled, we don’t get any compile time
error. After compiling the program, if we don’t have any compile time error,
then we have to execute the java program as shown below:
C:\New Folder>java Excep
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Excep.main(Excep.java:7)
As soon as we execute the program, we see that a message is displayed.
This message is the result of execution of default exceptional handler by the
JVM. The job of the default exception handler is to display the details of the
exception to the user.
If we clearly observe the message, then we can notice that till line 6, the
program execution was normal, i.e. the program was under normal
execution. On encountering statement 7, JVM is not able to resolve the
problem, and it gets terminated from line 7 to end of the program.
But, if I want to handle this exception i.e. if I want to avoid the
abnormal termination of the program(due to raise of exception), then I have
to incorporate or include a mechanism known as Exceptional Handling
mechanism in to my program. On doing so, if there is an exception in my
program in future, then my program will not get terminated abnormally.

Thread

A Thread is nothing but part of a process. A thread is defined as a group of


statements that has its own separate path of execution. It must be noted
that each and every java program written by the user, has a thread
internally, i.e. when user is executing a java program, a thread runs
internally.
Let us write a java program, to see what is the name of the
thread that is running internally.

public class Thread1 {


public static void main(String[] args) {

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
62

System.out.println("The current thread is


"+Thread.currentThread());
}
}

When we compile the above program, we don’t get any compile time error.
But when we execute the above program , we get the following output as
shown below:

The current thread is Thread[main,5,main]

The first is name of the thread, the second is the priority and the third is the
name of the group.

public class Thread1 {


public static void main(String[] args) {
Thread t = new Thread();
System.out.println("The current thread is
"+Thread.currentThread());
System.out.println("The name of the thread is "+t.getName());
}
}

If we compile the above program, we don’t get any compile time error. But
when we execute the java program, we get the following output as shown
below:

The current thread is Thread[main,5,main]


The name of the thread is main

Program Explanation:

Thread t = new Thread();


When the above statement gets executed, an object of class Thread
gets created. The job of JVM is to assign a name to this object, value to
this thread object and the name of the group to which this thread
belongs. The value indicates the priority. The priority for thread ranges
from 1 to 10. The minimum is 1 and the maximum is 10. The default

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
63

value is 5. The third is the name of the group to which the newly
created thread belongs.

If user wants to see the detail information about a thread i.e. name of the
thread, the priority of the thread that is assigned by JVM and the name
of the group to which thread belongs, then it is possible with the help
of a method known as currentThread. This thread is a static method
which is present in a class known as Thread class. So, if we want to see
this details of newly created thread object then it is possible with the
help of the following statement as shown below:

System.out.println("The current thread is "+Thread.currentThread());

If user wants to see the name of the thread only, then it is possible with
the help of a method known as getName() , which is a method present
in a class known as Thread Class. So, if we want to see only the name
of the thread, then it is possible with the help of the following
statement as shown below:

System.out.println("The name of the thread is "+t.getName());

Creating a Thread:

If user wants to create and manage a thread, then it is possible with help of
two ways:

a. First, with the help of a class known as Thread class. i.e. we have to
create a sub class, which has to extend Thread class.
b. Secondly, with the help of an interface known as Runnable i.e. we
have to create a class that must implement this interface.

Both Thread class and Runnable interface are present in a package known as
java.lang package, which is a predefined package in Java.

First Way to create a Thread:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
64

The first way to create a thread is to create a class, which is derived from a
class known as Thread class. The steps that are involved to create a thread
by extending Thread class are:

i. Derive a sub class from class Thread


ii. Override run method
iii. Create instance of sub class
iv. Call start method of thread class

public class Thread2 extends Thread {


public void run(){
int i=1;
for(;i<=10;i++){
System.out.println(i);
}
}
public static void main(String[] args) {
Thread2 t1 = new Thread2();
t1.start();
}
}

In the above program, we are creating a class, which is extending from a


pre-defined class known as Thread class. As we know that Thread class
contains various methods. But the most important method are start() and
run(), which is used to start and run a thread. So, in our class, in order to run
a thread we have to provide the body of run() i.e. we are performing method
over riding. After writing the body of the method, we have to invoke the run
method. To invoke the run() , first we have to create an object of the sub
class in which run() method is over ridden.
After creating an object of the class, we can invoke
the run() method. But if we invoke a run() method, with the help of an object
of sub class, then a thread is not started. In other words, if we want to start a
thread, first we have to invoke the start() method. Once the start() method is
invoked by the sub class thread object, internally the start() method will
invoke run() method of the sub class and in this way the thread gets
executed. It must be noted that the start() method must not be over ridden.
If we over ride the start() method, then run() method doesn’t gets invoked. It

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
65

must be remembered that , if you want to run a thread, then it must be


invoked with the help of start() method only.

Second way to Create Thread

As I said you that, threads are created by the programmer for internal use.
The second way to create a thread is to implement an interface known as
Runnable. It must be noted that the Runnable interface is present in a
package known as java.lang package, which is considered to be default
package in Java. Runnable is the name of the interface, that consists of only
one method known as run() method. So, it is responsibility of the user is to
write the body of run() method in a class known as Implementation class. In
other words, if user wants to create a thread then, the user has to create an
implementation class for Runnable interface.

public class Threads3 implements Runnable{


public void run(){
for(int i=0;i<10;i++){
System.out.println(" Child Thread");
}
}
public static void main(String args[]){
Threads3 t3 = new Threads3();
Thread t = new Thread(t3);
t.start();
for(int i=0;i<10;i++){
System.out.println("Main Thread");
}

}
}

In the above program, we can notice that the Runnable interface consists of
only one method known as run() method. But as I said you that, if you want a
thread to be started it is mandatory that it gets started if and only if start()
method is invoked. Since, Runnable interface is not having start() method,
we are creating an object of user define thread class, and passing this object

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
66

in the constructor of the predefine Thread class, so that a connection can be


established between the user define thread class and pre defined Thread
class. Once the connection gets established between these two classes, now
we can invoke the start() method that is present in pre define Thread class,
with the help of user define thread class object.
In our example, the user define thread object is
represented by t, so iam using t object to invoke the start() method.

As it is discussed in previous topics that each and every program in Java has
a default thread known as main thread. In the above program, we have a two
threads, one is user define thread and the second is the main thread. As we
know that the priority of the main thread is 5, and the priority of the user
define thread if also 5. But during execution, the JVM will give more priority
to main thread than the user define thread i.e. first the statements present in
main thread gets executed and then the statements in run() method of user
define class gets executed. Normally, this is the output that is always
expected, but also some times it totally depends it may varied i.e. it totally
depends on the type of scheduling algorithm that is used by a system
program known as Thread Scheduler. But if you want to change the priority
of the user define thread then it is possible with the help of a method known
as setPriority() method which is present in a class known as Thread class.
Normally the priority of a thread lies between 1 to 10. 1 is said to be
minimum priority and 10 is said to be maximum priority. If user want to set
some priority to some thread , then user can write this method in the
program as shown below. It must be noted, that instead of giving the values
between 1 to 10, but if user is giving value more than 10, then an exception
by name IllegalArgumentException gets generated.

public class Threads5 extends Thread {


public void run(){
for(int i=0;i<10;i++){
System.out.println("Child Thread");
}
}
public static void main(String[] args) {
Threads5 t5 = new Threads5();
t5.setPriority(10);
t5.start();

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
67

for(int i=0;i<10;i++){
System.out.println("Main Thread");
}
}
}

In the above example, you could see they are two threads, the first is the
main thread and the second is the user defined thread. So iam setting a
value of 10, to the user define thread with the help of a method known as
setPriority () method.

Multitasking Versus Multithreading:


Multi means many. Executing several tasks simultaneously is known as
multitasking. Multitasking is also known as Process Based Multitasking. A
process based multitasking is defined as a process of executing more than
one task, where each task is a separate independent process. For example,
let us consider different tasks like Java Editor, audio player and downloading
file. While typing a program in a java editor, we can listen audio songs in an
audio player. At the same time, we can download a file from the net i.e.
when we are typing java program in the java editor, there is no disturbance
in the audio i.e. all the tasks are independent to each other. This concept is
known as Multi tasking. Multi tasking is best at Operating System Level.
Multi threading is also known as Thread Based Multitasking.
Multi threading is defined as a process of executing several tasks, where
each task is separate independent part of same program, and each
independent part is known as thread. For example, if we consider MS-Word
as an independent program, then opening of IDE is considered to be a
thread, loading of the paper is a thread, if we press Ctrl+P we get a print
window, which is also a thread, if we press Ctrl+S, we get a save window,
which is also a thread. As we can notice that, all these threads belong to the
same process. Multi threading is best at Programmatic Level.

Thread Life Cycle

A thread can be in any one of the following states as shown below:

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
68

1) New or Born
2) Ready or Runnable
3) Running
4) Waiting
5) Terminated or Dead

New State:

When ever we create a thread, it is said be in a state known as new state.


Practically, when user creates a thread with the help of new operator, then it
is said to be in new state. While in new state, a thread is considered to be
idle.

Ready or Runnable State:

After being in new state, the thread moves to Ready state or Runnable state.
Practically, when thread object invokes start() method, then thread enters
into Ready state. In this state, the thread request for Thread Scheduler,
which in turn execute thread scheduling algorithms, and the result of this
algorithm will make the thread to be allocated to CPU, for execution.

Running State:

After waiting for CPU, the thread scheduler will allocate the CPU to the
thread. This state is known as Running state. Practically, when thread object
invokes run() method, then it is said to be in Running state.

Waiting State:

During the execution of thread, if the thread is suspending current execution


for some amount of time, then it is said to be in Waiting state or Blocked
state. Practically, it happens when a thread object invokes sleep() method or
wait() method or join() method or yield() method. After completion of
waiting, the threads waits for CPU to be allocated i.e. the thread enters into
Ready state, where it waits for CPU. After some time, the CPU gets allocated,
and the thread enters into a state known as Ready state.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
69

Termination state or Dead state:

After completion of execution, the thread enters a state known as


Termination state or Dead state.

Thread Groups:

A Thread Group is defined as group that consists of several threads. In other


words, threads of a same category are kept in a common place known as
thread group. The advantage of a thread group is that we can control all
threads, with the help of a single method. The steps that are used to create a
thread group are:

ThreadGroup tg= new ThreadGroup(“Groupname”);

where

tg: ThreadGroupObject

Group Name: Name of the thread group

The above line is used to create a thread group.

class A extends Thread{


public void run(){
System.out.println("Method A");
}
}
class B extends Thread{
public void run(){
System.out.println("Method B");
}
}
public class Threads10 {

public static void main(String[] args) {

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
70

A a1 = new A();
B b1 = new B();
/* The below statement when executed creates
a thread group by name TG
*/
ThreadGroup tg = new ThreadGroup("TG");
Thread t1 = new Thread(tg,a1,"TG");
Thread t2 = new Thread(tg,b1,"TG");

/* The above two statements when executed,


create two threads
and add these two threads to this group by name TG
*/
System.out.println("Parent of tg is :"+tg.getParent());
//The above statement when executed finds parent group
System.out.println("Thread group of t1 is "+t1.getThreadGroup());
/*The above statement when executed finds
thread group of t1
*/
t1.start();
t2.start();
/* The below statement is used to know number
of threads that are active
*/
System.out.println("Number of threads that are active in a thread
group TG are :"+ tg.activeCount());
}
}

Daemon Threads:
The threads that get executed at the back ground, in order to support the
main thread are known as Daemon threads. In other words, the job of
daemon thread is to provide support for non-daemon thread. The best
example of a non-daemon thread is main thread. The various examples of
the daemon threads are Garbage Collector, Thread Scheduler etc.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
71

public class Threads11 {


public static void main(String args[]){
System.out.println ("main thread is
daemon?”+Thread.currentThread().isDaemon());
}
}

If we want to check, whether a thread is daemon or not, it is possible with


the help of a method known as isDaemon() method. This method is a
boolean method i.e. if the thread is daemon, then true is returned and if the
thread is non-daemon then false value gets returned. In the above program,
iam testing whether the main thread is daemon or not. After I execute the
program, I get answer as false. It means that the main thread is not a
daemon thread. But if I tried to change the nature of a thread i.e. as I know a
main thread is a non-daemon thread, but if I try to apply setDaemon()
method to change the thread i.e. make it daemon() then I get an exception
known as IllegalThreadStateException.

It must be noted that the priority of a daemon thread is very low i.e. 1. But, if
we want to increase the priority of a daemon thread then it is possible with
the help of a method known as setDaemon () method. For example, during
execution of the program, the main thread priority is 5 and the priority of the
garbage collector is by default 1. If JVM wants to increase the priority of
garbage collector, then it will use a method known as setDaemon () method.
But if programmer, wants to change the priority of a user define thread, then
also it is possible with the help of a method known as setDaemon() method.
The below program shows how to change the value of a user define thread:

public class Threads12 extends Thread {


public static void main(String[] args) {
Threads12 t12 = new Threads12();
t12.start();
t12.setDaemon(true);
System.out.println(t12.isDaemon());
}
}

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.
PROGRAMMING Prepared by Mir Ahmed Ali (Ali Sir),
IN JAVA UNIT I Assistant Professor of CSE, MJCET
72

When the above program gets compiled, we don’t get any compile time
error. But if the program gets executed, we get output as shown below:

Exception in thread "main" java.lang.IllegalThreadStateException


at java.lang.Thread.setDaemon(Unknown Source)
at Threads12.main(Threads12.java:7)

In the above program, we are creating a user define thread which is a thread
that is sharing the features of main thread. Since, main thread is a non-
daemon thread, the user define thread is also a non-daemon thread. And if
we try to change the value of a non-daemon thread, then it gives an
exception as shown above.

These notes are dedicated to my father Mr. Mir Farooq Ali, Professor and
Ex-Head of the Department of Mathematics (Retired), MJCET and my mom
Mrs. Arifa, Vice Principal and Junior Lecturer in Botany (Retired) Govt.
Falaknuma Junior College. If you have any doubts in this document, you
can call me on 9010149047 or mail me at [email protected],
your queries will be replied within 24 hours.

You might also like