0% found this document useful (0 votes)
4 views173 pages

Java

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

Java

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

1.

Fundamentals of Object Oriented Programming

Object oriented Paradigm:

Paradigm means Model. Object Oriented Approach is a new Model. It is used to


eliminate problems in Procedure Oriented Approach.
The languages that follow Procedure Oriented Approach are called as Procedure
Oriented Languages such as COBOL, PASCAL, and FORTRAN etc.

The languages that follow Object Oriented Approach are called as Object
Oriented Languages such as C++, JAVA, SIMULA and SMALLTALK etc.

Procedure Oriented Approach Object Oriented Approach


It mainly concentrates on problem and its It mainly concentrates on planning and
solution. So, the behavior of the system then on implementation. So, the behavior
will not know before developing the of the system will be known before
project developing the project
It is suitable for smaller project It is suitable for big or complex projects
It is unnatural It is natural
Basic Concepts of Object Oriented Programming

The basic concepts of Object Oriented Programming are

1. Class/Object
2. Encapsulation
3. Data Abstraction
4. Inheritance
5. Polymorphism
The above five concepts are also called as features of OOPS

1) Class/object:
Class:
 A class is a user defined data type.
 A class is not a physical one because no storage space created in the memory.
 A class is a set of properties and actions.
 Properties represent variables.
 Actions represents methods
 A class is a structure or model of an object
 Properties and actions both are called as members of a class.
Object:
 An object is a physical one because it allocates memory.
 An object is an instance of a class.
 An object also contains a set of properties and actions.

Here, pone and ptwo are objects to the Person Class.


2) Encapsulation:
Encapsulation is a combination of data and code.

Encapsulation = Data + Code.

Advantage: Two or more classes can contain the properties with the same
names.
name
Name :
: :
:

Person Student

Dr. V. Venkateshwarlu Page 2


3) Data abstraction:
Providing the security to the data is said to be Data abstraction. We can provide
security to the data at different levels using access specifiers.
Access specifiers: Access specifier specifies the scope of a variable.
Scope: Scope means the place or area where the member can be accessed.

4) Inheritance:
Inheritance is an extraction of new software from already existing software.
According to Java extraction of new classes from already existing classes is said to
be inheritance.

F1

F2

F3

F4

Inheritance can be achieved in Java by using a keyword extends.


Note: Java supports 3 forms of inheritance.
i) Single inheritance
ii) Multilevel inheritance
iii) Hierarchical inheritance

5) Polymorphism:
It is a Latin word. Poly means many, morphism mean actions. i.e. one thing exhibits
in many forms or one thing performs many actions.

The examples of polymorphism are method overloading, constructor overloading


and method overriding etc.

Dr. V. Venkateshwarlu Page 3


Benefits of OOP

OOP provides several benefits to both the developer and the user. It solves the many
problems in the development of software products that improves the quality. It
improves the productivity, best quality of product and reduces the cost of the product.

The benefits of OOP are

 The main advantage of class is re-usability. Once a class is provided we can


create any number of objects whose structure is same but behavior is different.
 Two or more classes can have properties with same names using Encapsulation
 Security can be provided to the data using Data Abstraction.
 Redundancy can be eliminated using inheritance.
 It is easy to partition the work in a project.
 Object-oriented systems are easily maintainable.

Applications of OOP

Large number of systems developed using OOP techniques. OOP techniques are used to
complex and big projects.

Some of the applications of OOP techniques are

Object-Oriented Databases

Decision support and Office Automation Systems

Hypertext and Hypermedia

AI and Expert Systems

Real-Time Systems

Dr. V. Venkateshwarlu Page 4


2. Java Evolution
History of Java:
In 1990’s“SUN MICRO SYSTEMS” (USA), wanted to develop software to control
“Consumer Electronic Goods”.

 This work was assigned to “Mr. James Gosling” and his team.
 James Gosling and his team were started this project by using C++ which was
introduced in the year 1983.
 After the completion of 30%, C++ was not supported. So, James Gosling and his
team were developed a new language called as “Oak” (The name of a tree which
they used to see from the window when they were developing the language).
 James Gosling and his team developed the Oak language by removing all the
complicated concepts from C++.

Oak=CPP – [Complicated Concepts of CPP]+[Ideas of James Gosling]

 He tested the Oak language on “Green Project” (*7 device), and it was
succeeded. He developed the Green project using “APPLETS” concept to get the
images. Up to 1993, “Internet” was CUI, which was turned to GUI because of Oak.
 Later, the Oak language was renamed to “JAVA”. Since “OAK” name was
registered by some other company. Java is an Island which is famous for Tea
and Coffee plants. Mr. James Gosling and his team were very fond of tea and
coffee. Hence they given a name as “Java”.
 In 1995 Sun Micro System announced Java at SunWorld conference in 1995.

Dr. V. Venkateshwarlu Page 5


There are 3 parts of java provided by “SUN MICRO SYSTEMS”.

Java SE- It is the Java Standard Edition that contains core java classes. It is used to develop
standard applets and applications.

Java EE- It is the Java Enterprise Edition that contains the classes to develop business
applications.

Java ME- It is Java Micro edition. It is used to develop code for portable devices such as
mobile phones etc.

Why Java?

In case of ‘C’

 C Compiler generate .exe files


 .exe file will be generated by the ‘C’ compiler according to the rules and
regulations of the platform.

x.c C compiler [Link] Windows+Intel

Unix+Motorola

 

Windows+Intel

The .exe file generated by ‘C’ compiler in one platform can’t be executed in different
platform.

So, C is platform dependent.

Dr. V. Venkateshwarlu Page 6


In case of Java
Java compiler generates .class files

.class file contains byte code instructions (Intermediate code)

A .class file generated in one computer can be executed in any other computer
irrespective of platform. Hence, Java is platform independent.

Java Virtual Machine (JVM): JVM is a set of programs written in ‘C’ Language.

JVM internally contains a program called “Interpreter” used to convert the byte
code to machine code line by line. Every platform has its own JVM. So, JVM converts
byte code to the platform convenient. JVM is platform dependent. Since, it is written
in ‘C’ Language.

Differences between .exe and .class files

.exe files .class files


‘C’ or C++ compiler generates .exe files Java compiler generates .class files
.exe file contains machine code .class file contain byte code
.exe files are platform dependent .class files are platform dependent
.exe files are easily effected by virus .class files can’t be effected by virus
Reason: These are batch files Reason: These are plain text files

Dr. V. Venkateshwarlu Page 7


Features of Java:
According to Sun Microsystems, Java is “Simple, Object Oriented, Compiled and
Interpreted, Secured, Robust, Platform Independent, Garbage collected, Multithreaded,
Dynamic, Extensible, High performance”.

1) Simple:
Java is Simple. Since, all the complicated concepts from C++ had been removed.

Java=CPP – [Complicated Concepts of CPP]+[Ideas of James Gosling]

2) Object Oriented:
Java is Purely Object Oriented programming language. Since, it supports all the
features of Object Oriented Approach such as
i) Class/Object
ii) Encapsulation
iii) Data Abstraction
iv) Polymorphism
v) Inheritance

**Note: Object based language: Which supports all the Object Oriented Features
except Inheritance

3) Compiled and Interpreted:


Java Compiler takes the .java file, and generates .class file. .class file contains
byte code (Intermediate code). The byte code instructions will be taken by the
interpreter present In JVM and translates to machine code line by line which is
executed by the processor. Hence, Java is both compiled and interpreted
language.
4) Platform independent:
A .class file generated in one platform can be executed in any other computer
irrespective of platform. Hence, Java is platform independent.
5) Secured:
Since the Java compiler generates .class files, .class files are plain text files and
can’t be affected by virus. Hence, Java is secured.

Dr. V. Venkateshwarlu Page 8


6) Robust:
Java programs are robust programs. Robust programs are the programs which
doesn’t cause any harm to the computer i.e., software or hardware
Reason: Exception handling.
Robustness of Java programs can be achieved by the concept of Exception
handling.
7) Garbage collector:
Garbage collector is a program that collects (deletes) unwanted data from
memory. By that, the memory can be used in an efficient manner.
8) Multithreaded:
Multi-tasking: Execution of 2 or more programs simultaneously is called as multi-
tasking.
Thread: Thread is a part of a program; a thread is also called as light weight
process. Every thread has its own way of execution. Executing 2 or more threads
of a program simultaneously is called as multi-Threading: The main aim of the
multi-threading is to reduce the CPU execution time, by that the performance will
be improved.
9) Extensible:
The functions related to C and C++ are said to be “Native methods” in Java.
Java is extended to C and C++, i.e., we can use the native methods in Java.
10) Dynamic:
In Java always memory is allocated dynamically, i.e., the memory will be allocated
at run time.
Since the memory is allocated at run time,
i) There is no wastage of memory.
ii) There is no limitation of memory.
11) High performance:
JIT compiler (Just-In-Time) improves the performance of the Java applications.

Dr. V. Venkateshwarlu Page 9


Differences between ‘C’ and Java

Java is similar to ‘C’, the difference is Java is an Object Oriented Programming


Language where as ‘C’ is a Procedure Oriented Language. Some more differences
between ‘C’ and Java are

C Java
‘C’ is a Procedure Oriented Language Java is an Object Oriented Language
It is Platform Dependent It is Platform Independent
‘C’ Compiler generates .exe files Java Compiler generates .class files
It supports the keywords sizeof, typedef It does not support the keywords sizeof,
typedef
It supports jumping statement goto It does not support goto
It support the pointers concept It does not support the pointers concept
Pre-processor statements #include, Pre-processor statements #include,
#define are available in ‘C’. #define are not available in Java
It supports structures and unions It does not support structures and unions
new and instanceof operators are not new and instanceof operators are available
available in ‘C’ in Java
Type modifiers auto, extern, register, Type modifiers auto, extern, register,
signed and unsigned are available in ‘C’ signed and unsigned are not available in
Java
Enumerations are available in ‘C’ Enumerations are also available in Java

Dr. V. Venkateshwarlu Page 10


Differences between C++ and Java

C++ Java
C++ is not a purely object-oriented Java is purely an object-oriented
programming Language, since it is possible programming language, since it is not
to write c++ programs Without using a possible to write a java program using at
class or an object least one class.

Pointers are available in C++ Pointers are not available in Java


C++ has goto statement Java does not have goto statement

Automatic casting is available in C++ In some cases, implicit type casting is


available, but is advisable that the
programmer should use casting when
required.
Multiple Inheritance is achieved in c++ No multiple inheritance in Java, it is
indirectly achieved using interfaces.

Operator overloading is available in C++. Operator overloading is not available in


Java.
#define, typedef and header files are #define, typedef and header files are not
available in c++ available in Java but there are means to
achieve them.
There are 3 access specifiers in C++: Java supports 4 types of access specifiers:
private, public and protected. private, public, protected and default.
There are constructors and destructors in Only constructors are available in Java,
C++. destructors are not available.
Allocation and de-allocation of memory is Allocation and de-allocation of memory
the responsibility of the programmer. will be taken care by JVM.

Dr. V. Venkateshwarlu Page 11


Java and Internet

Java is strongly associated with the Internet because the first application program
written in Java was HotJava, a Web Browser to run applets on internet. Internet users
can use Java to create applet programs and run them locally using Java-enabled browser
such as HotJava. They can also use a Java-enabled browser to download an applet
located on a computer anywhere in the internet and run it on his local computer.

Dr. V. Venkateshwarlu Page 12


Web Browsers

The Internet is a vast collection of information represented in many ways and stored on
many computers. A large portion of the Internet is organized as a part of World Wide
Web which uses hypertext. Web browsers are used to navigate through the information
found on the net. They allow us to retrieve the information spread across the Internet
and display it using the Hyper Text Markup Language (HTML).

Examples:

HotJava
Netscape Navigator
Internet Explorer

HotJava

HotJava is the Web Browser developed by Sun Micro System. It was the first browser to
provide support for the Java language, which makes the web more dynamic and
interactive. It is used to locate and run applet programs on Internet.

HotJava is available for the platform Windows 95, Windows NT and Windows XP and
also available for Sun Solaris.

Netscape Navigator

Netscape Navigator was developed by Netscape Communications Corporation. It is a


general purpose browser that can run Java applets. It is available for Windows 95,
Windows NT, and Sun Solaris. It has many features such as visual display about
downloading process and indication of the number of bytes downloaded etc.

Internet Explorer

Internet Explorer was developed by Microsoft. It is a popular browser available for


Windows 95, Windows NT and Windows XP. It uses Just-In-Time (JIT) compiler that
increases the speed of execution.

Note: Both Navigator and Explorer use toolbars, icons, dialog boxes and menus for easy
navigation.

Dr. V. Venkateshwarlu Page 13


Hardware and Software Requirements

Java is supported on Windows 95, Windows NT, Windows XP, Sun Solaris, MAC
and UNIX operating systems.

The minimum hardware and software requirements for Java are

Hardware requirements Software Requirements

Minimum of 8 MB Memory Operating System


Hard Disk Java Runtime Environment (JRE)
A CD-ROM Drive
A Mouse
A Standard Keyboard

JAVA ENVIRONMENT
It includes a huge number of development tools and large number of classes &
interfaces. The development tools are part of the system known as Java Development
Kit (JDK). The classes and methods are part of the Java Standard Library (JSL), also
known as Application Program interface (API).
JDK:

It is a set of tools and utilities that are used to develop Java applications.
Some of the tools are

javac : To compile a java file


java : To execute a .class file
javap : To provide information about the .class file

appletviewer : To execute java applets


javadoc : To create HTML documents

javah : For ‘C’ Header file

Dr. V. Venkateshwarlu Page 14


Process of Running the Java Application

[Link] javadoc Html File


javac
Document

javac
javac

javac
[Link] Header Files
javah

java

Output

Application program Interface

An API is also called as Java Standard Library (JSL). An API is a set of classes and
interfaces. These classes and interfaces are defined in different packages based upon
their functionality. For example all the Input-Output related classes are defined in
[Link] package. Most commonly used packages are [Link], [Link], [Link], [Link]
etc

Dr. V. Venkateshwarlu Page 15


Architecture of JVM:

1) Class Loader Subsystem:


Class loader Subsystem performs two tasks
i) Loads all the .class files
ii) Decides to store the data in different memories(5 memories)

2) JAVA Run-time areas:


i) Method area: The code related to methods will be stored at
“method area”
ii) Heap: Objects are stored at Heap.
iii) Java Stack: The results that are obtained from Java methods will be
stored at Java stack
iv) Program Counter: The address of next instruction to be executed
by processor will be stored in program counter
v) Native method stack: The result which obtained from native
methods will be stored at Native method stack.

Dr. V. Venkateshwarlu Page 16


3) Execution phase:
i) Interpreter: It takes one by one byte code instruction and translates
to machine code which will be executed by the processor.
ii) JIT compiler: It takes block of byte code instructions, translates to
machine code and place in a memory called “Hotspot”;
Hotspot: It is a memory given by the JVM to the JIT compiler for storing
the machine code instructions generated by JIT compiler.
Note: Both JIT compiler and Interpreter work simultaneously to improve
the performance of Java.
iii) Native method Library: It contains C and C++ header files.
iv) Native method interface: It takes C or C++ related header files from
native method library and gives to JVM (Interpreter/JIT) whenever
required.

Dr. V. Venkateshwarlu Page 17


3. Overview of Java Language
Keywords:

The meaning of keyword is already known to the compiler. Keywords are also called
as “Reserved words”
Ex: byte, short, int, float, final, abstract, extends, implements, package, public…..etc
Constants:

A constant is a value which never be changed. A constant is also called as literal.

Different types of constants are


i) Integer constants: It represents numbers without decimal point.
Ex: -5,-2, 0, 15, 9…etc
ii) Float constants: It represents numbers with decimal point (It allows up to 5
digits after decimal point).
Ex:-3.141, 8.909, 0.00011…etc
iii) Double constants: It also represents numbers with decimal point. It allows up
to 15 digits after decimal point.
Ex: -2.010003, 12.11772309891230955…..etc
iv) Character constants: A character may be an alphabet or it may be a special
symbol or it may be a digit. Character constants should be represented in
single quotes.
Ex: ‘A’, ‘+’, ‘5’…..etc
v) String constants: A String represents group of characters. A String constant
should be represented in double quotes.
Ex: “Venkat”, “#1-1-1/A”, “Wgl-2”, ….etc
vi) Boolean constants: A Boolean constant may be true or false.
Variables:

A variable is a name given to the memory cells or locations.


A Variable is also called as ‘Data name’. Since, a variable is a name given to the data.
A variable can store the constant (data); the value of a variable can be changed.

Example Algorithm:
a=10
b=20
c=a+b
print c

Dr. V. Venkateshwarlu Page 18


Rules for the declaration of a variable:
 Starting letter of a variable name should be an alphabet.
Ex: rno (valid) 1s (invalid).
 A variable name shouldn’t contain spaces.
Ex: emp no=1020; (invalid)
 A Variable name allows underscore.
Ex: emp_Name
 Variable name doesn’t allow special symbols.
Ex: stud-age
 A variable name may contain digits.
Ex: m1
 A variable name should not be a keyword.
Ex: public; for;

Note: Every word starting letter of a variable name should be capital except first
word.
Ex: monthlyIncome, annualIncome, rollNo, empNo etc.

Datatypes:
Data types are used for the creation of variables.

Any data type specifies 2 things.

i) How many memory cells or locations to be allocated to a variable?


ii) What type of data (constant) can be stored in a variable?

Data types are of 3 types.


i) Pre-defined data types: The data types which are defined by the “Java Soft” are
called as pre-defined data types.
Ex: int, char, float…etc
ii) Derived data types: The data types which are defined by using pre-defined data
types are said to be derived data types.
Ex: Arrays
iii) User-defined data types: The data types which are defined by the user or
programmer are said to be user-defined data types.
Ex: classes, abstract classes, interfaces….etc

Dr. V. Venkateshwarlu Page 19


PRE-DEFINED data types:
Syntax for declaration of variables:
Datatype variable1, variable2, … , variablen;

i) Integer category:
----------------------------------------------------------------------------------------------------------

Data type no. of Range


Name bytes
---------------------------------------------------------------------------------------------------------
byte 1 -128 to +127

short 2 -32768 to +32767


int 4 -2147483648 to +2147573647

long 8 -9223372036854775808 to – 9223372036854775807

Ex:

int a, b;
ii) Float category:

-----------------------------------------------------------------------------------------------------------
Data type no. of Range

Name bytes

------------------------------------------------------------------------------------------------------------
float 4 -3.4e38 to -1.4e-45 for negative values

and 1.4e-45 to 3.4e38 for positive values

double 8 -1.8e308 to -4.9e-324 for negative values


and 4.9e-324 to 1.8e308 for positive values

Ex:

float salary;

Dr. V. Venkateshwarlu Page 20


iii) Character category:

-------------------------------------------------------------------------------------------

Data type Byte Range


--------------------------------------------------------------------------------------------
char 2 0-65535

---------------------------------------------------------------------------------------------
Ex: char ch;
ASCII Range: 0-255 UNICODE Range: 256-65535
In Java character is allocated by 2 bytes since, the character variable not only store ASCII
code but also stores UNI CODE.

UNI CODE:
UNI code is a UNIVERSAL code given for the characters other than English.

iv) String category:


String up to 2 Billion Characters (Range)

String is a data type and it is also a class.


A variable declared with String data type can store String constant.

Ex: String name;


v) Boolean category:
Data type No. of Bytes Value

boolean 1 true/false
Ex: boolean response;

Giving Values to Variables


A variable must be given a value after it has been declared. This can be achieved in two
ways.
1. By using an assignment statement.
2. By using a read statement.

Dr. V. Venkateshwarlu Page 21


By using an assignment statement

A value can be given to a variable using assignment statement(=).

Syntax:
Variablename = value;
Ex:

a = 10;
b = 20;
ch = ‘A’;
Note:
A value can be given to a variable at the time of declaration called as Initialization of a
variable.
Syntax:

Datatype variablename = value;

Ex:
int rno = 5; // initialization
float avg = 75.5f; // initialization

The Java compiler always prefers the decimal value as double. To specify the declared
value is float to the compiler, we’ve to write ‘f’ after decimals.

By using a read is statement:

A value can be accepted from keyboard using readLine() method of Integer Wrapper
class which can understood in later topics.
Identifier
An identifier is a name given to a variable or a method or a class or an interface or a
package etc.

Examples: int rno; //giving a name to a variable


void areaRect(int l, int b){..} //giving a name to a method
class A{..} //giving a name to a class

Dr. V. Venkateshwarlu Page 22


Output Statement in Java:
Monitor: Standard output device ----------[Link]
[Link] ():
It is a statement used to print something on to the monitor.
Ex: [Link] (“Good afternoon”);

O/P:

Good afternoon_

Ex: [Link] (“KU”);

[Link] (“Vidyaranyapuri”);

[Link] (“HNK”);

O/P: KUVidyaranyapuriHNK_

Note: print () prints the message on the screen and the cursor remains on the same line.

[Link] ():
Prints the message and then moves the cursor to the next line.

Ex: [Link] (“Venkat”);

[Link] (“Informatics”);

Output:

Venkat

Informatics

Dr. V. Venkateshwarlu Page 23


int x = 10, y = 20;

[Link] (“Sum =”+x+y);

[Link] (“Sum =”+(x+y));

Output:

Sum =1020

Sum =30

Syntax for writing a simple Java program:

class ProgramName

public static void main (String a[])

---------

---------

main() method explains the starting and ending points of a program to the JVM.

JVM always calls first main method of a .class file.

The main method’s class name and program name should be same.

In Java it is not possible to write a program without using class. Hence, Java is purely
Object Oriented language.

Dr. V. Venkateshwarlu Page 24


Write a Java program using editor…

C :\...> cd\

C: \ > cd program files\Java\Jdk1.5.0\bin

C: \program files\Jdk1.5.0\bin\>edit [Link]

//Blue color screen…

Write a program to find sum of two numbers.

Save and Exit

C: \...bin>javac [Link]

C: \...bin>java Sum

Dr. V. Venkateshwarlu Page 25


The output of the program is

Write a program to calculate area of rectangle.

class Area{

public static void main (String a[]){

int a, l, b;

l=10;

b=20;

a=l*b;

[Link] (“Area =”+a);

Output:

Area =200

Dr. V. Venkateshwarlu Page 26


Structure of Java program:
Comments
Package declarations
Import statements
Class and Interface definitions
class ProgramName
{

public static void main (String a[])

{
--------------
--------------
--------------

Comments:

Comments improve the readability and understandability. Comments are non


executable statements. We can write any number of comments during in a single
program.
Comments are of 3 types
1. Single line comments:
Single line comments are used to write the comments meant for a single line.
Single line comments can be represented using 2 forward slashes (//).

Ex: // single line comments…

2. Multi line comments:


Multi line comments can be represented using the markers /* and */.
Ex: /* ------------------
---------------------------
---------------------------*/

Dr. V. Venkateshwarlu Page 27


3. Java documentation comments:
These comments can be represented using the markers /** and */. These
comments are used to provide description of a Java program. This description helps
in creating .html file called as API document. To create an API document we can use
a compiler called as javadoc compiler.
Ex:
 /** Description about a class */
 class A
 {
 // code for class A
 /** description about methods */
 }

Example program on Comments:


/* Program Name : [Link]
Author : Venkat
Organization : KUC
Date : 02-03-2014 */
class SimpleInt
{
public static void main(String arg[])
{
//variable declaration
double s, p, t, r;
// storing values
p=10000;
t=24;
r=3;
//calculating
s=p*t*r/100;
//Display result
[Link](“Simple Interest= “+s);
}
}

Dr. V. Venkateshwarlu Page 28


Import statements:

Application Program Interface (API):


An API is also called as Java Standard Library (JSL). An API is a set of classes and
interfaces. These classes and interfaces are defined in different packages based upon
their functionality. The class includes a set of methods. For example all the Input-
Output related classes are defined in [Link] package. Most commonly used packages
are [Link], [Link], [Link], [Link] etc.

Classes and interfaces (Java API) API

InputStreamReader |-- Packages [Link]


[Link]
BufferedReader | |

Classes String
System
[Link] | |
String
. Methods length()
.
If we use the methods of a class, the corresponding class should be imported.

Ex: import [Link];

import [Link];

(Or)
import [Link].*;
Here, * represents to import all the classes and interfaces present in the package.
By default [Link] package will be imported.

Package declaration:
We the users can create our own packages called as user-defined package.
A user defined package can be created by the programmer using the keyword
“package”

Syntax: package [Link];

Dr. V. Venkateshwarlu Page 29


Class and interface definitions:
A class is a set of methods that should be defined using the keyword “class”.
An interface is a set of incomplete methods which is defined by using the
keyword “interface”.
A class and interface should be defined after importing the statements.
class ProgramName:
If the class name and the program names are different, then there is a need to
remember a program name for the compilation and the class name which
contains the main method should be remembered for running the program.
Instead of remembering two names, the class which contains main method and
the program name are same; there is no need to remember two names.
public static void main()
void:
The main method is not returning any value. So, it should be declared as void,
main method explains the starting point and the ending point of the program to
the JVM.
The main method is called by the JVM outside the class using class name. Hence,
it should be declared as public static.

String args[] (Command Line Arguments):

The main method is called by JVM from command line. If we want to pass the
arguments to the main method, there is a need to pass the arguments from the
command line. Such a concept is called as command line arguments.

class CmdDemo{

public static void main(String args[]){

[Link](args[0]);

[Link](args[1]);

>javac [Link]

Dr. V. Venkateshwarlu Page 30


>java CmdDemo KU Wgl

Explanation:

KU is an argument stored in args[0] and Wgl is an argument stored at args[1].

Naming Conventions

It explains rules to be followed by a Java Programmer while writing the names of


packages, classes, methods, and variables etc.

 Keywords and package names are written in small letters.


public, void, static -------keywords
[Link], [Link], [Link] --- packages
 Every word of a class name and an interface name should be start with a
capital letter.
InputStreamReader, BufferedReader, String, System ---Classes
Serializable, Runnable -- Interfaces
 The first word of a method name is in small letters, then, from second word
onwards each new word should start with a capital letter.
readLine(), parseInt(), equalsIgnoreCase() -- Methods
 Variable rule is as same as method names
rno, empName, empSal --Variables
 Constants are fixed values that should be written by using all capital letters.
PI, MAX_VALUE -- public static final variables

Dr. V. Venkateshwarlu Page 31


Scope of Variables
Variables are of three types

1. Instance variables
2. Class variable(static variables)
3. Local variables

1. Instance variables:
Instance variable is declared inside a class. Instance variables are created when
the objects are instantiated. Instance variables are separate for every object.

Syntax:
class ClassName
{
Datatype variable;
:
}
2. Class Variables:
Class variable is declared inside a class using a keyword static. So, It is also called
as static variable. Class variables are common (global) to all the objects that class
creates.

Syntax:
class ClassName
{
static datatype variable;
:
}
3. Local variables:
Local variables are declared inside a method. These variables cannot be accessed
outside the method definition.

Syntax:
returntype methodName([parameters..])
{
Datatype variable;
}

Dr. V. Venkateshwarlu Page 32


Symbolic Constants:
Generally we use constants in a program. These constants may appear repeatedly in a
number of places in the program. For example the mathematical constant ‘pi’ whose
value is 3.14. We may change the value of ‘pi’ from 3.14 to 3.142 to improve the
accuracy of calculations. For this we need to change the value of constant explicitly
wherever it has been used. If any value is left unchanged, the program may produce
inaccurate results.

Symbolic constant solves the above said problem. Symbolic constant is a name
substituted for a variable. It can be declared using the keyword final. So, it is also called
as final variable. Its value cannot be changed during the execution of a program.
Syntax:
final datatype VARIABLENAME = value;

Ex:

final double PI = 3.142 ;

Note:
1. Symbolic constants are written in capital letters.
2. A value assigned to a symbolic constant cannot be changed.
An Example Program on Symbolic Constant

class FinalDemo{

public static void main(String args[]){

final int x=10;

[Link](“x = “+x);

//x=20; will not be allowed

//[Link](“x= “+x);

Dr. V. Venkateshwarlu Page 33


Type casting:
Conversion of one type of value to the other type of value is said to be type casting
(Type Conversion) for example int to float, float to double, char to int etc.
Ex:
short x = 125;
int y = x;
Here, x is source variable, y is destination variable.
Type casting is of two types.

1. Implicit type casting( Automatic conversion)


2. Explicit type casting.

Implicit type casting:


Conversion of one type of value to the other type internally by the Java compiler is
said to be implicit type casting.

Implicit type casting is possible when the following two cases are satisfied.
Case 1: Both source variable and destination variable should belongs to same
category.

Case 2: Destination variable size should be greater than source variable.

Ex:1 Ex:2
byte b = 10; long x = 10.5;
int n = b; //valid 2 cases satisfied; int y = x; /* invalid, since destination
variable size not greater than source
variable size */

Explicit type casting:


Conversion of one type of value to the other type of value externally by the
programmer is said to be Explicit type casting. This can be done in Java using cast
operator.

Ex: double d = 10.5;


int x = (int) d; // (int) is a cast operator.

Note: The cast operator and data type of destination variable should be same.

Dr. V. Venkateshwarlu Page 34


Accepting the values from Keyboard:
To accept the values from the keyboard, we need two connections.

i) Connecting Keyboard to the InputStreamReader object.


InputStreamReader ins= new InputStreamReader([Link]);
ii) Connecting InputStreamReader object to the BufferedReader object.
BufferedReader br=new BufferedReader(ins);

To read (accept) the values from the keyboard, we should use the methods of
BufferedReader.

InputStreamReader ins=new InputStreamReader([Link]);

BufferedReader br=new BufferedReader(ins);

These two steps can be written in a single line as follows

BufferedReader br=new BufferedReader(new InputStreamReader([Link]));

Note: BufferedReader, InputStreamReader are the classes present in [Link] package.

Dr. V. Venkateshwarlu Page 35


i) read():

[Link](“Enter your grade..”);

int ich=[Link]();

char ch=(char)ich;
[Link](ch);

The above two statements can be written in a single statement as follows

char ch=(char) [Link]();

Ex2:
[Link](“Enter your gender..”);

char g= (char)[Link]();

read method throws an Exception (run time error) called IOException.

ii) readLine():
[Link](“Enter your name…”);
String sname=[Link]();
[Link](“Enter your college name..”);
String cname=[Link]();

Dr. V. Venkateshwarlu Page 36


Wrapper classes:
Wrapper classes are used to convert to primitive types into object types. Wrapper
classes are contained in the [Link] package.

Data types Wrapper class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Wrapper class Byte:

Method: public static byte parseByte(String);


It is a method that converts byte value present in String format to the byte
format.
Ex1:
String n = ”25”;
byte bn = [Link](n);

Ex2: byte x = [Link](“39”);

Reason:
String value present in String format can’t be converted to byte format.

Dr. V. Venkateshwarlu Page 37


Wrapper class Short:
Method: public static short parseShort(String)
It is a method used to convert a short value present in String format to the
short format.
Ex: short n= [Link](“1234”);

Wrapper class Integer:


Method: public static int parseInt(String)
It is a method which is used to convert an integer value present in String
format to an Integer format.
Ex: String sal=”125000”;
int isal=[Link](sal);

Wrapper class Long:


Method: public static long parseLong(String)
It is used to convert a long value present is the String format to long format.
Ex: String population = “1126007761”
long l_pop= [Link](population);

Wrapper class Float:


Method: public static float parseFloat(String)
It is a method used to convert the value present in the String format to the
float format.
Ex: String area = “24.50f”;
float f_area =[Link](area);

Wrapper class Double:


Method : public static double parseDouble(String)
It is a method used to convert the value present in the String format to the
double format.
Ex: String area = “30.0455”;
double d_area = [Link](area);

Note: Parsing methods throw a NumberFormatException, if the String value does not
represent a number or numeric value.

Dr. V. Venkateshwarlu Page 38


/* Write a program to find sum of two numbers by accepting input from keyboard

Program name: [Link] */

import [Link].*;
class SumTwo
{

public static void main(String args[])throws IOException


{
BufferedReader br=new BufferedReader (new InputStreamReader([Link]));
int a, b, c;
[Link](“Enter two numbers…”);

a=[Link]([Link]());

b=[Link]([Link]());
c=a+b;

[Link](“The sum of the given two numbers is “+c);

Out put:
Enter two numbers…

10

20
The sum of the given two numbers is 30

Dr. V. Venkateshwarlu Page 39


4. Operators and Expressions
Operators in Java:
An operator is a symbol that can perform a specific operation on operands.

Operand: An operand may be a variable or it may be a constant.

Expression: An expression is a combination of operators and operands.

Ex: b=a+20;

Operands Symbol

Types of operators:
1) Arithmetic Operators (+,-,*, /, %):
The operators which are used for simple mathematical calculations are called
as arithmetical operators.

int a=10, b=3;

[Link] Operator Meaning Ex Result

1 + Addition a+b 13

2 - Subtraction a-b 7

3 * Multiplication a*b 30

4 / Division a/b 3 (quotient)

5 % Modulo a%b 1 (remainder)

Dr. V. Venkateshwarlu Page 40


2. Assignment Operator (=):
Assignment operator is used to store a value into the variable.
Syntax: variable = constant/variable/expression;

Ex: int a, b, c;
a =10; (constant)
b= a; (variable)
c=a+ b; (expression)

3. Relational Operators (<,>, ==,! =, <=,>=):


Relational operators are also called as comparison operators.
Relational operator compares two values and gives a logical value either true
or false.

Note: Relational operators and Arithmetic operators are binary operators. Since, both
operators will use two operands.

int a=10, b=20, c=10;

[Link] Operator Meaning Ex Result

1 < Less than a<b True


2 > Greater than a>b False
3 == Equals a==c True
4 != Not equal to a!=c False
5 <= Less than or Equal to a<=b True
6 >= Greater than or Equal to a>=b False

Dr. V. Venkateshwarlu Page 41


4. Logical Operators ( ll, &&,! ): Logical operators are of 3 types.
a) Logical OR (ll)
b) Logical AND (&&)
c) Logical NOT (!)

a) Logical OR (ll):
When all the conditions are false, the result will be false; otherwise the result
will be true.

b) Logical AND (&&):


When all the conditions are true, the result will be true; otherwise the result
will be false.
Logical OR and Logical AND can be understood by the following truth table.

C1 C2 C1llC2 C1&&C2
T T T T
F T T F
T F T F
F F F F

Ex:
int s1=60, s2=70, s3=30;
if (s1>=35 && s2>=35 && s3>=35)
Pass
else
Fail

The result will be fail.

If any one of the conditions is false, the total result will be false.

c) Logical NOT (!):


Logical not is used to negate a value.

C !C
T F
F T

Dr. V. Venkateshwarlu Page 42


5. Unary Operator:
Unary operator operates only on one operand. Unary operators are of 2
types.
I) Unary minus operator (-)
II) Increment/Decrement operators (++/--)

I) Unary minus operator:


Unary minus operator negates a value
Ex:
int x=10;

[Link] (-x); gives o/p as -10

II) Increment or Decrement:

These are categorized into 2 types

a) Prefix operator:

Increment or Decrement operator will be written before variable.

Pre means before.

Syntax: ++/--variable;

Again prefix operators are of 2 types

i) Pre-increment operator:

Increment operator will be written before a variable. Such type of operators are said to
be Pre-increment operators.

Syntax: ++variable;

ii) Pre-decrement operator:

Decrement operator will be written before a variable. Such type of operators are said to
be Pre-decrement operators.

Syntax: --variable;

Dr. V. Venkateshwarlu Page 43


b) Postfix operator:

Increment or Decrement operators will be written after the variable.

Syntax: variable++/--;

Postfix operators are of 2 types. Those are

i) Post-increment:

Increment operator will be written after a variable. Such type of operators are said to be
post-increment operator.

Syntax: variable++;

ii) Post-decrement:

Decrement operator will be written after the variable. Such type of operators are said to
be post-decrement operator.

Syntax: variable--;

Prefix Postfix
1)First most ++/-- 1)All operations will be first
2)Remaining all operations 2)++/--

Example for pre-increment:

int x = 10;

[Link] (++x);

O/P: 11

Example for post-increment:

int y = 10;

[Link] (y++);

O/P: 10

Dr. V. Venkateshwarlu Page 44


6. Ternary Operator (? :) Or Conditional Operator

The operator which operates on 3 operands is said to be ternary operator. First the
condition will be evaluated, if the condition is true, then value of variable1 will be stored
in variable3; otherwise value of variable2 will be stored in variable3.

Syntax:

Ex: int a=10, b=20, big;

big= (a>b)? a: b;

7. Dot (.) operator:

Dot operator is used to access the members (methods or variables) of a class.

It is also used to access the classes of package.

Ex: [Link]

8. “new” operator:

new is an operator used to allocate the memory dynamically(run time).

Student sone = new Student();

9. Comma (,) operator:

Comma operator is used to separate two or more expressions.

Ex: int a = 10, b = 20, c = 30;

10. instanceof:

It is used to check whether the object belongs to specific class or not.

If the object belongs to a class it returns true; otherwise it returns false.

Dr. V. Venkateshwarlu Page 45


11. Bitwise operators:
Any number can be represented In 2 ways.

a) Decimal number system: Decimal number system uses the digits 0-9
Ex: x=12
b) Binary number system: binary number system uses the digits 0 and 1.

Ex: x=1100
We can convert decimal number system to binary number system and vice versa.
Ex: 12 = 1 1 0 0
1X23 + 1X22 + 0X21 + 0X20
8 + 4 + 0 + 0 = 12

Definition: Bitwise operator operates only on bits i.e., (0’s and 1’s)

Types of Bitwise operators:

i) Bitwise complement (~):


It is used to negate the bits. It is also called as 1’s complement.
EX:
x=12 0 0 0 0 1 1 0 0
~x= 11110011
ii) Bitwise OR (l):
Bitwise OR can be executed using logical OR gate.
It can be understood by using the following truth table.
X Y xly
1 1 1
1 0 1
0 1 1
0 0 0
EX: x=10 0 0 0 0 1 0 1 0

y =11 0 0 0 0 1 0 1 1
.

Xl Y = 0 0 0 0 1 0 1 1

Dr. V. Venkateshwarlu Page 46


iii) Bitwise AND (&):
Bitwise AND operator is executed by using logical AND gate.
It can be understood by using the following truth table.

X Y x&y
1 1 1
1 0 0
0 1 0
0 0 0

iv) Bitwise XOR (^):


Bitwise XOR can be executed by using logical XOR gate.
It can be understood by the following truth table.

X Y x^y
1 1 0
1 0 1
0 1 1
0 0 0

EX: x=10 0 0 0 0 1 0 1 0
y = 11 0 0 0 0 1 0 1 1
.
x^y= 0 0 0 0 0 0 0 1
.
v) Bitwise Left shift (<<):
It is used to shift n bits of a value towards left side.
It can be represented as x<<n, i.e., shift the n bits of x towards left.
EX: x=10

0 0 0 0 1 0 1 0

x<<2

0 0 1 0 1 0 0 0

Empty bits should be filled with zeros.

Dr. V. Venkateshwarlu Page 47


vi) Bitwise Right shift (>>):
Bitwise Right shift operator used to shift n bits of a number towards right side.
It can be represented as x>>n, i.e., shift n bits of x towards right side.

Ex: x=10 0 0 0 0 1 0 1 0

x>>2
0 0 0 0 0 0 1 0

Example Program:
class BitsDemo
{
public static void main(String args[])
{
int x=10, y=11;
[Link](“complement of x=”+( x));
[Link](“x | y =”+(x | y));
[Link](“x & y =”+(x & y));
[Link](“x ^ y =”+(x ^ y));
[Link](“x << 2 =”+(x << 2));
[Link](“x >> y =”+(x >> y));
}
}
O/P:
complement of x=10
x | y=11
x& y=10
x ^ y =1
x<< 2=40
x>> 2=0

Dr. V. Venkateshwarlu Page 48


Arithmetic Expressions:
An arithmetic expression is the combination of operands and operators. An operand
may be a variable or it may be a constant. Some of the mathematical or algebraic
expressions and their equivalent Java expressions are given below:

Mathematical Expression Java Expression

𝑎𝑏𝑐 (a*b*c)/(x+y)
𝑥+𝑦

a = 𝜋𝑟 2 a = 3.14 * r * r

Evaluation of Expressions
Expressions are evaluated using assignment operator.

Syntax:

variable = expression;

When the statement is encountered, the expression is evaluated first and the result is
placed in the variable on the left-hand side of assignment operator.

All the variables in the expression must be assigned values before the evaluation.

Ex:

int a, b, c, d;

a = 10;

b = 5;

c = 3;

d = (a+b)/c; //d is placed with 5

Dr. V. Venkateshwarlu Page 49


Precedence of Arithmetic Operators
An arithmetic expression will be evaluated from left to right using the precedence of
operators.

High priority will be given for () % / *

Low priority will be given for + -

In general the precedence of the arithmetic operators can be written as

() -- (B) Brackets

Modulo -- (O)

Division -- (D)

Multiplication -- (M)

Addition -- (A)

Subtraction -- (S)

The word which is used to remember the precedence is “BODMAS”.


int a=2, b=3, c=10, d;
d = a+b*(c/a)+c%b;
// the value of d is 18
To evaluate the above expression the following steps takes place
Step1: 2+3*(10/2) +10%3
Step2: 2+3*5+10%3
Step3: 2+3*5+1
Step4: 2+15+1
Step5: 18

Dr. V. Venkateshwarlu Page 50


5. Decision Making Branching and Looping
Control Structures
Control structures are used to execute the statements according to the requirement of
the programmer i.e., we can branch from one location to another location; a set of
statements can be executed for more than once and etc…

The default flow of execution is every statement will be executed only once in a
sequential manner one after the other.

These are categorized into three types,

Those are

i) Branching statements
ii) Looping statements
iii) Jumping statements

Block: A block is a set of statements written in between the flower braces

i) Branching statements:
if:
When the condition is true, ‘if’ block statements will be executed otherwise
‘if’ block statements will not be executed.

Syntax:
if(condition)
{
---------
--------- if block statements
---------
}
--------
-------- Out of if block statements

Dr. V. Venkateshwarlu Page 51


Flow chart:

/* Example program on if condition


Program name: [Link]*/
import [Link].*;

class Biggest
{

public static void main(String args[])throws IOException


{

BufferedReader br=new BufferedReader new(InputStreamReader([Link]));

int a, b;
[Link](“Enter two numbers…”);

a=[Link]([Link]());
b=[Link]([Link]());

if(a>b)

{
[Link](“a is bigger…”);
}

Dr. V. Venkateshwarlu Page 52


if(b>a)

[Link](“b is bigger…”);
}
[Link](“End of the program…”);

}
}

if-else:
When the condition is true, if block statements will be executed; Otherwise else block
statements will be executed.
Syntax:

if(condition)

{
--------
--------

}
else

{
--------
--------

}
--------

--------

Dr. V. Venkateshwarlu Page 53


Flow chart:

/* Program to check whether the given number is even or odd

Program name: [Link]*/

import [Link].*;

class EvenOdd{
public static void main(String args[])throws IOException

{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));

int n;

[Link](“Enter any value…”);


n=[Link]([Link]());
if(n%2==0)

{
[Link](“ given number is even…”)
}

Dr. V. Venkateshwarlu Page 54


else

[Link](“given number is odd…”);


}
}

Nested if:
An if block present in the else block of the another if block is said to be Nested if
Syntax:

Dr. V. Venkateshwarlu Page 55


Flow chart:

Note:
When all the conditions are false then else-block (default) statements will be executed.

Default statements are represented using StatementsX in flow chart.

switch case:
Syntax:
switch(var)

{
case 1:

Statements 1;

break;
case 2:
Statements 2;

Dr. V. Venkateshwarlu Page 56


break;

-----

------
default:
default statements;

The ?: Operator
?: is a Conditional Operator and is also called as Ternary Operator. The operator which
operates on 3 operands is said to be ternary operator. First the condition will be
evaluated, if the condition is true, then value of variable1 will be stored in variable3;
otherwise value of variable2 will be stored in variable 3.

Dr. V. Venkateshwarlu Page 57


Syntax:

Ex: int a=10, b=20, big;

big= (a>b)? a: b;

Example Program:

class CondOptDemo
{

public static void main(String args[])


{

int a = 10, b = 20, big;


big = (a > b) ? a : b ;

[Link](“Biggest number: “+big);

}
}

ii) Looping statements:


Executing a statement or set of statements for more than one time is called as
looping statements. Looping statements are also called as Iterative
statements.

For:
The statements in the “for” block will be executed until the condition gets
false. It is an entry control loop because condition is checked before entering
into the loop.
Initialization will be executed only once where as condition, updation will be
executed for more than once.

Dr. V. Venkateshwarlu Page 58


The initialization expression initializes the loop; it’s executed once, as the loop
begins. When the condition expression evaluates to false, the loop
terminates. The updataion/modification expression is invoked after each
iteration through the loop; it is perfectly acceptable for this expression to
increment or decrement a value.

Syntax:
for(initialization; condition; updation)
{
-----------
-----------
}
---------
---------

Flow chart:

Dr. V. Venkateshwarlu Page 59


Example Program: To print a message for 5 times.

Example Program 2: To print the natural numbers from 1 to n.

Output of this program is:

Dr. V. Venkateshwarlu Page 60


While-loop:
The purpose of while loop is same as that of for loop i.e. to execute the
statements repeatedly until the condition gets false. The only difference is
their style of execution and syntaxes are different.
The while loop is an entry controlled loop because condition is checked
before entering into loop.

Syntax:
initialization
while(condition)
{

----------
----------
----------
updation;
}
----------
----------

Example Program 1
Write a program to print even numbers from 1 to n:

Output:

Dr. V. Venkateshwarlu Page 61


do-while-loop:
The do-while loop is exactly like the while loop, with one difference. In the
while loop, condition is checked before entering into the loop, where as in the
do-while loop, condition is checked after the statements in the loop are
executed. Hence, the statements in the do-while executed at least once even
then the condition is false first time. The loop is executed as long as the
condition remains true and it terminates when it gets false.
The do-while loop is exit controlled loop because the condition is checked
after executing the statements at the bottom of the loop.

Syntax:

Dr. V. Venkateshwarlu Page 62


Flow chart:

Write a program to check whether given number is Armstrong or not.

Dr. V. Venkateshwarlu Page 63


Output:

Differences between while and do-while


while do-while
It uses only one keyword while. It uses two keywords(do and while)

It is an entry control loop. It is an exit control loop.

It checks the condition before executing It execute the block before checking the
the block of while statement. condition.

Syntax:
init; Syntax:
while(condition) init;
{ do
---- {
---- -----
updation; -----
} updatation;
}while(condition);

; (semi-colon) is not required after ; (semi-colon) is required after condition.


condition.

While block statements will be executed do while block statements will be


only if the condition is true executed atleast once independent of
whether the condition is true or false.

Dr. V. Venkateshwarlu Page 64


Example Program: Example Program:
class WhileDemo class DoWhileDemo
{ {
p s v m(String args[]) p s v m(String agrs[])
{ {
int i=10; int i=10;
while(i>=20) do
{ {
[Link](“Hello); [Link](“Hello”);
i++; i--;
} }while(i>=20);
[Link](“Thank u”); [Link](“Thank u”);
} }
} }
Output: Output:
Thank u Hello
Thank u

Nested for:
A for block written within another for block is said to be nested for

Program to print the given numbers 1 2 3 as


123
123
123

Dr. V. Venkateshwarlu Page 65


If there is no nested for loops, then the program should be written as,

The program should be written as follows by using the nested for loops

Output:

Dr. V. Venkateshwarlu Page 66


iii) Jumping control statements:
a) break:
break is a statement and also a keyword that terminates the switch block.
All loops execute the statements repeatedly until the condition specified gets
false. But, in some situations we want to exit from the loop before the actually
the loop terminates. This can be achieved using break statement.
break is a statement that terminates the loop before the condition gets false.
Syntax:
break;
Write a program to demonstrate break statement.

Output:

b) Continue:
In a loop, if the condition specified evaluates to true then all statements in the
loop executes and when it reaches to the end of loop then control goes back to
the condition. But in some situations, after executing few statements in the loop

Dr. V. Venkateshwarlu Page 67


the controller should be passed to the condition. This can be achieved using
continue statement.
continue is the statement when it is executed the controller (JVM) jumps to the
next iteration. So that the statements after continue will not be executed. When
the condition gets false loop terminates.

Example program on continue:

Output:

Dr. V. Venkateshwarlu Page 68


6. Classes, Objects and Methods
Languages are of two types.

i) Procedure oriented languages:


The language that follows procedure oriented approach is called as
procedure oriented language.
ii) Object oriented language:
The language which follows object oriented approach is called as object
oriented language.
Procedure oriented approach:

 It mainly concentrates on problem and its solution.

So, the behavior of the system will not know before developing the project.

 It is suitable for smaller projects


 It is unnatural

The above problems can be solved by using the new approach called as object
oriented approach.

Object oriented approach:


 It mainly concentrates on planning and implementation.
So, the behavior of the system will be known before developing the project.
 It is suitable for big or complex projects
 It is natural

As a part of object oriented approach there are five features.


1) Class/object
2) Encapsulation
3) Data Abstraction
4) Inheritance
5) Polymorphism

Any language that supports these five features is called as an object oriented
language.
Ex: C++, Java, SIMULA etc…
Any language that supports all the features of OOPS except Inheritance is said to be
Object based language.

Dr. V. Venkateshwarlu Page 69


Class/object:
Class:
A class is a user defined data type. A class is not a physical one because no storage
space created in the memory. A class is a set of properties and actions. Properties
represent variables, Actions represents methods. A class is a structure or model of
an object. Properties and actions both are called as members of a class.

A class can be defined as


class ClassName
{
//Properties
//Methods
}
Property (Field) Declaration
A property is declared in the same way as we declare a local variable. Properties are
declared inside the body of the class definition. These variables are called as instance
variables because they are created whenever an object of a class instantiated.

class Person
{
String name;

int age;

}
Methods Declaration:

A class with only data fields without methods that operate on that data has no life.
Methods are declared inside the body of the class but immediately after the declaration
of instance variables.
A method contains two parts
1. Method Prototype
2. Method Body

1. Method Prototype: It specifies the name of the Method (method name), the type
of the value it returns (return type) and no. of parameters.

Dr. V. Venkateshwarlu Page 70


2. Method Body: It consists of a group of statements which contains logic to
perform the task. Method body is written in between “{ }”

Syntax:
returntype methodName([parameters list..]) //method prototype
{
//method body

}
Ex:

void talk() //method with no parameters


{

//code
}

Defining a class with fields and methods

class Person
{
//properties
String name;
int age;
//actions
void talk()
{
[Link](“I am “+name);
[Link](“My age is “+age);
}

Dr. V. Venkateshwarlu Page 71


Object:
An object is a physical [Link] object is an instance of a [Link] object also
contains set of properties and actions.
The general format to create an object
ClassName ref = new ClassName();

Creating the objecs


Person pone = new Person();
Person ptwo = new Person();

Note: pone, ptwo are reference variables referring to Person class objects.

The main advantage of classes is re-usability.

Dr. V. Venkateshwarlu Page 72


Accessing class members
The members of a class can be accessed inside the class directly and can be
accessed outside the class using reference variable (object) name and dot.

Example
[Link]=”Raj”; //accessing instance variables outside the class
[Link]=25;
[Link](); //accessing instance method outside the class

Relationship between class and object:

Once a class is provided, we can create any number of objects whose structure is
same but behavior is different. A class is of no use without creation of an object.
No objects can be created without using class.

An example program that demonstrates class and object:


//[Link]
class Person
{
//properties
String name;
int age;
//actions
void talk()
{
[Link](“I am “+name);
[Link](“My age is “+age);
}
}

//[Link]
class PersonDemo
{
public static void main(String agrs[])
{
Person pone, ptwo;
pone=new Person();
ptwo=new Person();
[Link]=”Raj”;

Dr. V. Venkateshwarlu Page 73


[Link]=25;

[Link]=”Ravi”;
[Link]=28;

[Link](“pone reference number = “+[Link]());


[Link](“ptwo reference number = “+[Link]());

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

>javac [Link]
>javac [Link]

Ex:2
//[Link]
class Book
{
int bpages;
String bname;
void setBook(int bp,String bn)
{
bpages=bp;
bname=bn;
}
void getBook()
{
[Link](bpages+”\t”+bname);
}
}

//[Link]
class BookDemo
{
public static void main(String args[])
{
Book bone;
bone=new Book();

Dr. V. Venkateshwarlu Page 74


[Link](222,”Java”);
[Link]();
}
}

>javac [Link]
>javac [Link]
>java BookDemo
222 Java

Dr. V. Venkateshwarlu Page 75


Encapsulation:
Encapsulation is a combination of data and code.

Encapsulation = Data + Code.

Advantage: Two or more classes can contain the properties with the same
names.
name
Name :
: :
:

Person Student
1)
Data abstraction:
Providing the security to the data is said to be Data abstraction. We can provide
security to the data at different levels using access specifiers.
Access specifiers: Access specifier specifies the scope of a variable.
Scope: Scope means the place or area where the member can be accessed.

We have 4 types of access specifiers in Java.


i) private
ii) public
iii) protected
iv) default

Syntax to declare variable using access specifier:

access_specifier datatype variablename = [value];

Syntax to declare method using access specifier:


access_specifier returntype methodName([parameters..])
{

//code
}

Dr. V. Venkateshwarlu Page 76


private members can be accessed within the same class in which they are
declared. i.e., private members can’t be accessed outside the class.

protected, default, public members can be accessed in the same class in which
they are declared and can also be accessed outside the class.

Inheritance:
Inheritance is an extraction of new software from already existing software.
According to Java extraction of new class from already existing class is said to be
inheritance.

F1

F2

F3

F4

Inheritance can be achieved in Java by using a keyword extends.


Note: Java supports 3 forms of inheritance.
iv) Single inheritance
v) Multilevel inheritance
vi) Hierarchical inheritance

Polymorphism:

It is a Latin word. Poly means many, morphism mean actions. i.e. one thing exhibits
many actions.
The examples of polymorphism are method overloading, constructor overloading,
method overriding, etc.

Dr. V. Venkateshwarlu Page 77


Initializing the properties of an object:
Method1:
class Person
{
//properties
String name=”Yakoob”;
int age=22;
//actions
void talk()
{
[Link](“I am “+name);
[Link](“My age is “+age);
}
}
class PersonDemo
{
public static void main(String args[])
{
Person pone, two;
pone=new Person();
ptwo=new Person();
[Link]();
[Link]();
}
}
In this method every object will be initialized with some value.

Method 2:
Constructor:

 Constructor is a special method that has the same name as that of class
name.
 Constructor is used to initialize the properties of an object.
 Constructor shouldn’t have any return type(even we shouldn’t write void).
 Constructor is automatically executed during the creation of an object. i.e.,
execution of a constructor and object creation will be done at same time.

Dr. V. Venkateshwarlu Page 78


class A //[Link]
{
A()
{
[Link] (“Constructor of A…”);
}
}
class UseA // [Link]
{
public static void main(String args[]){
A aone = new A();
A atwo = new A();
}
}

Zero argument constructor:


Constructor with no parameters is said to be zero argument constructor.

class Book{
int bpages;
String bname;
Book(){
bpages=100;
bname=”Java”;
}
public void getBook(){
[Link](“bpages+”\t”+bname);
}
}
class UseBook{
public static void main(String args[]){
Book bone, btwo;
bone=new Book();
btwo=new Book();
[Link]();
[Link]();
}
}
Dr. V. Venkateshwarlu Page 79
Note: In zero argument constructors every object is initialized with the same values.
Parameterized constructor:
Constructor may have parameters called parameterized constructor.

A constructor may have any number of parameters.

class Book
{
int bpages;//instance variable
String bname;//instance variable
Book(int bp, String bn)
{
bpages=bp;
bname=bn;
}
public void getBook()//instance method
{
[Link](bpages+”\t”+bname);
}
}
class useBook
{
public static void main(String args[])
{
Book bone, btwo;
bone=new Book(111, “Java”);
btwo=new Book(222, “C++”);
[Link](“Books details..”);
[Link]();
[Link]();
}
}
Note: Every object is initialized with different values.
Output:
Books details
111 Java

222 C++

Dr. V. Venkateshwarlu Page 80


Default constructor:
If no constructor is provided in .java file, the java compiler adds a zero argument
constructor to the .class file called as default constructor.

Default constructor initializes default values as follows


byte ---- 0 float ----0.0f char --- null character bolean --- false
short --- 0 double --- 0.0 String --- null

int -------0 reference --- null

long -----0

Book
//no constructor

javac

[Link]
//zero argument constructor
(Or) default constructor.

class Book{
int bpages;// instance variable
String bname;//instance variable
// no constructor provided
public void getBook(){
[Link](bpages+”\t”+bname);
}
}
class UseBook{
public static void main(String args[]){
Book bone=new Book();
[Link](“Book details..”);
[Link]();
}
}

Dr. V. Venkateshwarlu Page 81


Output:

Book details..

0 null

javap: It is a command that provides information about .class file such as properties,
constructors, methods prototypes etc…
Ex:>javap Book

Compiled from “[Link]”


class Book extends [Link]
{
int bpages;
[Link] bname;
Book(); //default constructor provided by java compiler
public void getBook()
}

Constructor overloading:
Constructor overloading is a concept in which we can provide two or more constructors
with different signature. i.e., number of arguments or type of the arguments will be
different. The general syntax is as given below

class A
{
A()
{
//code
}
A(int n)
{
//code
}
}

Dr. V. Venkateshwarlu Page 82


class Book
{
int bpages;
String bname;
Book()
{
bpages=111;
bname=”Java”;
}
Book(int bp, String bn)
{
bpages=bp;
bname=bn;
}
public void getBook()
{
[Link](bpages+”\t”+bname);
}
}
class UseBook
{
public static void main(String args[])
{
Book bone=new Book();
Book btwo=new Book(222, “C++);
[Link](“Books details..”);
[Link]();
[Link]();
}
}

Output:
Books details..
111 Java

222 C++

Dr. V. Venkateshwarlu Page 83


Copy constructor:
Copy constructor initializes the value of one object to the other object.

Copy constructor contains the parameter of same class.

class Book{
int bpages;
String bname;
Book()
{
bpages=111;
bname=”Java”;
}
Book( Book b)
{
bpages=[Link];
bname=[Link];
}
public void getBook()
{
[Link](bpages+”\t”+bname);
}
}
class UseBook
{
public static void main(String args[])
{
Book bone=new Book();
Book btwo=new Book(bone);
[Link](“Books details..”);
[Link]();
[Link]();
}
}
Output:

Books details..
111 Java

111 Java

Dr. V. Venkateshwarlu Page 84


Static Members:

Static members are of 2 types,


1) Static variables
2) Static methods
Static variables: A variable which is declared as static is called as static variable.
 Static variables are allocated before the creation of an object. Hence, static
variables are also called as class variables.
 Static variables are common to all the objects of same class.
 Static variables are created outside the object.
 The variables which are not declared using the keyword static are called as non-
static variables.
 Non-static variables allocates the memory at the time of creation of an object
(instance); hence, non-static variables are called as instance variables.
 Instance variables are separate for every object.
 Instance variables can be accessed outside the class using reference variable
name and . (dot)
 public static variables can be accessed outside the class using class name and .
(dot)

Example program:

class A
{
int x;
static int y;
public void setValues(int a, int b)
{
x=a;
y=b;
}
public void showValues()
{
[Link](“Instance variable x: “+x);
[Link](“Static variable y: ”+y);
}
}

Dr. V. Venkateshwarlu Page 85


[Link]

class StaticVarDemo
{
public static void main(String args[])
{
A aone=new A();
A atwo=new A();
[Link](10,20);
[Link](“aone…”);
[Link]();
[Link](“atwo…”);
[Link]();

A.y=100; //public static variable can be accessed using class name and .
[Link](“After changing…”);
[Link](“aone…”);
[Link]();
[Link](“atwo…”);
[Link]();
}
}

Out put:
>javac [Link]
>javac [Link]
>java StaticVarDemo
aone…
Instance variable x: 10
Static variable y: 20
atwo...
Instance variable x: 0
Static variable y: 20
After changing…
aone…
Instance variable x: 10
Static variable y: 100
atwo…
Instance variable x: 0
Static variable y:100

Dr. V. Venkateshwarlu Page 86


A y: 20 100

x 10 x 0
: :

aone atwo

Static methods:

 The methods that are declared using the keyword static are said to be static
methods.
 Static method allocates the memory before the creation of an object
 Static methods are common to all the objects.
 public static methods can be accessed using the class name and . (dot).
 The methods that are not declared using the keyword static are called as non-
static methods (Instance methods).
 Non-static methods are created during the creation of an object (instance);
Hence, non-static methods are called as instance methods.
 Instance methods can be accessed outside the class using reference variable
name and . (dot).
 Static methods can access only static variables, whereas instance methods can
access both static variables and instance variables.

Dr. V. Venkateshwarlu Page 87


class A1
{
int x;
static int y;
public void setValues(int a, int b)
{
x=a;
y=b;
}
public void showValues()
{
[Link](“Instance variable x: “+x);
[Link](“Static variable y: ”+y);
}
public static void dispValues()
{
[Link](“static variable y : “+y);
}
}

public class StaticMthDemo


{
public static void main(String args[])
{
A1 aone =new A1();
[Link](100,200);

[Link](“aone using show..”);


[Link]();

[Link](“aone using display..”);


[Link]();

[Link](“using class name A1..”);


[Link]();
}
}

Dr. V. Venkateshwarlu Page 88


Inheritance:
Extraction of a class from another class is said to be inheritance.

The main advantage of inheritance is re-usability.

There are 6 forms of inheritances.

1. Single inheritance:
Extraction of a class from single super class is said to be single inheritance.

2. Multiple inheritance:
Extraction of a single class from two or more parent classis is said to be multiple
inheritance.

Dr. V. Venkateshwarlu Page 89


3. Multilevel inheritance:
Extraction of a class from another sub class is said to be multilevel inheritance.

4. Hierarchical inheritance:
Extraction of two or more classes from a single super class is said to be hierarchical
inheritane.

5. Hybrid inheritance:
Combination of two or more types of inheritances is said to be hybrid inheritance.

Dr. V. Venkateshwarlu Page 90


6. Multipath inheritance:
Extraction of a class from two classes, that have been extracted from a common
super class.

Note: Java support only 3 forms of inheritance.


1) Single inheritance
2) Multilevel inheritance
3) Hierarchical inheritance.

Dr. V. Venkateshwarlu Page 91


 Java doesn’t support multiple inheritance, hybrid inheritance, multi path
inheritance. Since there is a chance of getting “ambiguity” error.
 C++ supports all 6 forms of inheritances. Since ambiguity error can be solved
using virtual base class.
1) Single inheritance:
class Student{
int rno;
String name;
public void setStud( int r, String n)
{
rno=r;
name=n;
}
public void getStud()
{
[Link](rno+”\t”+name);
}
}
class Marks extends Student{
int s1,s2;
public void setMarks( int m1, int m2)
{
s1=m1;
s2=m2;
}
public void getMarks()
{
[Link](s1+”\t”+s2);
}
}
class StudDemo{
public static void main(String args[]){
Marks sone=new Marks();
[Link](1, “Venkat”);
[Link](“student details..”);
[Link](90,80);
[Link]();
[Link]();
}
}

Dr. V. Venkateshwarlu Page 92


2) Multilevel inheritance:
Both the Student class and Marks classes are as same as in the above
application.
class Student
{
//code
}
class Marks extends Student
{
//code
}
class Result extends Marks
{
int tot;
double avg;
public void cal()
{
tot=s1+s2;
avg=tot/2;
}
public void getResult()
{
[Link](tot+”\t”+avg);
}
}
class MulLevelInhDemo
{
public static void main(String args[])
{
Result rone=new Result();
[Link](1,”Kalam”);
[Link](99,90);
[Link]();
[Link](“student details….”);
[Link]();
[Link]();
[Link]();
}
}

Dr. V. Venkateshwarlu Page 93


3) Hierarchical inheritance:

class Student{
//code
}
class InterOne extends Student {
public void setInterOne(int m1, int m2){
s1=m1;
s2=m2;
}
public void getInterOne() {
[Link](s1+”\t”+s2);
}
}
class InterTwo extends Student{
int s1,s2;
public void setInterTwo(int m1, int m2) {
s1=m1;
s2=m2;
}
public void getInterTwo() {
[Link](s1+”\t”+s2);
}
}
class HiInhDemo{
public static void main(String args[]){
InterOne ione=new InterOne();
InterTwo itwo=new InterTwo();
[Link](1, “Hanan”);
[Link](17,18);
[Link](2, “Venkat”);
[Link](19,20);
[Link](“Students details..”);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

Dr. V. Venkateshwarlu Page 94


[Link]:

Every class in Java is direct or indirect sub class of [Link] class.


(Or)
[Link] class is direct or indirect super class of every class in Java.

[Link]

Student

Marks

Relationship between super class and sub class:

Animals
//method applicable to all animals

Cat Dog
//methods specific to Cat //methods specific to Dog

Cat c=new Cat(); Dog d = new Dog();


Animal a1,a2;

a1=new Cat(); (1) a2=new Dog(); (2)


A Cat object is created and it can be A Dog object is created and it can be
Seen like an Animal. Seen like an animal.

Animal a3=new Student(); (3)/* Invalid,


Since, Student is not a sub class of Animal */

From (1), (2), (3)


A reference variable of super class can refer only to its sub class object.

Dr. V. Venkateshwarlu Page 95


Cat c1;
c1=new Animal(); (4)
//Animal object can’t be seen like a Cat.

Dog d1;
d1=new Animal(); (5)
//Animal object can’t be seen like a Dog.

From (4), (5)


The reference variable of sub class can’t refer to its super class object.

From (1)(2)(3)(4) and (5)


A reference variable of super class can refer to its sub class object but vice versa is not
possible.

[Link] o;
o=new Student();
o=new Person();
o=new Cat();

Note: A reference variable of a [Link] class can refer to any class object.
Since, [Link] class is directly or indirectly super class of every class in Java.

Dr. V. Venkateshwarlu Page 96


Method overloading:

It is a concept in which two or more methods having same names with different
signature. i.e., number of arguments should be different or data types of the arguments
should be different.

 Method overloading is an example of polymorphism.

class Adds
{
public void sum(int x, int y)
{
[Link](“Sum of 2 integers is: “+(x+y));
}
public void sum(int x, int y, int z)
{
[Link](“ Sum of 3 integers is : “+(x+y+z));
}
public void sum(float x, float y)
{
[Link](“Sum of 2 floats is :”+(x+y));
}
}
class MethodOverLoadDemo
{
public static void main(String args[])
{
Adds a= new Adds();
[Link](10.5f, 12.5f);
[Link](10,20);
[Link](10,20,30);
}
}
Output:

Sum of two floats is: 31.0


Sum of two integers is: 30
Sum of 3 integers is: 60

Dr. V. Venkateshwarlu Page 97


Method overriding:
 Method overriding means both the super class method and sub class methods
having the same name with same signature. i.e, number of parameters and types
of parameters should be same.
 Method overriding is allowed only in inheritance
 When overriding occurs in inheritance, the super class method will be hidden by
sub class method. So that, we can access only the sub class method but not the
super class method.
 Method overriding is an example of Polymorphism.

Example Program:
class Parent{
public void show()
{
[Link](“show of parent…”);
}
}
class Child extends Parent{
public void show()
{
[Link](“show of child…”);
}
public void display()
{
show();
show();
}
}
class OverrideDemo{
public static void main(String args[])
{
Child c=new Child();
[Link]();
}
}
Output:
show of Child…
show of Child…

Dr. V. Venkateshwarlu Page 98


The above problem can be solved by using the keyword super.
Syntax: [Link]([arg1, arg2, arg3….])

Note: Re-compile & Re-execute the above app by doing the following changes
public void display()
{
[Link]();
show();
}
Output: show of Parent…
show of Child…

Keyword final:

final keyword using with a variable: A variable which is declared as final whose value
never be changed once assigned.

Class FinalDemo{
public static void main(String args[]){
final int x=10;
[Link](“x = “+x);
//x=20; will not be allowed
//[Link](“x= “+x);
}
}
final keyword using with a method: A method which is declared as final can’t be
overridden in sub classes.

class P{
public final void show()
{
[Link](“show method of P…”);
}
}
class C{
/* public void show() // final method can’t be overridden.
{
[Link] (“show method of C…”);
} */
}

Dr. V. Venkateshwarlu Page 99


final keyword using with a class: A class which is declared as final can’t be inherited
into sub classes i.e., sub classes can’t be created for final classes

final class Super


{
//code
}
/* class Sub extends Super */ // final class can’t be extended

Keyword super( Explicit calling of super class constructor):

A super keyword is used to call super class constructor from sub class constructor.
super should be the first statement in the sub class constructor.

class A{
int a;
A(int x)
{
a=x;
}
public void showA()
{
[Link](“a= “+a);
}
}
class B extends A
{
int b;
B(int x,int y)
{
super(x);
b=y;
}
public void showB()
{
[Link](“b= “+b);
}
}

Dr. V. Venkateshwarlu Page 100


class SuperDemo
{
public static void main(String args[])
{
B bone=new B(10,20);
[Link]();
[Link]();
}
}

A sub class constructor implicitly calls a super class constructor when they have no
parameters.

class A
{
A()
{
[Link](“Constructor of A”);
}
}
class B extends A
{
B()
{
[Link](“Constructor of B”);
}
}
class Demo
{
public static void main(String args[])
{
B b=new B();
}
}

Output:
Constructor of A
Constructor of B

Dr. V. Venkateshwarlu Page 101


Keyword this: “this” is a keyword refers to the presently using object. It is used to
access the instance variable inside the block, when the instance variable name and local
variable having same names.

Ex:

class A
{
int x; //instance variable
public void setV(int x)
{
this.x=x;
}
public void getV()
{
[Link](“x= “+x);
}
}
class ThisDemo
{
public static void main(String args[])
{
A a=new A();
[Link](10);
[Link]();
}
}

Output:

X=10

Dr. V. Venkateshwarlu Page 102


Abstract classes
Complete method:
A method with code is said to be a complete method.
Ex: public void sum(int x, int y)
{
-----
-----
}

Incomplete method:
A method without code is said to be an incomplete method.
Ex: public abstract void sub(int x, int y);
Incomplete method should be declared as abstract such a method is said to be
abstract method.

Complete class:
 A class with all complete methods is said to be complete class.
 Complete class is also called as “concrete class”
 Object can be created to the complete class.

Incomplete class:
 A class that contains at least one incomplete method is called as incomplete
class.
 Incomplete class should be declared as abstract. Such a class is also called as
abstract class.
 Objects can’t be created to the abstract class, but reference variables can be
created.
 Abstract classes are used to extended into sub classes.
 The sub class has a responsibility to provide the code for all the incomplete
methods of an abstract classes, otherwise the sub class also becomes an abstract
class
 The objects that have the same requirement will be provided as complete
methods.
 The objects that have the different requirement will be provided as in complete
methods.

Dr. V. Venkateshwarlu Page 103


Ex: [Link]
public abstract class Car
{
public void fuelTank()
{
[Link](“Fill the fuel into the tank…”);
[Link](“Drive the car now…”);
}
public abstract void steering();
public abstract void breaking();
}

[Link]
public class Maruthi extends Car
{
public void steering()
{
[Link](“Maruthi uses normal steering…”);
}
public void breaking()
{
[Link](“Maruthi uses gas breaking…”);
[Link](“Apply breaks to stop the car…”);
}
}

[Link]
public class Santhro extends Car
{
public void steering()
{
[Link](“Santro uses power steering…”);
}
public void breaking()
{
[Link](“Santro uses hydralic breaks…”);
[Link](“Apply breaks to stop the car…”);
}
}

Dr. V. Venkateshwarlu Page 104


[Link]

public class UseCar


{
public static void main(String args[])
{
Car m,s;
m=new Maruthi();
s=new Santhro();

[Link](“Maruthi…”);
[Link]();
[Link]();
m. breaking();
[Link](“-------------------------“);
[Link](“Santhro…”);
[Link]();
[Link]();
[Link]();
}
}

>javac *.java
>java [Link]
Maruthi…
Fill the fuel into the tank..
Drive the car now…
Maruthi uses normal steering…
Maruthi uses gas breaking…
Apply breaks to stop the car…
-------------------------
Santhro…
Fill the fuel into the tank..
Drive the car now…
Manthro uses power steering…
Santhro uses hydralic breaking…
Apply breaks to stop the car…

Dr. V. Venkateshwarlu Page 105


Interfaces
 An interface contains only abstract methods. i.e., Incomplete methods (methods with no
code).
 An interface may have 0 or more abstract methods which are all public and abstract by
default.
 An interface can have variables which are public static and final by default. This means
all the variables of the interface are constants.
 We cannot create an object to an interface, but we can create a reference variable.
 All the abstract methods of an interface should be implemented in its implementation
classes. If any method is not implemented, then that implementation class should be
declared as “abstract”.
 A reference variable of an interface can refer to its implemented class objects.
 Multiple inheritances can be achieved in java indirectly by using interfaces. i.e., a class
can implement multiple interfaces.

Example Application on Interface:

// [Link]

interface InterOne

void sq(int n);

void cube(int n);

//[Link]

class IntImp implements InterOne

public void sq(int n)

[Link](“Sqaure = ”+(n*n));

Dr. V. Venkateshwarlu Page 106


public void cube(int n)

[Link](“Cube= ”+(n*n*n));

//[Link]

class DemoApp

public static void main(String args[])

IntImp i=new IntImp();

[Link](5);

[Link](5);

>javac [Link]

>javac [Link]

>javac [Link]

>java DemoApp

Square = 25

Cube = 125

Dr. V. Venkateshwarlu Page 107


Extending Interfaces:

An interface can extend another interface. The following diagram demonstrates

Shapes is a class implemented of Square interface which is extended from Rectangle


i.e. Shapes is direct implemented class of Square and indirect implemented class of Rectangle.
Hence Shapes as a responsibility to implement the code for both the methods of Rectangle and
Square interfaces.

//[Link]
public interface Rectangle
{
void areaRect(int l, int b);

//[Link]
public interface Square extends Rectangle
{
public void areaSq(int s);

Dr. V. Venkateshwarlu Page 108


//[Link]
public class Shapes implements Square
{
public void areaRect(int l, int b)
{
[Link](“Area of Rectangle: “+ (l * b) );
}
public void areaSq(int s)
{
[Link](“Area of Square: “+ (s * s) );
}
}
public UseShapes
{
Public static void main(String args[])
{
Shapes sh = new Shapes();
[Link](10, 5);
[Link](6);
}
}

>javac [Link]
>javac [Link]
>javac [Link]
>javac [Link]
Area of Rectangle: 50
Area of Square: 36

Can Java support multiple inheritance? Justify?

 Java cannot support multiple inheritance. i.e., two or more classes cannot be extended.
 Multiple inheritance can be supported by java indirectly using interfaces.
 Multiple interfaces can be implemented by a single class. i.e., two or more interfaces can
be implemented by a single class.

Dr. V. Venkateshwarlu Page 109


 Variable declared in the interface is by default public, static, and final.

The following example demonstrates how multiple inheritance is achieved using interfaces
and how variable declared in an interface can be accessed.

Dr. V. Venkateshwarlu Page 110


interface Husband //[Link]

double INC = 10000.00;

interface Wife //[Link]

double INC = 5000.00;

class Family implements Husband, Wife //[Link]

public void totIncome()

double tot = [Link] + [Link];

[Link](“Total Income of Family: ”+tot);

//[Link]

class MultInh

public static void main(String args[])

Family f = new Family();

[Link]();

Dr. V. Venkateshwarlu Page 111


>javac [Link]

>javac [Link] s

>javac [Link]

>javac [Link]

>java MultInh

Total Income of Family: 15000.00

Dr. V. Venkateshwarlu Page 112


7. Arrays, Strings and Vectors
Array:
An array is a collection of elements that can store more than one value of similar type.

Ex:
int a[ ]= {10, 20, 30}; 10 20 30

0 1 2
 An array allocates the memory in a sequential manner.
 For arrays the index number starts from “zero”

 Size of an array = number of elements X size of data type.

 For n values there will be “n-1” index numbers since the index number starts from
“zero”.

Initialization of an array:
Storing the values into an array at the time of memory allocation is said to be
“initialization” of an array.
Ex:

a[ ] = {10,20,30};

10 20 30
0 1 2
The elements of an array should be accessed by using index numbers;
Hence arrays are also called as “index variables”.

Dr. V. Venkateshwarlu Page 113


Output:

Assigning the values into an array:

The process of storing the values into an array after the allocation of memory is said to
be assigning the values into an array.

Output:

Dr. V. Venkateshwarlu Page 114


HASH code:

HASH code is a unique reference number given by JVM to the block of memory.
JVM takes memory address and applies Hash Code Generation Algorithm to generate
hash code.
Accepting the values into an array:

Output:

Dr. V. Venkateshwarlu Page 115


Two dimensional Arrays:
 In 2-dimensional array, every element consists of two indices.
 One index represents row number and the other index represents column
number.

Initialization of 2-Dimensional arrays:

Syntax:

data type array_name[ ][ ]={


{value1,value2,….valuen},

{value1,value2,….valuen},

{value1,value2,….valuen}

};

Ex:

int a[][]= {
{10, 20},
{30, 40}
};

Note:
 2-Dimensional arrays are used in solving matrices.

Dr. V. Venkateshwarlu Page 116


2-Dimensional arrays are also called as Array of Array, because 2-Dimensional array
contains a group of single dimensional arrays as a part of it.

Example program:
class ArrayTwo
{
public static void main(String args[])

{
int a[][]= { {10,20}, {30,40}};

int i,j;
for(i=0;i<2;i++)

{
for(j=0;j<2;j++)

[Link](a[i][j]+” “);
}

[Link](“\n”);

}
}

Output:
>javac [Link]
>java ArrayTwo
10 20
30 40

Dr. V. Venkateshwarlu Page 117


Write a program for 2-Dimensional array by accepting values from keyboard.

import [Link].*;
class ArrayTwoAccept
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader( new InputStreamReader([Link]));
int i,j,m,n;
[Link](“Enter the order of matrix [mxn]:”);
m=[Link]([Link]());
n=[Link]([Link]());
int a[][]=new int[m][n];
[Link](“Enter values…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=[Link]([Link]());
}
}
[Link](“Array elements are…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
[Link](a[i][j]+” “);
}
[Link]();
}
}
}
Output: >javac [Link]
>java ArrayTwoAccept
Enter the order of matrix [mxn]:
2 2
Enter values… 10 20 30 40
Array elements are…
10 20
30 40

Dr. V. Venkateshwarlu Page 118


Write a program on sum of two matrices by accepting values from keyboard.

import [Link].*;
class MatrixSum
{
public static void main(String args[])throws IOException
{
BufferedReader br= new BufferedReader( new InputStreamReader([Link]));
int i,j,m,n;
[Link](“Enter order of 2 matrices…”);
m=[Link]([Link]());
n=[Link]([Link]());
int a[][]=new int[m][n], b[][]=new int[m][n], c[][]=new int[m][n];
[Link](“Enter values into matrix a…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
a[i][j]=[Link]([Link]());
}
[Link](“Enter values into matrix b…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
b[i][j]=[Link]([Link]());
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=a[i][j]+b[i][j];
}
[Link](“Result matrix is…”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
[Link](c[i][j]+” “);
[Link]();
}
}
}

Dr. V. Venkateshwarlu Page 119


Output:
Enter order of 2 matrices
2
2
Enter values into matrix a…
10
12
15
18
Enter values into matrix b…
5
8
5
2
Result matrix is…
15 20
20 20

3-Dimensional arrays:
 In 3-d arrays every element consists of 3 dimensions
 In 3-d arrays every element consists of 3 indices.
 First index number represents the index of single dimensional array.
 The next two indices represents row, column number of a double dimensional
array.
 3-d array consists of single dimensional array and every element of a single
dimensional array consists of 2-d array.

Initialization of 3-d array:


int a[][]= {
{
{1,2},
{3,4}
},
{
{5,6},
{7,8}
}
}

Dr. V. Venkateshwarlu Page 120


Example program:
class ArrayThree
{
public static void main(String args[])
{
int i, j,k;
int a[][][]={
{
{1,2},
{3,4}
},
{
{5,6},
{7,8}
},
{
{9,10},
{11,12}
}
};
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
[Link](a[i][j][k]+” “);
}
[Link]();
}
[Link]();
}
}
}

Dr. V. Venkateshwarlu Page 121


Output:

1 2
3 4

5 6
7 8

9 10
11 12

Dr. V. Venkateshwarlu Page 122


Strings
String:
String is a class in [Link] package. But in java all classes are also considered as data
types. So we can also say String as a data type.
String can be declared as
String s;
S = ”KU”;
The above two statements can also written as
String s = ”KU”;
String can also be created using new operator
String s = new String(“KU”);

String class Methods:


length():
-It returns the length or no. of characters of a string.

toLowerCase():
-This method converts all characters of the string into lower case and returns it.

toUpperCase():
-This method converts all characters of the string into upper case and returns it.

equals():
-This method returns true if two strings are same, otherwise false. This is case
sensitive.
Ex: [Link](s2);

equalsIgnoreCase():
-This method returns true if two strings are same, otherwise false. This is not case
sensitive.

concat()
-This method appends(joins) two string and returns it.
Ex: [Link](s2);

compareTo():
-This method is useful to compare two strings and to know which string is bigger
or smaller. This is case sensitive.
Ex: [Link](s2);

Dr. V. Venkateshwarlu Page 123


compareToIgnoreCase():
-This method is useful to compare two strings and to know which string is bigger
or smaller. This is not case sensitive.

trim():
-This method removes spaces from the beginning and ending of a string.

substring():
-This method is used to extract a sub string from a main string.

Example program on String methods

“[Link]”
public class StringTest
{
public satic void main(String args[])
{
String s1=”hello”, s2=”KU”, s3=”java”, s4=”friend”;
[Link](“Length of s1=”+[Link]());
[Link](“s2 in lower case=”+[Link]());
[Link](“s3 in upper case=”+[Link]());
[Link](“s1 concats with s4=”+[Link](s4));
}
}

Output:

Length of s1=5
S2 in lower case=ku
S3 in upper case=JAVA
S1 concats with s4=hellofriend

Dr. V. Venkateshwarlu Page 124


StringBuffer:
String class creates an object length is fixed and content cannot be modified.
StringBuffer creates an object of flexible length and whose content can be modified.
StringBuffer object can be created as
StringBuffer s1 = new StringBuffer(“Welcome”);
Some of the StringBuffer methods are

[Link](s2) : Adds the string s2 to s1 at the end


[Link](n, s2) : Inserts the string s2 at the position n of the string s1.

[Link]() : Returns the no. of characters in the StringBuffer object

[Link](n, ‘x’) : Modifies the nth character to x


[Link](n) : Returns a substring from nth position to the end of the string

Mathematical functions (methods) in java:

 Mathematical methods are used to perform mathematical operations.


 All the mathematical methods are defined in Math class.
 All the mathematical methods are public and static by default. Hence they can be
accessed by using class name and dot (.).
 Math is a class in [Link] package.

Method Name Meaning

sqrt(double) It returns the square root of a given number

cbrt(double) It returns the cube root of a given number

pow(double , double) It returns m to the power of n

abs(double) It returns the absolute value of a given number

log(double) It returns the log value

Dr. V. Venkateshwarlu Page 125


exp(double) It returns the exponent value

toRadians(double) It is used to convert to radians

toDegrees(double) It is used to convert to degrees

sin(double) It returns the sine value

cos(double) It returns the cos value

tan(double) It returns the tan value

Example Program:

“[Link]”

public class MathTest

public static void main(String args[])

[Link](“Square root of 9 = ”+[Link](9));

[Link](“5 to the power of 3 = “+[Link](5, 3));

[Link](“Abs value of -20 = “+[Link](-20));

[Link](“value of sin 90 = “+[Link](90));

Output:

Square root of 9 = 3.0

5 to the power of 3 = 125.0

Abs value of -20 = 20

value of sin 90 = 0.8939966636005579

Dr. V. Venkateshwarlu Page 126


Vector:

 Vector is a collection class or a Container class.


 An object created to Collection class is called as Collection object.
 A Collection object can store other objects.
 A Vector stores elements (objects).
 Vector is synchronized i.e. two or more threads can act on Vector object
simultaneously.
 Vector class is present in [Link] package.

A vector object can be created as

Vector v = new Vector();

Vector class Methods:

add(element):

This method is used to add an element to the Vector.

remove(int position):

This method is used to remove an element from vector of a specified position.

clear():

This method removes all the elements from the Vector.

size():

This method returns the no. of elements present in the Vector.

get(int position):

This method returns the element of a specified position in the Vector.

Dr. V. Venkateshwarlu Page 127


Example program on Vector:

“[Link]”

import [Link].*;

public class VectorTest

public static void main(String args[])

Vector v = new Vector();

[Link](“Pavan”);

[Link](“Mahesh”);

[Link](“Prabhas”);

[Link](“Size of vector: “+[Link]());

[Link](“List: “+v);

Output:

Size of vector: 3

List: [Pavan, Mahesh, Prabhas]

Dr. V. Venkateshwarlu Page 128


Wrapper classes
Vectors cannot handle primitive types like int, float, double and char. Wrapper classes
are used to convert primitive types into object types. Wrapper classes are defined as a
part of [Link] package. The following table shows primitive types and their
corresponding wrapper classes.

Data types Wrapper class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Converting Primitive Numbers to Object Numbers using Constructors

Constructor Calling Conversion Action

Integer ival = new Integer(i); Primitive integer to Integer Object

Long lval = new Long(l); Primitive long to Long Object

Float fval = new Float(f); Primitive float to Float Object

Double dval = new Double(d); Primitive double to Double Object

Dr. V. Venkateshwarlu Page 129


Converting Object Numbers to Primitive Numbers Using typeValue() method

Method Calling Conversion Action

int i = [Link](); Integer Object to primitive integer

long l = [Link](); Long Object to primitive long

float f = [Link](); Float Object to primitive float

double d = [Link](); Double Object to primitive double

Converting Numbers to Strings using toString() method

Calling Method Conversion Action

str = [Link](i); primitive integer to String

str = [Link](l); primitive long to String

str = [Link](f); primitive float to String

str = [Link](d); primitive double to String

Converting String Objects to Numberic Objects using the static method valueOf()

Method Calling Conversion Action

Integer ival = [Link](str); String Object to Integer Object

Float fval = [Link](str); String Object to Float Object

Long lval = [Link](str); String object to Long Object

Double dval = [Link](str); String object to Double Object

Dr. V. Venkateshwarlu Page 130


Converting Numeric Strings to Primitive Numbers using static Parsing Methods

Method Calling Conversion Action

int i = [Link](str); Converts String to primitive integer

long l = [Link](str) Converts String to primitive long

float f = [Link](str); Converts String to primitive float

Double d = [Link](str); Converts String to primitive double

Note: parsing methods throws a NumberFormatException if the value of the str does
not represent a number.

Enumerated Types

An enum type is a type whose fields consist of a fixed set of constants. Common
examples include compass directions (values of NORTH, SOUTH, EAST and WEST) and
the days of the week.

Similar to final variables, the names of enum type’s fields are in CAPITAL letters. Since,
they are constants. We can define enumeration type by using enum keyword.

For example, we can specify the days of the week enum type as

public class EnumDemo

{
enum Days

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY


}

public static void main(String args[])

Dr. V. Venkateshwarlu Page 131


for(Days d : [Link]())

weekend(d);
}
}

private static void weekend(Days d)


{
if([Link]([Link]))
[Link](d+" is a holiday");
else

[Link](d+" is a working day");

}
}

Output:
SUNDAY is a holiday

MONDAY is a working day

TUESDAY is a working day

WEDNESDAY is a working day


THURSDAY is a working day

FRIDAY is a working day


SATURDAY is a working day

Dr. V. Venkateshwarlu Page 132


8. Packages
Java API Packages
API represents Application Program Interface.

According to Java programmer an API is set of classes and interfaces that perform a
specific operation.

According ‘C’ programmer an API is set of functions that perform a specific operation.

A package represents a directory that contains related group of classes and interfaces.
A package is used to isolate the classes.
For example we can import the classes of [Link] package as
import [Link].*;

Where, java is a directory name and io is another sub directory within it.

‘*’ represents all the classes and interfaces of that io sub directory.
Advantages of Packages:

 Packages are useful to arrange related classes and interfaces into a group i.e. the
classes and interfaces that performs the same task will be grouped together as a
package. For example, [Link] package contains all the classes and interfaces that
perform input and output operations.
 Packages allow to two classes with same names provided in two different
directories.
 Packages provide a way to “hide” classes thus preventing the other programs
that are meant for internal use only.
 A group of packages is called a library. The classes and interfaces of a package are
like books in a library and can be reused several times. This reusability nature of
packages makes programming easy. Just think, the packages in java are created
by JavaSoft people only once, and millions of programmers all over the world are
daily by using them in various programs.

Dr. V. Venkateshwarlu Page 133


Types of Packages

There are two types of packages in java. They are:

1. Pre-defined Packages (Java API Packages or Built-in Packages)


2. User-Defined Packages

1. Pre-defined Packages:
These are the packages which are already available in java language. These
packages provide all necessary classes, interface and methods for the
programmer. For every task there is a method available in Java and that method
can be used by the programmer without developing the logic on his own.
Some Pre-defined packages are

[Link]: lang stands for Language. It consists of Language support classes.


These are classes that java compiler itself uses and therefore they are
automatically imported. They include Wrapper classes, String, StringBuffer,
Thread and Exception classes etc.

[Link]: uitl stands for utility. It consists of Language utility classes such as
ArrayList, Vector, Stack, LinkedList, Date etc.

[Link]: io stands for input and output. It consists of input/output support classes.
These classes used to perform input-output related tasks.

[Link]: net stands for network. Client-Server programming can be done using
this package. They include classes for communicating with local computer as well
as with internet servers.

[Link]: awt stands for abstract window toolkit. They include classes to develop
GUI applications.

[Link]: Classes for creating and implementing applets.

[Link]: sql stands for structured query language. They include classes to deal
with databases such as Oracle, MySQL etc.

Dr. V. Venkateshwarlu Page 134


java
User-defined Packages

Similar to Pre-defined packages, the users of the Java language may also create their
own packages called as User-defined packages. A user defined package can be created
using the keyword “package”.
Declare the package at the beginning of a file.

Syntax: package packagename;

A simple sketch to understand the reusability of a package as shown below


mathops

Addition
Add(-,-) {….}

import [Link]; import [Link];


class UseAdd class X
{ {
p s v m(String a[]) p s v m(String a[])
{ {
Addition a=new Addition(); Addition aone=new Addition();
[Link](10,20); [Link](3,5);
} }
} }

Dr. V. Venkateshwarlu Page 135


A program for adding a class to a package.

package mathops;
public class Addition
{
public void add(int x,int y)
{
[Link](“Addition of two integers:”+(x+y));
}
}
Steps to compile the package:
D:\Programs\Java programs>javac –d. [Link]

[Link]

Using “Addition” class in another class (Accesing a package)

import [Link];
class UseAdd{
public static void main(String args[]){
Addition a=new Addition();
[Link](10,20);
}
}
>javac [Link]
>java UseAdd
Addition of 2 integers is:30

Adding another class to a package:

package mathops;
public class Subtraction{
public static void main(String args[]){
[Link](“Subtraction of 2 integers is:”+(x-y));
}
}
>javac –d. [Link]

Dr. V. Venkateshwarlu Page 136


Using both the classes of a package in another class:

import mathops.*;
public class UseAddSub
{
public static void main(String args[])
{
Addition a=new Addition();
Subtraction s=new Subtraction();
[Link](10,20);
[Link](10,20);
}
}
>javac [Link]
>java UseAddSub
Addition of 2 integers is: 30
Subtraction of 2 integers is: 10

Creating sub packages: A package within another package is said to be sub package.
Syntax: package [Link];
Adding a class to sub package:

package [Link];
public class Wish
{
public void wishing()
{
[Link](“Good evening…”);
}
}
>javac –d . [Link]

[Link]

Dr. V. Venkateshwarlu Page 137


Accessing the Wish class.
import [Link];
public class UseWish
{
public staitc void main(String args[])
{
Wish w=new Wish();
[Link]();
}
}
>javac [Link]
>java UseWish
Good evening…

Dr. V. Venkateshwarlu Page 138


Hiding classes

When we import a package using “*”, all public classes are imported. However, we may
prefer to “not import” some classes i.e. we may like to hide these classes from accessing
outside the package. Such classes should not be declared as “public”.

Example:
package pone;

class A
{

//code of A
}
>javac -d . [Link]

The class A which is not declared as public is hidden from outside of the package pone.
This class can be accessed in the same package.

Accessing the class A


import pone.*;

class B
{

A a = new A();

..
}
>javac [Link]
When we compile [Link], the compiler will generate an error, since the class A which is
not declared as public cannot be imported.

Dr. V. Venkateshwarlu Page 139


Static Import

It is a feature used to access static members of a class directly i.e. without using
ClassName and dot.
Syntax:
import static [Link];
Or

import static [Link].*;


If there is no static import we need to write a program as

import [Link];
class A{

public static void main(String args[]){


double r = 5.5;

double area = [Link]*r*r;

[Link](“Area of Circle: “+area);


}

The above program can be written using static import which allows to access a public
static member directly without using classname or interfacename and dot.
import static [Link].*;

class A{
public static void main(String args[]){
double r = 5.5;

double area = PI*r*r;

[Link](“Area of Circle: “+area);


}
}

Dr. V. Venkateshwarlu Page 140


Access specifiers:

An access specifier is a keyword which is used to specify where to access a member of a


class or class itself. There are four access specifiers in java. They are private, public,
protected and default. If no access specifier is used then java compiler will take it as a
default access specifier. Access specifier specifies the scope of a member.

Scope: It means the place or area where a member can be accessed.

 private members can be accessed in the same class in which they are defined.
Hence, the scope of private is class scope

 default members can be accessed in the other class of same package.


Hence, the scope of default is package scope.

 protected members can be accessed in the other classes of same package and in
the sub classes.
Note: Sub classes may also be present in different package.
Hence, the scope of protected members is sub class scope.

 public members can be accessed anywhere.


Hence, the scope of the public is global scope.

Dr. V. Venkateshwarlu Page 141


Path setting:
Write a java program at the user required folder (Ex: D:\Programs\Java)

 Open the command prompt,


 Move to D:\Programs\Java
 Compile the program as

D:\Programs\Java>javac [Link]
It gives an error as ‘javac’ is not recognized internal or external command.
So, we need to set the path by using the variable path.
>set path=C:\Program Files\Java\Jdk1.7.0\bin
 Now we can compile and execute the java file

>javac [Link]

>java xxx

Note:

The above path setting is temporary

Since, this path setting will be applicable until we close the editor.

Dr. V. Venkateshwarlu Page 142


Permanent path setting:
 Right click on My Computer.
 Select properties.
 Click on Advanced tab.
 Click on Environment Variable.
 In the user variables click on New.
 Give the variable name as path and variable value as
C:\Program Files\Java\Jdk1.5.0\bin
 Click on OK.
 Click on OK.
 Finally click on OK.

Dr. V. Venkateshwarlu Page 143


9. Managing Errors and Exceptions
Bug: An error in a program is said to be Bug.

Debugging: Solving the errors in a program is said to be debugging.

Errors are of three types


1. Compile time errors
2. Logical errors
3. Runtime errors

1. Compile time errors:


 These are syntactical errors found in the code.
 These errors are identified by the compiler during the compilation of a program.
 Compile time errors does not cause any harm to the program. i.e., No loss of
data.

Example program:
class Err

public static void main(String args[])

{
[Link](“Hello”)
}
}

>javac [Link]

Note: In the above program semi colon missed is a syntactical error.


2. Run-time error:
 These errors represent the inefficiency of the computer system to execute
a particular statement.
 These errors are not detected by the java compiler. They are detected by
the JVM only at run-time.

Dr. V. Venkateshwarlu Page 144


Example Program

class Err{

public static void main( )


{
[Link](“Hello”);

}
}
Output:
>javac [Link]
>java Err

Exception in thread “main” [Link]: main

3. Logical Errors:
 These are the errors that occur due to improper or bad logic written by the
programmer.
 Logical errors are not detected either by the compiler or not by the JVM.
 The programmer is solely responsible for them.
 These errors does not cause any harm to the program. i.e., no loss of data.

Example Program:
class Err{

public static void main(String args[]){

int a, s=5;

a = 4*s; //wrong use: a = s *s;


[Link](“Area of Square= ”+a);
}
}

Output:

Area of Square= 20

Dr. V. Venkateshwarlu Page 145


Exception:

Run-time error is also called as an Exception. When an exception is occurred at


run-time the program terminates abnormally and there is a loss of data.

Exception Handling:
Handling the exception at run-time such that the program should be terminated
in a normal way and there should not be any loss of data is said to be Exception
Handling.
Exceptions are of two types

1. Checked Exception
2. Unchecked Exception

1. Checked Exception:
The exceptions checked at compile-time by the java compiler are called ‘Checked
Exceptions’. The programmer should handle the checked exceptions or throw them.
public static void main(String args[]) throws IOException

Here, IOException is an example for checked exception.

The point is that an exception occurs at run-time but in case of checked


exceptions, whether we are handling it or not, it is detected at compilation time.

2. Unchecked Exception:
The exceptions checked by the JVM are called ‘Unchecked Exceptions’.
Unchecked Exceptions may be handled or may not be handled by the programmer.
When it is occurred the program will be terminated abnormally.
Ex: ArithmeticException, NumberFormatException etc..

All exceptions are declared as classes in java.

Class: Exception
Exception is a super class for all exceptions in java.

Dr. V. Venkateshwarlu Page 146


[Link]

|
Throwable
|

Exception

|-IOException, InterruptedException etc (Checked Exceptions)


|-ArithmeticException
|-NumberFormatException Unchecked Exceptions

|-ArrayIndedOutOfBoundsException

:
An Exception Example:

class Excep
{
public static void main(String args[])
{
[Link](“Open a file..”);
[Link](“Write some data..”);
int a, b, c;
a=[Link](args[0]);
b=[Link](args[1]);
c=a/b;
[Link](“Result=”+c);
[Link](“Close a file..”);
}
}
Output:
>javac [Link]
>java Excep
Open a file..
Write some data..
Exception in thread “main” [Link]: / by zero..

Dr. V. Venkateshwarlu Page 147


Exception Handling:
Exception can be handled using try, catch, finally blocks.

try:
tryblock scans for run-time errors.
Syntax:

Try
{
Statements to scan for a run-time error
}

catch:
The programmer should write the catch block to display the exception details. catch
block will be executed when an exception is raised.

Syntax:

catch(Exceptionclass ref)
{
Statements to handle Exception
}

Note: catch should be followed by the try block.

finally:
finally is a block of statements that contains the code for closing the files, closing
the data base connections etc..
Syntax:

Finally
{
Statements to close the database connections
}

Dr. V. Venkateshwarlu Page 148


Note:

- finally block should be followed by the catch blocks.


- finally block is optional i.e. we may write or we may not write.
An example program to handle the ArithmeticException(Unchecked).

class ExpOne{
public static void main(String args[])
{
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(ArithmeticException ae)
{
[Link](“Error: “+ae);
[Link](“b value shoud not be zero..”);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}
Output:
>javac [Link]
>java ExpOne 10 0
Open a file..
Write some data..
Error:[Link]: / by zero
b value should not be zero..
Close a file..
Program terminates..
Dr. V. Venkateshwarlu Page 149
Handling Multiple Exceptions:
Most of the times there is a possibility of getting more than one exception. In this
case, the programmer should write multiple catch blocks to handle each one of them.

class ExpTwo
{
public static void main(String args[])
{
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(ArithmeticException ae)
{
[Link](“Error: “+ae);
[Link](“b value shoud not be zero..”);
}
catch(NumberFormatException nfe)
{
[Link](“Error: “+nfe);
[Link](“Pass only integer values..”);
}
catch(ArrayIndexOutOfBoundsException aioe)
{
[Link](“Error: “+aioe);
[Link](“Not enough values..”);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}

Dr. V. Venkateshwarlu Page 150


Output:
>javac [Link]
>java ExpTwo 10
Open a file..
Write some data..
Error:[Link]: …
Not enough values..
Close a file..
Note:

 A try block can be followed by several catch blocks.


 A catch block can’t be written without try block.

Handling multiple exceptions using single catch block:


Exception is the super most class for all the exceptions. A reference variable of
super class can refer to sub class objects. So a catch block of Exception can handle any
type of Exception.

class ExpThr{
public static void main(String args[]){
[Link](“Open a file..”):
[Link](“Write some data..”);
int a, b, c;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c = a / b;
[Link](“Result= “+c);
}
catch(Exception ae)
{
[Link](“Error: “+e);
}
finally
{
[Link](“Close a file..”);
}
[Link](“Program terminates..”);
}
}

Dr. V. Venkateshwarlu Page 151


“throws” clause:

Programmer should handle the checked exceptions. In case, the programmer


unable to handle the checked exceptions, he should throw them out using ‘throws’
clause. Otherwise, java compiler gives an error.
Example Program:

Import [Link].*;
class ExpFour
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int a, b, c;
[Link](“Enter two values:”);
a=[Link]([Link]());
b=[Link]([Link]());
c= a+b;
[Link](“\n Sum: “+c);
}
}
Output:
>javac [Link]
>java ExpFour
Enter two values:
10
20
Sum: 30

Dr. V. Venkateshwarlu Page 152


Handling the Checked Exception using try, catch, finally blocks:

import [Link].*;
class ExpFour
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int a, b, c;

try
{
[Link](“Enter two values:”);
a=[Link]([Link]());
b=[Link]([Link]());
c= a+b;
[Link](“\n Sum: “+c);
}
catch(IOException e)
{
[Link](“Error:”+e);
}
}
}
Output:
>javac [Link]
>java ExpFour
Enter two values:
10
20
Sum: 30

Dr. V. Venkateshwarlu Page 153


User-Defined Exception:

An exception created by the programmer (user) is called as user-defined


exception.
The following steps are followed in creation of a user-defined exception.
Step 1: The user-defined exception must be a subclass of Exception. Since, all exceptions
are subclasses of Exception class.
Ex:

classMarksOutOfBoundsException extends Exception

Step 2: The user should provide a zero argument constructor in a user defined
exception.

Ex:
public MarksOutOfBoundsException( ) { }

Step 3: The user should provide a one parameterized constructor and the parameter
should be a String. It should call a super class constructor.

Ex:

public MarksOutOfBoundsException(String msg)


{
super(msg);

Step 4: When we want to raise our own exception, we need to create an object to the
exception class and throw it using throw clause.
MarksOutOfBoundsException me = new MarksOutOfBoundsException(“Exception
details..”);
throw me;

Dr. V. Venkateshwarlu Page 154


Example Application on User-Defined Exception:

class MarksOutOfBoundsExceptionextends Exception


{
public MarksOutOfBoundsException( ){ }
public MarksOutOfBoundsException(String msg)
{
super(msg);
}
}

import [Link].*;
class UserExp
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
int marks;
try
{
[Link](“Enter Marks: “);
marks=[Link]([Link]());
if(marks>100)
{
MarksOutOfBoundsException me=new
MarksOutOfBoundsException(“Marks should not be greater than 100”);
throw me;
}
[Link](“Ur Marks: “+marks);
}
catch(MarksOutOfBoundsException me)
{
[Link](“Error: “+e);
}
}
}
Output:
>javac [Link]
>java UserExp
Enter Marks: 110
Error:[Link]: Marks should not be greater than 100

Dr. V. Venkateshwarlu Page 155


10. Multi-Threaded Programming
Multi-Tasking:
Execution of two or more tasks simultaneously is said to be Multi-tasking.
Multi-Threading:
Execution of two or more threads simultaneously is said to be Multi-Threading.
Thread:
 A Thread is a part of a program called as Light weight process.
 Every thread has its own way of execution.
 Every thread will be executed depending up on the priority.
 The thread with higher priority will be executed first.
 All the threads are created from main thread called as child threads.
 Main method itself is a thread.
 The priority of main thread is ‘5’ and the name of main thread is “main”
 Main thread should be terminated after the termination of all the child threads.

Thread Interruption (InterruptedExcpetion)


During the execution of lower priority thread, if higher priority thread comes for
execution the following cases takes place
i. The lower priority thread itself gives the control to the higher priority thread.
ii. The higher priority thread forcibly takes the control from lower priority thread.
In both the cases lower priority thread is looser and hence throws InterruptedException.

Life cycle of a thread:

Dr. V. Venkateshwarlu Page 156


 A new thread calls start() method for starting the execution of a thread.
 start() method calls run method to execute the statements of a thread.
 If all the statements of a thread executed then JVM calls stop() method to stop
the execution of a thread that represents successful termination.
 If any interruption is occurred the thread will be temporarily suspended, in the
mean while another thread will be executed.
 The thread which is suspended may again resumed and enters into running state.
 If any dead lock is occurred the thread enters into blocked state that represents
unsuccessful termination.

We can create the thread in two ways


1. A thread can be created by extending “Thread” class.
2. A thread can also be created by implementing “Runnable” interface.

Note: To create our own thread it must be a subclass or it must be extended form
Thread Class

Methods of Thread class:


1. public void setName(String tname)
It is used to set a name to the thread
2. public String getName()
It is used to return the name of a thread.
3. public void setPriority(int pno)
It is used to give a priority to the thread.
4. public int getPriority()
It is used to return the priority no. of a thread.
5. public static void sleep(milliseconds)
It suspends the currently executing thread for a specific period of seconds.
1000 Milliseconds = 1 Second
6. public static currentThread()
It returns the reference of a currently executing thread

Dr. V. Venkateshwarlu Page 157


A simple thread program:

“[Link]”
public class MThread
{
public static void main(String args[])
{
Thread t = [Link]();

[Link](“Current Thread: “+t);


[Link](“Venkat”);
[Link](6);

[Link](“After changing..”);
[Link](“Current Thread: “+t);
}
}

Output:

>javac [Link]
>java MThread
Current Thrread: [main, 5, main]
After Changing..
Current Thread: [Venkat, 6, main]

Dr. V. Venkateshwarlu Page 158


An application to create multiple threads using Thread class:

“[Link]”
public class CThread extends Thread
{
String tname;
public CThread(String name)
{
super(name);
tname=name;
[Link](tname+” Thread Created..”);
start();
}
public void run()
{
[Link](tname+” started..”);
try
{
for(int i=1; i<=5; i++)
{
[Link](tname+” : “+i);
[Link](1000);
}
}
catch(Exception e)
{
[Link](“Error: “+e);
}
[Link](tname+” thread terminated..”);
}
}

Dr. V. Venkateshwarlu Page 159


“[Link]”
public class MainThread
{
public static void main(String args[])
{
[Link](“Main Thread started..”);
CThread ct1 = new CThread(“First”);
CThread ct2 = new CThread(“Second”);
try
{
for(int i=1; i<=5; i++)
{
[Link](“Main : “+i);
[Link](2000);
}
}
catch(Exception e)
{
[Link](“Error: “+e);
}
[Link](“Main thread terminated..”);
}
}

Output:
>javac [Link]
>javac [Link]
>java MainThread

Dr. V. Venkateshwarlu Page 160


Thread Synchronization:
Synchronization is a process in which at any given time only one thread can
access the common resource.
The key concept of synchronization is semaphore or monitor that exclusively
locks the resource when one thread is accessing.

Dead Lock:
 Dead Lock is an error that can be encountered in multithreaded programs
 It occurs when two or more threads wait indefinitely for each other to relinquish
locks.

Dr. V. Venkateshwarlu Page 161


11. Applet Programming
Applet:

-An Applet is a small program that runs very fast in the net and runs as a part of web application
in the browser.

-Applets are used to develop GUI (Graphical User Interface) applications.

-Applet is the first GUI concept introduced in the internet.

Browser:

-Browser is used to execute the web pages.

Web application:

-A web application is a set of web pages which can be executed using the browsers.

Examples:

Internet Explorer

Mozilla Firefox

Netscape Navigator

Opera etc

Life Cycle of an Applet:

Dr. V. Venkateshwarlu Page 162


An Applet is born with init() method and starts functioning with start() method. To Stop the
applet, the stop() method is called and to terminate applet completely from memory, the
destroy() method is called. Once the applet is terminated, we should reload HTML page again
to get the applet start once again from init() method. This cyclic way of executing the methods
is called applet life cycle.

init():

The init stage consists of initializing any methods and variables that applet needs to function,
such as images to be loaded. The init method is called when the applet is first loaded.

start():

The start stage starts the primary functions of an Applet. For example, if an applet plays a
sound, it could start playing during the start stage. The start method is called when the init
method has finished and the applet is ready to execute.

paint():

The paint stage occurs whenever the Applet’s display must be thrown on the screen. This
happens right after the start stage.

stop():

The stop stage can be used to stop any actions that might still be in progress from the start
stage.

destroy():

destroy is called automatically, and completes any memory cleanup or garbage collection that
needs to be done when an Applet destroyed.

The destroy method is called when you quit a browser.

Class: Graphics:

-It is a class in [Link] package.

-It contain methods related to Graphics

Ex:

drawString(“String”, int width, int height)

To develop the applet based application, we should extend our class from [Link].

Dr. V. Venkateshwarlu Page 163


An example program to develop on Applet

“[Link]”

import [Link].*;

import [Link].*;

import [Link].*;

public class AppDemo extends Applet

public void paint(Graphics g);

[Link](“Hello”, 250,250);

Compile the .java file

>javac [Link]

Applet will be executed in the browser, the browser understands the scripting languages.

So, we should write a HTML(Hyper Text Mark up Language) file to provide the information
about an Applet

Adding applet to a HTML File

“[Link]”

<html>

<body>

<applet code = “AppDemo” width=500 height = 500 ></applet>

</body>

</html>

Dr. V. Venkateshwarlu Page 164


Applets can be executed in two ways

i. Using Browser

ii. appletviewer (It is a mini browser)

i. Using Browser

Open internet explorer and type the URL(Uniform Resource Locator) of html file as

D:\appletapps\[Link]

ii. appletviewer

Open Command prompt (DOS Prompt) and move to the D:\appletapps using cd
command

D:\appletapps>appletviewer [Link]

Dr. V. Venkateshwarlu Page 165


An example Application on Life cycle of an Applet

“[Link]”

import [Link].*;

import [Link].*;

import [Link].*;

public class AppDemo extends Applet


{
public void init()
{
[Link](“init()..”);
}
public void start()
{
[Link](“start()..”);
}
public void paint(Graphics g);
{
[Link](“BDC”, 250,250);
}
public void stop()
{
[Link](“stop()..”);
}
public void destroy()
{
[Link](“destroy..”);
}
}

>javac [Link]

Dr. V. Venkateshwarlu Page 166


“[Link]”
<html>
<body>
<applet code = “AppLC” width=500 height = 500 >
</applet>
</body>
</html>

In command Prompt

>appletviewer [Link]

Passing parameters to Applet

We can pass parameters from HTML file to the Applet class, Such a concept is called as
dynamic programming through applets.

Parameter can be passed to the applet using a predefined tag called as “param” in
HTML file.

Example Application

“[Link]”

import [Link].*;
import [Link].*;
import [Link].*;
public class AppCol extends Applet
{
String str;
public void init()
{
setBackground([Link]);
setForeground([Link]);
str=getParameter(“bname”);
}
public void paint(Graphics g);
{
[Link](str, 250,250);
}
}
>javac [Link]

Dr. V. Venkateshwarlu Page 167


“[Link]”
<html>
<body>
<applet code = “AppCol” width=500 height = 500 >
<param name=”bname” value=”INDIA” />
</applet>
</body>
</html>

In command prompt

>appletviwer [Link]

Dr. V. Venkateshwarlu Page 168


Graphics
Class: Graphics

Graphics is class that contains different types of GUI methods.

It is a class present [Link] package.

Methods of Graphics class:

1. drawLine()
It is a method used to draw a line.
Syntax:
drawLine(int x1, int y1, int x2, int y2)

Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class LineDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 100, 200, 200);
}
}

Compile [Link]
>javac [Link]

“[Link]”
<html>
<body>
<applet code=”LineDemo” width=500 height=500 >
</applet>
</body>
</html>

Run the application


>appletviewer [Link]

Dr. V. Venkateshwarlu Page 169


2. drawRect()
This method is used to draw a rectangle.
fillRect()
This method is used to fill the rectangle with color.

Syntax:
drawRect(int x1, int y1, int width, int height)
fillRect(int x1, int y1, int width, int height)

Example Program:

“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class RectDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200);
[Link](25, 25, 100, 100);
}
}

Compile [Link]
>javac [Link]

“[Link]”
<html>
<body>
<applet code=”RectDemo” width=500 height=500 >
</applet>
</body>
</html>

Run the application


>appletviewer [Link]

Dr. V. Venkateshwarlu Page 170


3. drawOval()
It is used to draw a circle and ellipse.
fillOval()
It is used to fill a circle or ellipse with color.

Syntax:
drawOval(int x1, int y1, int width, int height)
fillOval(int x1, int y1, int width, int height)

Example Program

“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class OvalDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200);
[Link](25, 25, 100, 100);
}
}

Compile [Link]
>javac [Link]

“[Link]”
<html>
<body>
<applet code=”OvalDemo” width=500 height=500 >
</applet>
</body>
</html>

Run the application


>appletviewer [Link]

Dr. V. Venkateshwarlu Page 171


4. drawRoundRect()
It is used to draw a rounded rectangle.

Syntax:
drawRoundRect(int x1, int y1, int width, int ht, int xDiameter, int yDiameter);

5. drawArc()
It is used to draw an arc.
Syntax:
drawArc(int x1, int y1, int width, int height, int startAngle, int sweepAngle);

Example Program:
“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class ArcDemo extends Applet
{
public void paint(Graphics g)
{
[Link](100, 50, 250, 200, 0, 120);
}
}

Compile [Link]
>javac [Link]

“[Link]”
<html>
<body>
<applet code=”ArcDemo” width=500 height=500 >
</applet>
</body>
</html>

Run the application

>appletviewer [Link]

Dr. V. Venkateshwarlu Page 172


6. drawPolygon()

It is used to draw a polygon.

Syntax:

drawPolygon(int xPoints[ ], int yPoints[ ], int nPoints);

Example Program:

“[Link]”
import [Link].*;
import [Link].*;
import [Link].*;
public class PolygonDemo extends Applet
{
public void paint(Graphics g)
{
int x[] = {100, 200, 100, 200, 100};
int y[] = {100, 100, 200, 200, 100};
int n = 5;
[Link](x, y, n);
}
}

Compile [Link]
>javac [Link]

“[Link]”
<html>
<body>
<applet code=”PolygonDemo” width=500 height=500 >
</applet>
</body>
</html>

Run the application


>appletviewer [Link]

Dr. V. Venkateshwarlu Page 173

You might also like