0% found this document useful (0 votes)
214 views

r23 Java Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
214 views

r23 Java Material

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

OOP THROUGH JAVA (R23)

UNIT-1

FUNDAMENTALS OF OBJECT – ORIENTED PROGRAMMING

Introduction:

Q. Explain Object oriented paradigm?

Object-Oriented approach was introduced to overcome the drawbacks of Procedural approach. OOP treats
data as a critical element in the program development, and does not allow it to flow freely around the
system. It ties data more closely to the functions and protect from accidental modification from the
outside functions.

OOPs decompose a problem into a number of entities called “Objects”. The Organization of data and
functions in Object Oriented Programming is as shown below.

Organization of OOPS

Advantages of OOP’S:-
 Emphasis is on data rather than functions.
 Programs are divided into sub parts called Objects.
 Functions and data are tired together within the object.
 Data is hidden and cannot be access by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be easily added whenever necessary.
 OOPs follow Bottom-Up approach in program design.
 OOPs give security to data.
Disadvantages of OOP’S:-
 OOPs source code is too bigger, hence it requires huge memory.
 Bottom-Up approach gives a little bit of confusion to the programmer.

Q. Applications of OOP.
1. Artificial intelligence and expert systems.
2. Simulation and modeling studies.
3. Object oriented data base systems.
4. Object oriented operating systems.
5. Real time systems.
6. Decision support and office automation systems.
7. CAD (Computer Aided Design)/CAM (Computer Aided Manufacturing) systems.
8. Multimedia applications graphical user interface.
9. Computer based training educations.
10. GUI based applications such as windows applications.
11. Data recovery systems. 12. Image processing tools. 13. Distributed systems. 14. Neural
networks and parallel programming. 15. Audio video manipulation Tools.
Q. Explain Basic Concepts of OOP?

AECN, ATMAKUR 1
OOP THROUGH JAVA (R23)

The following are the basic elements of OOPs.

1. Objects:
i. Objects are the basic run time entities in an object oriented programming.
ii. Object takes a memory space and has an associated address.
iii.Objects are the variables of class.
iv. Each object contains data and code to manipulate that data.
2. Classes:
i. Classes are the basic building blocks of oops.
ii. Classes combined both data and functions.
iii.Classes create new user defined data types.
iv. Once a class has been defined we can create number of objects belongs to that class.
v. Classes are user defined data types and behaves like built-in data types.
3. Data abstraction:
Data abstraction means representing the essential features without including background details and
explanations.
4. Data encapsulation:
The process of combining both data and functions into a single unit (interface) is known as data
encapsulation.
5. Inheritance:
i. Inheritance is a process of creating a new class from an existing class. The new class contains
both the features of a new class and old class.
ii. Inheritance is very useful to add additional features to an existing class without modifying it.

6. Polymorphism:
 Polymorphism means the ability to take more than one form with a single interface.
 “Polymorphism” comes from the ‘Greek’ word. “Poly” means “many” and “morphism” means
“forms”. i.e., many forms.

7. Dynamic binding: Binding means the linking of method code during execution of the program.
Dynamic binding means that the code associated with a given procedure call is not known until the run
time.

8. Message passing: objects that communicate with each other by sending and receiving information with
the help of methods of objects.

Q. Explain about java Features?

The following are most important features of Java.

AECN, ATMAKUR 2
OOP THROUGH JAVA (R23)

1. Compiled and Interpreted. 8. High Performance.


2. Platform–Independent and Portable. 9. Dynamic and Extensible.
3. Object Oriented 10. Ease of Development
4. Robust and Secure. 11. Scalability and Performance
5. Distributed. 12. Monitoring and manageability
6. Simple Small and Familiar. 13. Desktop Client.
7. Multithreaded and Interactive.

1. Compiled and Interpreted: Java combined both compiled and interpreted.


Compiler: It translates source code into byte code. Interpreter: It generates Machine code that can be
directly executed by the machine that is running the java program.

2. Platform – Independent and Portable :


Java programs can be easily moved from one computer system to another. Changes and upgrades in
operating system, Processors and system resources will not force any changes in java programs.

3. Object Oriented :
Java is a true object –oriented language. Almost everything in java is an object. All program code and
data reside within objects and class. Java comes with an extensive set of classes, arranged in packages
that we can use in our programs by inheritance.

4. Robust and Secure :


Java is a robust language. It has strict compile time and runtime checking for data types. It deals with the
concept of Exception Handling. Security becomes an important issue for a language that is used for
programming on internet.

5. Distributed :
Java is a distributed language designed for creating applications on networks. It has the ability to share
both data and programs.

6. Simple and Small :


Java is a small and simple language. Many features of C and C++ that are sources of unreliable code are
not part of java.

7. Multithreaded and Interactive :


Multithreaded means handling multiple tasks simultaneously. Multithreaded programming means that we
need not wait for the application to finish one task before beginning another.

8. High Performance :
Java performance is impressive for an interpreted language, mainly due to the use of intermediate byte
code. According to Sun, Java speed is comparable to the native C and C++.
9. Dynamic and Extensible :
Java is a dynamic language. Java is capable of dynamic linking in new class libraries, methods and
objects. Java programs supports functions written in other languages such as C and C++. These functions
are known as native Methods.
Chapter: OVERVIEW OF JAVA LANGUAGE

Introduction: JAVA HISTORY

AECN, ATMAKUR 3
OOP THROUGH JAVA (R23)

Java is a general purpose, Object–oriented programming language developed by James Gosling


of Sun Microsystems in the 1991. This language is initially called as Oak and was renamed as Java in
1995. Java was developed for the developed for consumer electronic devices like TVs, VCRs etc., The
Java discovered that the existing languages like C and C++ had limitations in terms of both reliability and
Portability. They modeled their new language java on C and C++ but removed a number of features of C
and C++, thus made java a really simple, reliable, Portable and powerful language.

We can develop two types of java programs they are:

Stand-alone applications: They are programs written in java to carry out certain task on a Stand-alone
local computer. Executing Stand alone java program involves two steps:
 Compiling source code into byte code using java compiler
 Executing the byte code using java interpreter

Web applets: applets are small programs developed for internet applications. We can develop applets for
doing everything from simple animated graphics to complex games and utilities.

Stand alone programs can read and write file and perform certain operations that applet cannot do. An
applet can only run within a web browser.

History of java:

Year Development
Sun Microsystems decided to develop special software to manipulate consumer electronic
1990
devices.
1991 Most popular OOPs language Oak was introduced.
Green Project team by sun, demonstrated the application of their new language to control a
1992
list of home appliances.
World Wide Web appeared on the Internet and transformed the text-based internet into a
1993
graphical rich environment.
1994 A Web browser called “Hot Java” was development.
1995 Oak was renamed as Java.
1996 Sun releases Java Development Kit 1.0 (JDK 1.0)

1997 Sun releases Java Development Kit 1.1 (JDK 1.1)

1998 Sun releases Java2 with version 1.2 of the Software Development kit 1.2 (SDK 1.2)

1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE)

2000 J2SE with SDK 1.3 was released.

2002 J2SE with SDK 1.4 was released.

2004 J2SE with JDK 5.0 (J2SE 5.0) was released.

Simple java program structure

Q. Explain a simple java programming structure.

Every programming language follows certain program structure which is followed by the
programmer. A java program may contain many classes of which only one class defines main( ) method.

AECN, ATMAKUR 4
OOP THROUGH JAVA (R23)

Classes contain data members and methods that operate on the data numbers of the class. Each method of
a class may contain declarations and executable statements.

Documentation section suggested

Package declaration optional

Import statements optional

Interface statement optional

Class definition optional

Main method class

Main method definition Essential

Documentation section: this section includes a set of comment lines like giving name of the program,
author name etc. it is an optional section.

Package declaration: the first statement in java program is the package declaration statement. This
statement declares a package name and informs the compiler that the classes defined here belong to this
package.

Import statement: after package declaration statement, the immediate next line must be the import
statement. An import statement instructs the interpreter to load an entire package or some portion into
program. A program can contain multiple import statements. It is an optional section.

Interface statement: an interface is like a class which includes a group of abstract methods. This section
is used to declare an interface. It is an optional section.

Class definition section: a java program can contain multiple classes. These classes are defined in this
section with default access modifier. The number of classes can be depends on the complexity of the
program.

Main ( ) method: since every stand alone program requires a main method, this class is the essential part
of java program. A simple java program may contain this part. The main( ) method creates objects of
various classes and establishes communication between them.

JAVA TOKENS

Java language includes five types of tokens. They are

1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

Keywords:

Keywords are an essential part of a language. They implement specific features of the language.

AECN, ATMAKUR 5
OOP THROUGH JAVA (R23)

Keywords have specific meaning in java; we cannot use them as names for variables, classes, methods
and so on. All keywords are to be written in lower case letters. Java has 50 keywords.

abstract assert boolean break byte case


catch char class const continue default
do double else enum extends final
finally float for goto if implements
import instanceof int interface long native
new package private public protected return
short static strictfp super switch synchronized
this throw throws transient try void
volatile while

Identifiers:

An identifier is a name given to a programming element such as naming classes, Methods, variables,
object, labels, packages and interfaces in a program

Rules of Identifiers:
1) They can have alphabets, digits, underscore and dollar sign characters.
2) They must not begin with a digit.
3) Uppercase and Lowercase letters are distinct.
4) They can be of any length.

LITERALS: Literals in Java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. Java supports five major types of literals.

1) Integer Literals.
2) Floating Point Literals.
3) Character Literals.
4) String Literals.
5) Boolean Literals.

1. Integer Literals :
Integer literals represents the fixed integer values like 100, -55, 123450 etc. Decimal number
system uses 10 digits (from 0 to 9) to represent any number. Octal number system uses 8 digits (from
0 to 7) and prefix ‘0’ before the number. Hexadecimal number system uses 16 digits (from 0 to 9 and
A to F) and prefix 0x before the number.

Eg:- int decval = 26; // The number 26 in Decimal


int octval = O32; // The number 26 in Octal
int hexval = Ox1a;// The number 26 in Hexa Decimal
2. Floating point Literals
Float Literals represent fractional numbers. These are the numbers with decimal points like 2.0, -
0.0005, 3.14, 6.1e-32, etc. while writing these literals we can use E or e for scientific notation, F or f
for float literals and D or d for double literals.

Eg:- double d1 = 123.4;


double d2 = 1.234e2; // Equals to 1.234 X 102
float f1 = 1.234f

3. Character Literals: Character Literals indicate the following.


1) General Characters ( A to Z, a to z, 0 to 9 etc )
2) Special Characters ( !,@,#,^,&, etc)

AECN, ATMAKUR 6
OOP THROUGH JAVA (R23)

3) Unicode Characters.
4) Escape Sequence characters (\n, \t, \f, \r, \b etc)

4. String Literals: String literals represent objects of String class.


5. Boolean Literals: Boolean literals represent only two values true and false.

OPERATORS

Q) What is an Operator? Explain different types of Operators Using in Java.


An operator is a symbol used to perform operations between operands.
The following are the various operators in java:
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5) Increment and decrement Operators.
6) Conditional Operators.
7) Bitwise Operators.
8) Special Operators.

1 Arithmetic Operators: Arithmetic Operators are use to perform arithmetic calculations. The following
are the arithmetic operators.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division (Remainder)
Example: Let a, b are integer types and c is float type variables. If a=15, b=10 and c=2.5 then
Expression Result
a+b*c 40.0
a+b-c 22.5
a/b 1(decimal part truncated)
a%b 5 (remainder)
15 / 4.5 3.3333333

2 Relational Operators: The relational operators are used to compare two values and it gives
either true or false. These are used to form simple conditions. All the relational operators are applied on
any type of data. The following are the relational operators.
Operator Meaning
< Is Less than
<= Is Less than or equal to
> Is Greater than
>= Is Greater than or equal to
== Is Equal to
!= Is not equal to
Example: Let a=15 and ch=’A’ then
Expression Result
a = = 15 True

AECN, ATMAKUR 7
OOP THROUGH JAVA (R23)

a > 15 False
a< = 10 False
a ! = 13 True
ch = = ‘A’ True
ch > ‘A’ False

3. Logical Operators: Logical operators are used combine two or more conditions and gives the result
either true or false. These conditions are called compound conditions.

Operator Meaning
&& Logical AND
¦¦ Logical OR
! Logical NOT

Logical AND (&&) Operator: This operator gives true if all the conditions are true otherwise it gives
false. The truth table for && operator is as follows:

Condition1 Condition2 Condition1 && Condition2


TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Logical OR ( ¦¦ ) Operator: This operator gives false if all the conditions are false otherwise it gives true.
The truth table for ¦¦ operator is as follows:

Condition1 Condition2 Condition1¦¦ Condition2


TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Logical NOT (!) Operator: This operator negates (opposite) the result of a condition. It means if the
condition is true then it gives false. If the condition is false then it returns true. The truth table for !
Operator is as follows:
Condition ! (Condition)
TRUE FALSE
FALSE TRUE

Example: Let a=15, b=20 then

Expression Result

a==15 ¦ ¦ b== 20 True


a>15&&b>=20 False
a<=15&&b<=20 True
! (a = = 15) False

4. Assignment Operators:
The assignment operators are used to assign (store) a value to a variable. An assignment operator
always consists of a variable on left hand side and expression / constant / variable on right hand side.
There are two types of assignment operators. They are
i. Simple Assignment Operator
ii. Compound Assignment Operators

AECN, ATMAKUR 8
OOP THROUGH JAVA (R23)

Simple Assignment Operator: The equal sign ‘=’ is used as simple assignment operator. The general
format of this operator is as follows:

Expression
;
Variable =
Constant
In the above syntax, the value of Expression / Constant / Variable is assigned to the variable on the left
Variable
hand side of ‘=’ sign.

Eg: x = 35; y = a + b * c; z = y; a = b = 50;

Compound Assignment Operators: The general form of compound assignment operators is as


follows
Compound Expression
Variable
operator = ;
Constant

In the above syntax, the operator can be either +=, –=, *=, /= or %= Variable

Operator Example Meaning


+= a+=b a=a+b
–= a–=b a=a–b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b

5. Increment and Decrement Operators:

Increment Operator (++):


The increment operator is a unary operator. It is used to increase the value of an operand
by 1. The operand must be a variable. The increment operator ‘++’ has different meaning depending on
the position it is used. It means this operator is used in two ways. They are pre-increment and post-
increment.

Pre-increment: If the ‘++’ operator precedes the operand then it is called “Pre increment”. In this
method, the pre-increment operator increments the value of variable first and then the new value is used
in the expression.
For example: c = ++a; means a = a + 1;
c = a;
Post-increment: If the ‘++’ operator succeeds the operand then it is called “Post increment”. In this
method, the old value of the variable is used in expression and then it is incremented.
For example: c = a++; means c = a;
a = a + 1;
Decrement Operator (– –):
The decrement operator is a unary operator. It is used to decrease the value of an operand
by 1. The operand must be a variable. The decrement operator ‘– –’ has different meaning depending on
the position it is used. It means this operator is used in two ways. They are pre-decrement and post-
decrement.

AECN, ATMAKUR 9
OOP THROUGH JAVA (R23)

Pre-decrement: If the ‘– –’ operator precedes the operand then it is called “Pre decrement”. In this
method, the pre-decrement operator decrements the value of variable first and then the new value is used
in the expression.
For example: c = – –a; means a = a – 1;
c = a;
Post-decrement: If the ‘– –’ operator succeeds the operand then it is called “Post decrement”. In this
method, the old value of the variable is used in expression and then it is decremented.
For example: c = a– –; means c = a; a = a – 1;
Initial Values Expression Final Values
A B A B
3 7 a = ++b 8 8
3 7 a = b++ 7 8
3 7 a = – –b 6 6
3 7 a = b– – 7 6
6. Conditional Operator: This operator performs condition based execution. This operator operates on
three operands. Hence it is also known as Ternary Operator. This operator simplifies “if…else” control
statement. The general form of conditional operator is as follows:
Syntax: var = (condition)? Statement1: Statement2;
Working: The conditional operator first evaluates the given condition. If the condition is true then
‘Statement1’ is evaluated. If the condition is false then ‘Statement2’ is evaluated.
Example:-
import java.io.*;
class max
{
public static void main(String args[]) throws IOException
{
int a,b,large;
DataInputStream d=new DataInputStream(System.in);
System.out.print(“Enter First Number”);
a=Integer.parseInt(d.readLine());
System.out.print(“Enter Second Number”);
b= Interer.parseInt(d.readLine());
large = (a>b) ? a : b;
System.out.println(“Large value is “ + large);
}
}
7. Bitwise Operators: Java has the capability of manipulating the bits (0 or 1) directly stored in the
memory. These operators perform bitwise operations on a bit by bit level. However, they must be used
only with integer or character type of values. The operators are as follows.
Operator Meaning
& Bitwise AND
¦ Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
<< Left shift
>> Right shift
>>> Right shift with Zero fill

Bitwise AND (&) operator: If all the bits are “1” then this operator returns “1” otherwise it returns “0”.

AECN, ATMAKUR 10
OOP THROUGH JAVA (R23)

Truth table:
& 1 0
1 1 0
0 0 0
Example: Let x = 15 and y = 19, then z = x & y is as follows
Value of x : 00001111
Value of y : 00010011
Value of z : 00000011
(x & y)

Bitwise OR ( ¦ ) operator: If any or all the bits are “1” then it returns “1” otherwise it returns “0”.
Truth table:
¦ 1 0
1 1 1
0 1 0

Example: Let x = 15 and y = 19, then z = x ¦ y is as follows


Value of x : 00001111
Value of y : 00010011
Value of z : 00011111
Bitwise XOR ( ^ ) (x ¦ y) operator: If one bit is “1” and other is “0”
then it returns “1” otherwise it gives “0”.
Truth table:
^ 1 0
1 0 1
0 1 0

Example: Let x = 15 and y = 19, then z = x ^ y is as follows


Value of x : 00001111
Value of y : 00010011
Value of z : 00011100
(x ^ y)

1’s complement (~) operator: This operator is a unary operator that reverses the state of each bit. That
means it changes “0” as “1” and “1” as “0”.
Example: Let x = 19, then z = ~x is as follows

Value of x : 00010011
Value of z : 11101100
( ~x )

Left Shift (<<) operator:


This operator is used to move bit patterns to the left. It is used in the following form
op<<n
Here, ‘op’ is an integer value and ‘n’ is number of bit positions. The left shift operator shifts all
the bits of operand ‘op’ to the left by ‘n’ positions. The left most ‘n’ bits in the original bit pattern will be
lost and right most ‘n’ bit positions are filled with zeros.

Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:

a 1100110011001111
a<<3  0110011001111000

AECN, ATMAKUR 11
OOP THROUGH JAVA (R23)

a<<5  1001100111100000

The left shift operator is used for multiplication purpose. It means, x<<n gives the result as x*2 n.
Example : 5<<1 gives 10, 5<<2 gives 20, 5<<3 gives 40

Right Shift (>>) operator:


This operator is used to move bit patterns to the right. It is used in the following form
op>>n

Here, ‘op’ is an integer value and ‘n’ is number of bit positions. This operator shifts all the bits of operand
‘op’ to the right by ‘n’ positions. The right most ‘n’ bits in the original bit pattern will be lost and left
most ‘n’ bit positions are filled with zeros.

Example: Let us consider ‘a’ is an unsigned integer whose bit pattern is as follows:

a 1100110011001111
a>>3  0001100110011001
a>>5  0000011001100110
The right shift operators can also be used for division purpose. It means, x>>n gives the result as
x
Example: 15>>1 gives 7, 15>>2
n gives 3, 15>>3 gives 1
2

Right Shift Zero fill (>>>) operator:


When dealing with positive numbers, there is no difference between >>> and >> operators. The
difference arises when dealing with negative numbers. The negative numbers have the higher order bit set
to 1. The Right shift Zero fill operator shifts zeros into all the upper bits, including the higher order bit.
Thus make a negative number into positive number.
op>>>n
8. Special Operators: The following are the special operators used in Java.
1) Instanceof Operator
2) Dot Operator
3) Cast Operator
4) new Operator
 Instanceof Operator: The instanceof is an object reference operator and return true if the object on
the left hand side is an instance of the class given on the right side. This operator determines whether
the object belongs to a particular class or not.

Ex: s1 instanceof student


It gives true if the object person belongs to the class student; otherwise it is false

 Dot Operator: this operator is also called as member selection operator(.) . The Dot Operator is
used to access the instance variables, methods of class objects, classes, and sub-packages from a
package.

Ex: person.age;
person.salary( );

 Cast Operator: Cast operator is used to convert one data type into another data type. This operator
can be used by writing datatype inside parenthesis.

Ex: double x = 10.54;


int y = (int) x; // stores 10 into y.

AECN, ATMAKUR 12
OOP THROUGH JAVA (R23)

 new Operator : new operator is used to create objects to classes. Objects are created on heap
memory by JVM, at runtime.

Java statements
Java Statements are similar to sentences in the natural languages. A sentence forms a complete idea
which can include one or more clauses. Likewise, a statement in Java forms a complete command to be
executed and can include one or more expressions.

The following are the various java statements:

 selection statements( if, if..else, switch).


 Repetitive statements( while, do, for).
 Jums statements( break, continue, return).
 Expression statements.
 Labelled statements.
 Exception handling statements( try, catch, finally).

Implementing a java program


Implementation of java program involves a series of steps. They include;
 creating the program
 compiling the program
 running the program

Creating the program: We can create a program using any text editor.

Ex:

class Sample
{
public static void main(String [ ]args)
{
System.out.println(“ hai”);
System.out.println(“ welcome”);
}
}

 We must save the program file name with .java extension file name properly.
 This file is called source file.
 The file name must be same as its class name.

Compiling the program: to compile the program, we must run the java compiler javac, with the name of
the source file.
Syntax: javac Sample.java

If everything is ok, the javac compiler creates a file called Sample.class containg the byte code of the
program.

Running the java program: we need to use the java interpreter to run a stand-alone program. At the
command prompt, type
Syntax: java Sample

AECN, ATMAKUR 13
OOP THROUGH JAVA (R23)

now, the interpreter looks for the main method in the program and begins execution from there. When
executed, our program displays the following;

hai
welcome

JVM (java virtual machine)


Q. Write about JVM. Or what is a java virtual machine explain?

 All language compilers translate source code into machine code for a specific computer.
 Java compiler also does the same thing.
 The java compiler produces an intermediate code known as byte code for a machine that does not
exist.
 This machine is called java virtual machine(JVM).

Java program Java compiler Virtual machine


Source code Byte code
The process of compiling a java program

The virtual machine code is not machine specific. The machine specific code is generated by the
java interpreter by acting an intermediary between the virtual machine and the real machine.

Byte code Java interpreter Machine code


Virtual machine Real machine
The process of converting byte code into machine code

The java object frame work for java virtual machine is as shown below.

Q. what is a symbolic constant in java?


A symbolic constant is a "variable" whose value does not change during the entire lifetime of the
program.

Ex. The matematical constant PI represents a value is 3.142.

Syntax : final type symbolic-name=value;


Ex: final float pi=3.14;
Rules of symbolic constants:
 Symbolic names taken the same form as variable names.
 After declaration of symbolic constants, they should not be assigned any other value within the
program.

AECN, ATMAKUR 14
OOP THROUGH JAVA (R23)

 Symbolic constants are declared for types


 They cannot be declared inside a method.

Java Command Line Arguments


Q. what are the command line arguments in java explain with examples?

The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console (keyboard) can be received in the java program and it can be used
as an input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1, 2, 3 and so on) numbers of arguments from the command prompt.

1. Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.

class CommandLineExample
{
public static void main(String args[ ])
{
System.out.println("Your first argument is: "+args[0]);
}
}

Compile by > javac CommandLineExample.java

Run by > java CommandLineExample raheem

Output:
Your first argument is: raheem

2. Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.

class A
{
public static void main(String args[ ])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}

Compile by > javac A.java


Run by > java A abdul raheem nellore

Output:
abdul
raheem
nellore

AECN, ATMAKUR 15
OOP THROUGH JAVA (R23)

Java Scanner Class


Q. How to get input from user in Java

Java Scanner class allows the user to take input from the console. It belongs
to java.util package. It is used to read the input of primitive types like int, double, long, short,
float, and byte. It is the easiest way to read input in Java program.

Syntax:
Scanner sc=new Scanner(System.in);

The above statement creates a constructor of the Scanner class having System.inM as an
argument. It means it is going to read from the standard input stream of the program.
The java.util package should be import while using Scanner class.

It also converts the Bytes (from the input stream) into characters using the platform's default
charset.

Methods of Java Scanner Class

Java Scanner class provides the following methods to read different primitives types:

Method Description

int nextInt() It is used to scan the next token of the input as an integer.

float nextFloat() It is used to scan the next token of the input as a float.

double nextDouble() It is used to scan the next token of the input as a double.

byte nextByte() It is used to scan the next token of the input as a byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() It is used to scan the next token of the input into a boolean value.

long nextLong() It is used to scan the next token of the input as a long.

short nextShort() It is used to scan the next token of the input as a Short.

BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.

BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.

AECN, ATMAKUR 16
OOP THROUGH JAVA (R23)

import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
}
}

CONSTANTS, VARIABLES AND DATA TYPES

Q. What is a constant? What are the various types of constants? Explain it with examples?

A Constant is a fixed value that does not change during the execution of the program. Java supports
several types of constants.

1) Numeric Constants
2) Character Constants
3) Symbolic Constants

1) Numeric Constants: - The numeric constants are two types they are
a) Integer Constants
b) Floating point Constants

Integer Constants: - A number without decimal portion is known as Integer constants.

0 2 9 -25 986-- Decimal


0 056 0654 0765 0567 Octal
0x 0x9 0xAAF 0x12CF 0XDFF Hexadecimal
Ex:- 30, 043, 0XAB

Floating point Constants: - A number with decimal portion is known as Floating point
Constants
Ex:- 30.70, 0.08E4, 0.008E-4

2) Character Constants: - The Character constants are two types they are
a) Single Character Constant
b) String Constant

Single Character Constant: - A Single Character Constant which is enclosed between single
quotes is known as Single Character Constants.
Ex:- ‘A’, ‘b’, ‘5’, ‘?’

AECN, ATMAKUR 17
OOP THROUGH JAVA (R23)

String Constant: - A String Constant is group of characters which are enclosed between double
quotes is known as String Constant.
Ex:- “ABC”, “Ravi”, “1234” etc.

Backslash Character constants:


Java supports some special backslash character constants that are used in output methods. For
example the symbol ‘\n’ stands for new line character. A list of such backslash character constants are
given below. These character combinations are known as “Escape Sequences”.
Constant Meaning
‘\b’ Back Space
‘\f’ Form Feed
‘\n’ New Line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quotes
‘\”’ Double quotes
‘\\’ Back Slash
VARIABLES

Q. what is a Variable. Explain its declaration and initializations?

A variable is an identifier that denotes a storage location used to store a data value. A variable may take
different values at different times during the execution of the program. Examples of the program are

Ex: average height total_height classStrength etc.

Variable names may consist of alphabets, digits, underscores and dollar characters.

Rules for Variable Names:


1) They must not begin with a digit.
2) Uppercase and Lowercase are distinct. This means Total is not same as TOTAL.
3) It should not be a keyword.
4) White space is not allowed.
5) Variable names can be of any length.

Declaration of Variables:
Variables are the names of storage locations. After designing variable names, we must declare them to the
compiler. Declaration does three things.

1) It tells the compiler what the variable name is.


2) It specifies what type of data the variable will hold.
3) The place of declaration decides the scope of the variable.

A variable must be declared before it is used in the program. Syntax for declaration of a variable is as
follows.

Syntax : Datatype variable1, variable2, variable3…………….variablen;

Eg:- int count; float x, y; double p1;

Q. Explain how to Giving values to Variables?


A variable must be given a value after it has been declared and before it is used in an expression. This can
be achieved in two ways.

1) By using an assignment statement.


2) By using a read statement.

AECN, ATMAKUR 18
OOP THROUGH JAVA (R23)

Assignment Statement: A simple method of giving value to a variable is through Assignment statement.
Syntax: Variablename = value;
Ex: initialvalue = 0;
finalvalue = 100;
y = ‘x’;
It is also possible to assign a value to a variable at the time of its declaration. The process of giving initial
values to variables is known as “initialization”.

Syntax: Datatype variablename = value;

Ex: int finalvalue = 100;


double total = 75.36;
Read Statement: We may also give values to variables interactively through the keyboard using the
“readLine( )” method.

Ex: DataInputStream ds = new DataInputStream(System.in);


int x=Integer.parseInt(ds.readLine( ));

The readLine( ) method reads the input from the keyboard as a string.

Q. Explain Scope and Life time of variables?


The area of the program where the variable is accessible is called its scope. A block is begun with an
opening brace and ended by a closing curly brace. Java allows variables to be declared with in any block.
A block defines a scope.
The scope defined by a method begins with its opening brace. However, if that method has parameters,
they are also included within the method’s scope.
Variables declared inside a scope is not visible to code that is defined outside that scope. Thus, when you
declare a variable within a scope, you are localizing that variable and protecting from unauthorized access
and modification.
Java variables are classified into three types.
1) Instance variables.
2) Class variables.
3) Local variables.

Instance variables:
Instance variables are declared inside a class. Instance variables are created when an objects are
instantiated and therefore they are associated with the object. They take different values for each object.

Class Variables:
Class variables are global to a class and belong to the entire set of objects that class creates. Only one
memory location is created for each class variable.

Local variables:
Variables declared and used inside methods are called local variables. They are not available for use
outside the method definition. Local variables can also be declared inside program blocks that are defined
between an opening brace and a closing brace ( { } ).
{

int x = 0;
{
-------
int n = 5;
------- Block 2
}

{
-------
int m = 10;
Block3
-------
}
}

Block 1
}

}
AECN, ATMAKUR 19
OOP THROUGH JAVA (R23)

Each block contains its own set of local variable declarations. In the above figure the variable x declared
in block 1 is available in all the three blocks. The variable n declared in block 2 and is available only in
block 2. Similarly m is accessible in block 3 only.

Q. Explain how to getting values of variables?

A computer program is written to manipulate a given set of data and to display or print the results. Java
supports two output methods that can be used to send the result to the screen.

 print( ) method // print and wait


 println( ) method //print a line and move to next line

print( ) method: This method sends information into a buffer. This buffer is not end until a new line
character is sent. The print( ) method prints output on one line until a new line character is encountered.

Ex: System.out.print(“hai”);
System.out.print(“wel come”);
Will display the words hai wel come on one line and waits for displaying further information on the same
line. For this we use the next line by printing a new line character as shown below:

System.out.print(‘\n’);

For example, the statements:

System.out.print(“hai”);
System.out.print(‘\n’);
System.out.print(“wel come”);

Will display two lines as follows: hai


Wel come

println( ) method: It takes the information provided and displays it on a line followed by a line feed.
Ex: System.out.println(“hai”);
System.out.println(“wel come”);
Will produce the following output: hai
Wel come

Q. what is type casting in java?

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or
interface.

Syntax: type variable1=(type)variable2;

Ex: Class Typecast


{
public static void main(String arg[])
{
int a = 350;
byte b;

b = (byte) a;
OUTPUT
System.out.println("b = " + b );
b = 94
}
}

AECN, ATMAKUR 20
OOP THROUGH JAVA (R23)

DATA TYPES

Q. What is a Data type? Explain different data types?

Every variable in java has a data type. Data type specifies the size and type of values that can be stored.
The data type allows the programmer to select the type appropriate to the needs of the application.

Data types in Java

Primitive Non-Primitive

Numeric Non-Numeric Classes Arrays Arrays

Integer Floating Point Character Boolean


Primitive data types are also called built-in types and non primitive data types are also called ‘Derived
data types or reference Types’.
Integer Types:
Integer types can hold whole numbers such as 123, -96, 5639 etc. the size of the values that can be stored
depends on the integer data type we choose. Java supports 4 types of integer data types. They are byte,
short, int, long. Java does not support the concept of unsigned.
Type Size Minimum Value Maximum Value
byte 1 Byte -128 127
short 2 Bytes -32768 32767
int 4 Bytes -2,147,483,648 2,147,483,647
long 8 Bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Floating point types:


Floating point types can hold numbers containing fractional parts such as 27.59,-1.375. There are two
types of Floating point types in Java. They are float, double.
 The float type values are single – precision numbers.
 The double type values are double – precision numbers.
Type Size Minimum Value Maximum Value

float 4 Bytes 3.4e-038 1.7e+038

double 8 Bytes 3.4e-308 1.7e+308

Character Type: In order to store character constants in memory, Java provides a character data type
called ‘char’. The char data type reserves 2 bytes of memory but it can hold only a single character.
Boolean Type: Boolean type is used when we want to test a particular condition during the execution of
the program. There are only two values that a Boolean type can hold: true or

AECN, ATMAKUR 21
OOP THROUGH JAVA (R23)

CHAPTER: DECISION MAKING & BRANCHING


Control Structures
Control structures are used to change the execution sequence of a program. In Java ‘language, the
control statements are classified into 3 types. They are as follows:

Control Statements

Conditional Repetitive or Iterative Unconditional or Jumping


Control Statements Control Statements Statements

If Statement while continue


if...else Statement do...while break
Switch Statement for return
Conditional Operator

Conditional Control Statements


The Conditional Control Statements are also known as Decision Making statements. These
statements execute a particular group of statements depending on the given condition. There are mainly
two types of conditional statements. They are;
1. if or if…else statement
2. switch statement
Flowchart:
►if statement:-
The ‘if’ statement is a conditional control statement that
executes the set of statements based on the condition.
The general form of simple if statement is
Condition T
if ( Condition )
{
Statement – block;
}
F Statement-block
Working: if the condition is true, then the statement block
will be executed. Otherwise the statement block will be
skipped and the execution will jump to the next statement
after the statement block.
The statement - block may be a single statement or a
group of statements. If there is only a single statement in the statement block, there is necessity of curly
braces ({ }).

Examples:
1. if (avg >= 75)
System.out.println(“grade is distinction”);
2. if (a < 0)
a++; Flowchart:

► If…else statement:
It is also conditional control statement that FALSE TRUE
Condition
executes the statements based on the condition. The
if..else statement is an extension of simple if statement.
The general form is
Statement-block2 Statement-block1
if ( Condition )
Statement – block1;
else
AECN, ATMAKUR Statement – block2; 22
OOP THROUGH JAVA (R23)

Working: if the Condition is true then the statement – block 1 will be executed. Otherwise the statement
– block2 will be executed.
Ex : if (n%2==0)
System.out.println(“Even Number”);
else
System.out.println(“Odd Number”);

► Nested if…else statement:


When the ‘if..else’ statement is used within another ‘if…else’ statement then it is called “nested
if” statement. The general format is as follows:
Syntax:
if (condition1)
{
if (condition2)
statement-block1 ;
else
statement-block2 ;
}
else
{
if (condition3)
statement-block3 ;
else
statement-block4 ;
}
In the above syntax,
i. If ‘condition1’ and ‘condition2’ are true then stament-block1 is executed
ii. If ‘condition1’ is true and ‘condition2’ is false then stament-block2 is executed
iii. If ‘condition1’ is false and ‘condition3’ is true then stament-block3 is executed
iv. If ‘condition1’ and ‘condition3’ are false then stament-block4 is executed

T Cond-1 F

T Cond-2 F T Cond-3 F

Statement-block1 Statement-block2 Statement-block3 Statement-block4

Ex: Class Nesting


{
public static void main(String args[])
{
int a=3,b=7,c=4;
Sytem.out.print(“Larget value is : “);
if( a>b)
{
if(a>c)
System.out.println(a);
else
System.out.println(b);
}
else

AECN, ATMAKUR 23
OOP THROUGH JAVA (R23)

{
if (b>c)
System.out.println(b);
else
System.out.println(c);
}
}
}

►Switch Statement:
The ‘switch’ statement is a multiple condition statement. It can be used to make a decision from
the number of choices. It is an extension of ‘if…else’ statement. The general format of switch statement is
as follows:
Syntax:
switch (op)
{
case v1 : statement-block1;
[break;]
case v2 : statement-block2;
[break;]
: :
: :
case vn : statement-block-n;
[break;]
[default : statement-block-d;]
In the above } syntax, ‘op’ is an integer or character.
V1, V2, …, Vn are the constants that represent
the value of ‘op’. These are the constants of either integer or character type.
Working:
The switch statement searches for a match of switch variable (op) and case constants (v1, v2, …,
vn). If a value matches to the ‘op’, then the switch
statement executes all the statements in that case-
block. Flowchart With break
If there is ‘break’ statement is used in that Switch without break:
block then it terminates the execution of switch
statement. If ‘break’ is not present, then all the Switch with break:
statements of remaining blocks are executed. Switch (op)
Example :
Class Example
{
public static void main(String args[])
{ Case V1 T
Statement-block1
int op=3;
switch (op)
{ F
case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”); Case V2 T
Statement-block2
break;
case 3: System.out.println( “Tuesday”);
break; F
case 4: System.out.println(“Wednesday”);
break;
Case Vn T
case 5: System.out.println(“Thursday”); Statement-block-n
break;

F
AECN, ATMAKUR 24
OOP THROUGH JAVA (R23)

case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default:System.out.println(“Wrong Value”);
}
}
}

REPETITIVE (OR) LOOPING (OR) ITERATIVE CONTROL STRUCTURES

The repetitive control statements are used to execute a group of statements repeatedly for a
specified number of times. The repetitive control statements are also called Iterative (or) Looping control
statements.
In Java, there are 3 types of repetitive control structures. They are
1. While Statement
2. Do…while Statement
3. For Statement

►While Statement (while loop):


This statement is used to execute one or more
statements repeatedly as long as the specified condition is
satisfied. It is an entry control loop structure.
Syntax: T
condition
while (condition) Statement-block
{
statement-block;
} F
In the above syntax,
1. The ‘condition’ is a relational expression that must be
enclosed within parenthesis.
2. The statement-block specifies one or more statements. When there is more than one statement,
they must be enclosed in braces ({}).
Working: The ‘while’ statement executes all the statements in the statement-block as long as the
condition returns true (non-zero) value. When the condition returns false (0) then the loop is terminated
and the control is transferred to the statement after the statement-block.
Ex : class ExWhile
{
public static void main(String args[ ])
{
int i=1;
while(i<=100)
{
System.out.print(i);
++i;
}
}
}
o/p: 1 2 3 4 …….100

► Do…While Statement:
This statement is used to execute one or more statements repeatedly as long as the specified
condition is satisfied. It is an exit control loop structure. The do…while structure executes the statement
part at least one time either the condition is true or false.

AECN, ATMAKUR 25
OOP THROUGH JAVA (R23)

Syntax:

do
{
statement-block;
} while (condition) ;

Example :
class ExDoWhile
{
public static void main(String args[ ])
{
int i=1;
do
{
System.out.print(i);
++i;
} while(i<=100); o/p: 1 2 3 4 …….100
}
}

► for Statement :
This statement is used to execute a set of statements repeatedly as long as the specified condition
is satisfied. It is an entry control loop structure.
Syntax:
for(initialisation ; condition ; increment/decrement)
{
statement-block;
}

working: It evaluates the initialization part first and then it checks the condition. If the condition is true
then it executes all the statements in the statement-block. After executing all the statements,
increment/decrement part is executed. This looping process is continued as long as condition is true.
When the condition becomes false, the loop is terminated.
Example
class ExFor Flowchart:
{ Initialization
public static void main(String args[ ])
{
int i;
for(i=1 ; i<=100 ; i++) condition
Statement-block
System.out.print(i);
}
}
Increment /
o/p: 1 2 3 4 …….100
Decrement

decrement

UNCONDITIONAL CONTROL STRUCTURES or JUMPS IN LOOPS

The unconditional control statements are used to change the execution sequence of a program by
transferring the control from one place to another place within a program without using any condition.

The following are the unconditional control structures (Jumps in loops) used in Java language.

AECN, ATMAKUR 26
OOP THROUGH JAVA (R23)

1. break
2. continue
3. return

►break Statement:
The break statement can be used in three ways.
1) break is used inside a loop to come out of it.
2) break is used inside the switch statement to come out of the block.
3) break is used in nested blocks to go to the end of the block.
Syntax:
break ; (or) break label;
Example:
class ExBreak class ExBreak
{ {
public static void main(String args [ ]) public static void main(String args [ ])
{ {
int i; int i, j;
for(i=1;i<=100;i++) outer : for(i=1;i<=100;i++)
{ {
System.out.print( i ); Inner : for (j=1; j<=100; j++)
if(i==50) {
break; System.out.print( j );
} if(j==50)
} break outer;
} o/p: 1 2 3 4 …….50 }
}
}
}
►Continue Statement:
Continue statement is used inside a loop to repeat the next iteration of the loop. When continue
statement is executed, the next statements in the loop are not executed and control of execution goes back
to the next repetition of the loop.
Syntax:
Continue ; (or) continue label ;
Example:
class ExConinue class ExContinue
{ {
public static void main(String args [ ]) public static void main(String args [ ])
{ {
int i; int i, j;
for(i=1 ; i<=10; i++) outer : for(i=1; i<=10; i++)
{ {
if(i==4 || i==7) Inner : for (j=1; j<=10; j++)
continue; {
System.out.print( i ); if(j==4 || j==7)
continue outer;
} System.out.print( i );
} }
} o/p: 1 2 3 5 6 8 9 10 }
}
}

AECN, ATMAKUR 27
OOP THROUGH JAVA (R23)

►return Statement :
return statement is used in a method to come out of it to the calling method. return statement is
often used in the methods.
Examples :
return (x+y); //calculates x+y and return that value
return -5; // return -5 to the calling method.

class Demo
{
public static void main( String args [ ] )
{
int res=Demo.square(10);
System.out.println(“Result = “ + res);
}
static int square(int num)
{
return num * num;
}
}

OP : Result = 100

Demo.square ( 10 ) return num * num

AECN, ATMAKUR 28
OOP THROUGH JAVA (R23)

UNIT-II

CLASSES, OBJECTS AND METHODS


Class:
A class is a collection of related objects that share common properties and actions. Classes are used to
pack a group of data items and functions. In java, the data items are called fields and functions are called
methods.

Defining a class:
Once a class is defined, we can create any number of objects belonging to that class. In java these
“variable” are called as instances of classes. Classes are defined using the keyword “class”.
Syntax :
class classname extends superclassname
{
[fields declaration ; ]
[methods declaration ;]
}

►Fields Declaration:
The variables which are declared inside a class are called fields. These variables are also called instance
variables because they are created whenever an object of the class is instantiated.
Ex: class Rectangle
{
int length;
int width;
}
The class Rectangle contains two integer type instance variables. No memory space is reserved for these
instance variables.

►Methods Declaration:
Methods are necessary for manipulating the data contained in the class. Methods are declared and defined
inside the body of the class immediately after the declaration of instance variables.
Syntax :
Returntype Methodname (Parameter – list)
{
Method Body;
}
Methods declaration have four basic parts
1. The name of the method (method name)
2. The type of the value that the method returns (return type)
3. A list of parameters (Parameter – list)
4. The body of the method.
Ex : class Rectangle
{
int length;
int width;
void getdata ( int x, int y )
{
length = x;
width = y;
}
}

AECN, ATMAKUR 29
OOP THROUGH JAVA (R23)

►Objects:
An object is a block of memory that contains space to store all the instance variables.

Creating Objects:
 Creating an object is also referred as Instantiating an object.
 In java objects are created using the operator new.
 The new operator creates an object of the specified class and returns a reference to that object.
Syntax 1:
Classname objname;
objname = new Classname ( );
Syntax 2:
Classname objname = new Classname ( );
Example:
Person p; // Declares the object
p = new Person ( ); // instantiate the object

The above two statements can also be combined as


Person p = new Person ( );
P
 Person p; null
P
Defing
 p = new Person ( );
Person
now p is a reference to Person object. Object

►Accessing Class Members:


We cannot access the instance variables and methods directly from outside the class. To access them from
outside the class, we must use the concerned object and the dot (.) operator.
Syntax :
Objectname.variablename = value;
Objectname.methodname(parameter-list);
Here objectname is the name of the object, variablename is the name of the instance variable
inside the object.
Example :
class A class Ex
{ {
int x,y; public static void main(String args[])
void getData(int m,int n) {
{ A a=new A( );
x=m; a.getData(10,20);
y=n; a.disp( );
} }
void disp( ) }
{
System.out.println(x); O/P : 10
System.out.println(y); 20
}
}

AECN, ATMAKUR 30
OOP THROUGH JAVA (R23)

Constructors
Constructor is a method used to initialize the instance variables of an object. Constructors are executed
when we create an object. Objects are created using the keyword new. The constructor must be same as
class name.

Java supports two types of constructors. They are:


1) Default constructors
2) Parameterized constructors.

►Default Constructor:
The Default constructor is the constructor that accepts zero arguments.
Syntax :
Constructorname( )
{
Constructor Body;
}
►Parameterized Constructor :
The Parameterized constructor is the constructor that accepts at least one argument.
Syntax :
Constructorname( Parameters list )
{
Constructor Body;
}

A constructor of a class may be either a default constructor or parameterized constructor.

Rules for defining constructors


 The constructor’s name and class name must be same.
 Constructors should not have any return type, even void.
 Constructors may or may not have parameters.
 A class can have more than one constructor.
 Constructor can use any access modifier.
 Interfaces should not have any constructors.

Example :
class Sample class Example
{ {
int x,y; public static void main(String args[])
Sample( ) {
{ Sample s1 = new Sample( );
x = 0; Sample s2 = new Sample( 10,20);
y = 0; s1.display( );
} s2.display( );
Sample( int a,int b) }
{ }
x = a;
y = b;
} Output : X = 0 Y= 0
void display( ) X = 10 Y= 20
{
System.out.println(“ X = “ + x);
System.out.println(“ Y = “ + y);
}
}

AECN, ATMAKUR 31
OOP THROUGH JAVA (R23)

Method Overloading in Java

If a class is create methods that have same name but different parameters and different definitions. It is
known as Method Overloading. Method overloading is used when objects required performing same
tasks but using different parameters. It is also called polymorphism.
 Method overloading increases the readability of the program.

Different ways to overload the method: There are two ways to overload the methods in java
1. By changing number of arguments
2. By changing the data type

Example 1: Method Overloading by changing the no. of arguments


In this example,
 we have created two overloaded methods,
 first sum method performs addition of two numbers and
 second sum method performs addition of three numbers.

class Calculation
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c); Output:30
} 40
public static void main(String args[])
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Example 2: Method Overloading by changing data type of argument
In this example,
 we have created two overloaded methods that differs in data type.
 The first sum method receives two integer arguments and
 second sum method receives two double arguments.

class Calculation2
{
void sum(int a,int b) Output: 21.0
{ 40
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);

AECN, ATMAKUR 32
OOP THROUGH JAVA (R23)

obj.sum(20,20);
}
}

Overriding Methods

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method that is already


provided by its super class.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. Method must have same name as in the parent class


2. Method must have same parameter as in the parent class.
3. Must be IS-A relationship (inheritance).

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.

class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}

public static void main(String args[ ])


{
Bike2 obj = new Bike2();
obj.run();
}

Output: Bike is running safely

AECN, ATMAKUR 33
OOP THROUGH JAVA (R23)

Q. Explain the Difference between method overloading and method overriding in java?

There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding


Method overriding is used to provide the
Method overloading is used to increase the readability of specific implementation of the method
1)
the program. that is already provided by its super
class.
Method overriding occurs in two classes
2) Method overloading is performed within class.
that have IS-A (inheritance) relationship.
In case of method overloading, parameter must be In case of method overriding, parameter
3)
different. must be same.
Method overloading is the example of compile time Method overriding is the example of run
4)
polymorphism. time polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return type can Return type must be same or covariant in
5)
be same or different in method overloading. But you must method overriding.
have to change the parameter.

Static Members
Basically a class contains two sections. One declares variables and the other declares methods. These
variables and methods are called instance variables and instance methods.
The members that are declaring with the static key Word are called static members.

Syntax: static int a;

The methods that are declared with the static keyword are called static methods

Syntax: static int large(int x, int y)

The static variable and static methods can be called without using the objects. They are also available for
use by other classes.

Ex: Defining and using static members


class Math
{
static float mul(float x, float y)
{
return x*y;
}
static float divide(float x, flaot y)
{
return x/y;
}
}
class Mathoperations
{
Public static void main(String [ ]args)
{ Output:
float a=Math.mul(4.0,5.0); b=10.0

AECN, ATMAKUR 34
OOP THROUGH JAVA (R23)

float b=Math.divide(a,2.0);
System.out.println(“b=”+b);
}
}
The above static methods are called using class names. In fact, no objects have been created for use.

Static methods have several restrictions:


 They can only call other static methods.
 They can only access static data.
 They cannot refer to this or super in any way.

Nesting of methods

Q. Explain Nesting of methods with example?

A method can be called by using only its name by another method of the same class is called Nesting of
methods.

Ex: The class Nesting defines one constructor and two methods, namely largest( ) and display( ). The
method display( ) calls the two numbers and then display the result.

Class Nesting
{
int m,n;
Nesting( int x, int y) // constructor method
{
m=x;
n=y;
}
int( larrgest( )
{
If(m>=n)
return(m);
else
return(n);
}
void display( )
{
int large=largest( ); // calling a method
system.out.println(“largest value=”+large);
}
}
class NestingTest
{
public static void main(String []args)
{
Nestint test=new Nesting(50,40 );
test.display();
}
}

Output:

Largest value= 50

AECN, ATMAKUR 35
OOP THROUGH JAVA (R23)

Q. Explain Final variables and methods?


All methods and variables can be overriding (redefine) by default in sub class. If we wish to prevent the
subclass from overriding the members of the superclass, we can declare as final using final as a modifier.

Ex: final int a=10;


final void show( )
Making a method final ensures that the functionality defines in this method will never be altered
in any way.
Similarly,
 The value of a final variable can never be changed.
 Final variables, behave like the class variables and they do not take any space on
individual objects of the class.

Q. Explain about Final classes?

Sometimes we want to prevent a class being further sub classes for security reasons. A class that cannot
be sub classed is called a final class. This achieved in java using the keyword final.

Ex: final class A(…)


final class B class extends some class(….)

Declaring a class final prevents any unwanted extensions to the class.


Static Members
Basically a class contains two sections. One declares variables and the other declares methods. These
variables and methods are called instance variables and instance methods.
The members that are declaring with the static key Word are called static members.

Syntax: static int a;

The methods that are declared with the static keyword are called static methods

Syntax: static int large(int x, int y)

The static variable and static methods can be called without using the objects. They are also available for
use by other classes.

Ex: Defining and using static members


class Math
{
static float mul(float x, float y)
{
return x*y;
}
static float divide(float x, flaot y)
{
return x/y;
}
}

AECN, ATMAKUR 36
OOP THROUGH JAVA (R23)

class Mathoperations
{
Public static void main(String [ ]args)
{ Output:
float a=Math.mul(4.0,5.0); b=10.0
float b=Math.divide(a,2.0);
System.out.println(“b=”+b);
}
}
The above static methods are called using class names. In fact, no objects have been created for use.

Static methods have several restrictions:


 They can only call other static methods.
 They can only access static data.
 They cannot refer to this or super in any way.

Nesting of methods

Q. Explain nesting of methods with example?

A method can be called by using only its name by another method of the same class is called Nesting of
methods.

Ex: The class Nesting defines one constructor and two methods, namely largest( ) and display( ). The
method display( ) calls the two numbers and then display the result.

Class Nesting
{
int m,n;
Nesting( int x, int y) // constructor method
{
m=x;
n=y;
}
int( larrgest( )
{
If(m>=n)
return(m);
else
return(n);
}
void display( )
{
int large=largest( ); // calling a method
system.out.println(“largest value=”+large);
}
}
class NestingTest
{
public static void main(String []args)
{
Nestint test=new Nesting(50,40 );
test.display();

AECN, ATMAKUR 37
OOP THROUGH JAVA (R23)

}
}

Output:

Largest value= 50

Recursion: A recursive method is a method that calls itself either directly or indirectly through another
method. A method call itself is termed as Recursion.
Example: fact(n) = 1 ; if n=0
n*fact(n-1) ;n1
// Write a program to print the factorial of a given number using recursion
class a
{
double fact(double x)
{
if(x==0)
return 1;
else
return x*fact(x-1);
}
}
class recur
{
public static void main(String[] args)
{
a obj=new a();
int p=Integer.parseInt(args[0]);
double t=obj.fact(p);
System.out.println("facatorial="+t);
}
}
// Write a program to print the first n Fibonacci sequence numbers using recursion
(Lab Program: 2)
class a
{
int f(int x)
{
if(x==0||x==1)
return x;
else
return (f(x-1)+f(x-2));
}
}
class fibo
{
public static void main(String[] args)

AECN, ATMAKUR 38
OOP THROUGH JAVA (R23)

{
a obj=new a();
int p=Integer.parseInt(args[0]);
for(int i=1;i<=p;i++)
{
int t=obj.f(i);
System.out.println(" "+t);
} }}
// Write a program to print the sum of ‘n’ numbers using the recursive formula
sum (n) = 0 ; if n = 0
n + sum(n-1) ; if n  1

Nested Class and Inner Classes It is possible to define a class within another class such classes are
known as nested classes. A nested class has access to all of the variables and methods of its outer class.
But the outer class doesn’t access the variables and methods of nested class. Since the scope of a nested
class is bounded by the scope of its enclosing class.
There are two types of nested classes: static and non-static
A static nested class is a class started with ‘static’ modifier. Due to the static it must access the members
of its enclosing class through an object. Direct access cannot be possible.
A non-static class is a class as ordinary representation of class. The most important type of the non-static
class is “Inner class”. The inner class has access to all of the variables and methods of its outer class.
Thus, inner class scope is fully within the scope of its outer class.
Example:
class outer
{
int out_x=34;
void test()
{
inner in=new inner();
in.display();
}
class inner
{
void display()
{
System.out.println("value="+out_x);
}
}
}
class test
{
public static void main(String[] args)
{
outer y=new outer();
y.test();
}

AECN, ATMAKUR 39
OOP THROUGH JAVA (R23)

}
Argument Passing: Arguments passed to a sub-routine (method) is falls into two categories.
1. Call by value
2. Call by reference
1. Call by Value: Call by value copies the value of an argument into the formal parameter of the sub-
routine. Therefore, if changes made to the parameter of the sub-routine have no effect on the argument
used to call it.
Example:
class Test
{
void meth(int i, int j)
{
i*=2; j/=2;
}
}
class cbv
{
public static void main(String[] args)
{
Test obj=new Test();
int a=4,b=7;
System.out.println("Before calling a="+a+" b="+b);
obj.meth(a,b);
System.out.println("After calling a="+a+" b="+b);
}
}
O/P: Before calling a=4 b=7
After calling a=4 b=7

2. Call by Reference: In this method, a reference to an argument is passed to the parameter. Inside the
parameter, this reference is used to access the actual argument specified in the call. Therefore, any
changes made to the parameter will effect the argument used to call it. This one is also referred as
passing an object as parameter to a method.
Example:
class Test
{
int a,b;
Test(int i,int j)
{
a=i; b=j;
} O/P: Before calling a=4 b=5
void meth(Test ox) After calling a=8 b=2
{
ox.a*=2;
ox.b/=2;
}
}

AECN, ATMAKUR 40
OOP THROUGH JAVA (R23)

class cbr
{
public static void main(String[] args)
{
Test obj=new Test(4,5);
System.out.println("Before calling a="+obj.a+" b="+obj.b);
obj.meth(obj);
System.out.println("After calling a="+obj.a+" b="+obj.b);
}
}

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifier in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.

AECN, ATMAKUR 41
BTech - II YEAR OOP THROUGH JAVA

UNIT : IV :: PACKAGES
DEFINING PACKAGE: Packages are containers for classes that are used to keep the class name space
compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.

A package is a container of classes and interfaces. A package represents a directory that contains related
group of classes and interfaces. For example, when we write statemens like:

import java.io.*;

Here we are importing classes of java.io package. Here, java is a directory name and io is another sub
directory within it. The ‘*’ represents all the classes and interfaces of that io sub directory. We can create
our own packages called user-defined packages or extend the available packages. User-defined packages
can also be imported into other classes and used exactly in the same way as the Built-in packages.

USE: Packages provide reusability.

ADVANTAGES OF PACKAGES:

Packages are used to group a variety of classes and/or interfaces. The grouping is usually done according to
functionality. Packages act as containers for classes. The following are benefits for packages.
1. The classes contained in the packages of other programs can be easily reused.
2. In packages classes can be unique compared with classes in other packages i.e., two classes in two
different packages can have the same name.
3. Packages provide a way to “hide classes”.
4. Packages also provide a way for separating “design” from coding.
Different Types of Packages: There are two types of packages in Java. They are:
 Built-in packages
 User-defined packages

Built-in packages: Java Built-in (API) provides a large number of classes grouped into different
packages according to functionality. Most of the time, we use the packages available with java API.
The following diagram shows the functional break down of packages that are frequently used in the
program. JAVA

Lang util applet awt net io


Java system packages and classes:

The following table shows the java system packages and their classes.

Packages Contents

1.) java. lang Language support classes. These are classes that java compiler itself uses and
there fore they are automatically imported. They include classes for primitive

1
BTech - II YEAR OOP THROUGH JAVA

types, strings, math functions, threads and exceptions.

2.) java. Util Language utility classes such as vectors, hash tables, random numbers, date, etc.

3.) java .io Input/output support classes. They provide facilities for the input and output of
data.

4.) java.awt Set of classes for implementing graphical user interface. They include classes for
windows ,buttons ,lists, menus etc.

5.)java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.

6.) java.applet Classes for creating and implementing applets.

Using system packages: There are two ways of accessing the classes stored in a package. The first
approach is to use the fully qualified class name of the class that we want to use. This is done by using the
package name containing the class and then appending the class name to it using dot operator (.) for
example
If we want to refer to the class ‘Colour’ in the ‘awt’ package then we may do so as follows.
java . awt . Colour
The second approach is to use the import statement. To add package in your classes use ‘import statement’.
This import statement appears at the top of the file before any class declarations, import is a keyword.
import packagename. Classname;
import package name. *;

Naming conventions:-
The following are naming conventions used for packages
1. All package names begin with lower case letter.
2. Every package name must be unique to make the best use of package.
3. Duplicate names will cause run-time errors.
Eg:- hyd.syntel.package
Here hyd denotes name of the city and syntel denotes name of the organization.
4. A user can create a hierarchy of packages with in the package by separating levels with dots.
2. User-defined packages:
Creating packages:To create user defined package, first declare the name of the package using the
‘package’ keyword followed by a package name. This must be the first statement in java source file(except
for comments and white spaces). Then we define a class as we normally define a class.
Syntax:-
package packagename;
public class ClassName
{
Body of the class;
}
Ex: - package pack;
public class A
{
Body of the class A
}

2
BTech - II YEAR OOP THROUGH JAVA

In the above example, the package name is a ‘pack’. The class ‘A’ is now considered as a part of this
package. This listing would be saved as a file called “A.java”, and located in a directory named “pack”.
When the source file is compiled, java will create an “A .class” file and store it in the same directory.The
“.class” files must be located in a directory, that has the same name as the package and this directory should
be a sub directory of the directory where classes that will import the package are located.
A java package file can have more than one class definition. In such cases only one of the classes
may be declared “public” and that class name with “.java” extension is the source file name. When a source
file with more than one class definition is compiled, java creates independent “.class” files for those classes.

Accessing user defined packages:Java system package can be accessed using “import” statement. The
same approaches can be used to access the user defined package as well. The import statement can be used
to search a list of package for a particular class.

Syntax:-
import package1. [package2].[package3].ClassName;
Here package1 is the name of the top level package, package2 is the name of the package i.e. inside the
package1 and so on we can have any number of packages in a package hierarchy finally the “explicit” class
name is specified and end with semicolon (;). Another approach to access package is
import package1.*;
Here package may denote a single package or a hierarchy of packages. The asterisk (*) indicates that the
compiler should search this entire package hierarchy when it encounters a class name. This implies that we
can access all classes contain in the above package directly.
Using a package

Package file:-

package pack1;
public class A
{
public void displayA ()
{
System.out.println (“A”);
}
}
The above file should be named A .java and stored in the sub directory ‘pack’, and compile this java file the
resultant A class will be stored in the same sub directory.

Class file:-
import pack1.A;
class PackageTest
{
public static void main (String args[ ])
{
A obj=new A( );
obj.displayA( );
}
}

3
BTech - II YEAR OOP THROUGH JAVA

The above simple program that imports the class ‘A’ from the package pack1, The source file be
supposed to save as ‘PackageTest’ Java and then compile now we can run the program and obtain the
result.
Inheriting package classes:-
import pack1.A;
class Inher extends A
{
void displayB()
{
System.out.println (“class Inher”);
displayA();
}
}
class PackageTest2
{
public static void main (String args[ ])
{
Inher obj=new Inher( );
obj.displayB( );
}
}
Adding a class to package:-
It is simple to add a class to an existing package. Consider the following package.
package pack1;
public class A
{
Body of the class;
}
The package p1 contains one public class by name A. Suppose we want to add another class B to this
package this can be done as follows:
1. Define the class and make it public.
2. Place the package statement.
[package pack1;] Before the class definition as follows
package pack1;
public class B
{
Body of the class
}
3. Store this as B.java file under the directory pack1.
4. Compile B.java file. This will create a B.class file and place it in the directory pack1.
Now the package pack1 will contain both the classes A and B.
Hiding classes:-
When we import a package using asterisk (*), all public classes are imported. However, we may
prefer not to import certain classes i.e., we may like to hide these classes from accessing outside the
package. Such classes should not be declared public.
Eg:-
package p1;
4
BTech - II YEAR OOP THROUGH JAVA

public class X //available to outside


{
Body of X
}
Class Y //not public-not available to outside
{
Body of Y
}
Here the class Y which is not declared public is hidden from out side of the package p1. This class can be
seen and used only by other classes in the same package.
Static import:-
The static import feature eliminates the need of qualifying a static member with the class name. The static
import declaration is similar to that of ‘import’. The “import static” is used to import the classes from
packages and use the static import statements. To import the static member from the classes and use them
without qualifying the class name syntax for using the static import feature is
import static packagename.classname.static data member;
(Or)
import static package name. ClassName.*;
Eg:-
import static java.lang.Math.*;
public class MathOp
{
public void circle (double r)
{
double area=PI*r*r;
System.out.println (“the area “+ area);
}
public static void main (String args[ ])
{
MathOp obj=new MathOp ( ));
Obj.circle (2.3);
}
}
/* Second way to create User-Defined packages: Just like the built in packages shown earlier, the users of
the Java language can also create their own packages. They are called user-defined packages. User-defined
packages can also be imported into other classes and used exactly in the same way as the Built-in packages.
CREATING AND IMPORTING PACKAGES:
package packagename; //to create a package
package packagename.subpackagename;//to create a sub package within a package.
e.g.: package pack;
 The first statement in the program must be package statement while creating a package.
 While creating a package except instance variables, declare all the members and the class itself as
public then only the public members are available outside the package to other programs.
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
5
BTech - II YEAR OOP THROUGH JAVA

{
private double d1,d2;
public Addition(double a,double b)
{
d1 = a;
d2 = b;
}
public void sum()
{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Compiling the above program:

The –d option tells the Java compiler to create a separate directory and place the .class file in that directory
(package). The (.) dot after –d indicates that the package should be created in the current directory.
So, out package pack with Addition class is ready.
Program 2: Write a program to use the Addition class of package pack.
//Using the package pack
import pack.Addition;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10,20);
ob1.sum();
}
}
Output:

Program 3: Write a program to add one more class Subtraction to the same package pack.
//Adding one more class to package pack:
package pack;
public class Subtraction
{ private double d1,d2;
public Subtraction(double a, double b)
{ d1 = a;
d2 = b;
}
public void difference()
{ System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
}
}
Compiling the above program:
6
BTech - II YEAR OOP THROUGH JAVA

Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
}
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs will not exist in the
current directory. Delete them from the current directory as they cause confusion for the Java compiler.
The compiler looks for byte code in Addition.java and Subtraction.java files and there it gets no byte code
and hence it flags some errors.

UNDERSTANDING CLASSPATH:

If the package pack is available in different directory, in that case the compiler should be given information
regarding the package location by mentioning the directory name of the package in the classpath.

The CLASSPATH is an environment variable that tells the Java compiler where to look for class files to
import.

If our package exists in e:\sub then we need to set class path as follows:

We are setting the classpath to e:\sub directory and current directory (.) an %CLASSPATH%
means retain the already available classpath as it is.

Creating Sub package in a package: We can create sub package in a package in the format:
7
BTech - II YEAR OOP THROUGH JAVA

package packagename.subpackagename;

e.g.: package pack1.pack2;

Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes
and interfaces of pack2, we can write import statement as:

import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{ public void show ()
{
System.out.println ("Hello Java Learners");
}
}
Compiling the above program:

ACCESSING A PACKAGES:

Access Specifier: Specifies the scope of the data members, class and methods.
 private members of the class are available with in the class only. The scope of private members of
the class is “CLASS SCOPE”.
 public members of the class are available anywhere . The scope of public members of the class is
"GLOBAL SCOPE".
 default members of the class are available with in the class, outside the class and in its sub class of same
package. It is not available outside the package. So the scope of default members of the class is
"PACKAGE SCOPE".
 protected members of the class are available with in the class, outside the class and in its sub class of same
package and also available to subclasses in different package also.

Program 6: Write a program to create class A with different access specifiers.

//create a package same


package same;
public class A
{ private int a=1;
8
BTech - II YEAR OOP THROUGH JAVA

public int b = 2;
protected int c = 3;
int d = 4;
}
Compiling the above program:

Program 7: Write a program for creating class B in the same package.


//class B of same package
package same;
import same.A;
public class B
{
public static void main(String args[])
{
A obj = new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program:

Program 8: Write a program for creating class C of another package.


package another;
import same.A;
public class C extends A
{ public static void main(String args[])
{ C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program:

9
BTech - II YEAR OOP THROUGH JAVA

THE OBJECT CLASS:


There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is,
Object is a super class of all other classes. This means that a reference variable of type Object can refer to
an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can
also refer to any array.
Object defines the following methods, which means that they are available in every object.

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override
the others. These methods are described elsewhere in this book. However, notice two methods now:
equals( ) and toString( ). The equals( ) method compares two objects. It returns true if the objects
are equal, and false otherwise. The precise definition of equality can vary, depending on the type of
objects being compared. The toString( ) method returns a string that contains a description of the
object on which it is called. Also, this method is automatically called when an object is output using
println( ). Many classes override this method.

JAVA ENUMS
 The Enum in Java is a data type which contains a fixed set of constants.
 It can be used for: days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) directions (NORTH, SOUTH, EAST, and WEST), season
(SPRING, SUMMER, WINTER, and AUTUMN or FALL),colors (RED, YELLOW, BLUE, GREEN,
WHITE, and BLACK) etc.
 According to the Java naming conventions, we should have all constants in capital letters. So, wehave
enum constants in capital letters.
Points to remember for Java Enum
 Enum improves type safety
 Enum can be easily used in switch
 Enum can be traversed
 Enum can have fields, constructors and methods
10
BTech - II YEAR OOP THROUGH JAVA

 Enum may implement many interfaces but cannot extend any class because it internally
extendsEnum class

Initializing specific values to the enum constants


The enum constants have an initial value which starts from 0, 1, 2, 3, and so on. But, we can initialize the
specific value to the enum constants by defining fields and constructors.

class EnumExample4{
enum Season{
WINTER(5), SPRING(10), SUMMER(15), FALL(20);
private int value;
private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);
}
}
Output:
WINTER 5
SPRING 10
SUMMER 15
FALL 20

Autoboxing and Unboxing:


The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and
opposite operation is known as unboxing.This is the new feature of Java5.

So java programmer doesn't need to write the conversion code.


Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is required.
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object int
Primitive.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to
usethe wrapper classes.

11
BTech - II YEAR OOP THROUGH JAVA

 Change the value in Method: Java supports only call by value. So, if we pass a primitive
value, it will not change the original value. But, if we convert the primitive value in an object,
it will change theoriginal value.
 Serialization: We need to convert the objects into streams to perform the serialization. If we
havea primitive value, we can convert it in objects through the wrapper classes.
 Synchronization: Java synchronization works with objects in Multithreading.
 java.util package: The java.util package provides the utility classes to deal with objects.
 Collection Framework: Java collection framework works with objects only. All classes of
the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue,ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of
eightwrapper classes are given below:

Primitive Type Wrapper class

Boolean Boolean

Char Character

Byte Byte

Short Short

Int Integer

Long Long

Float Float

Double Double
Simple Example of Autoboxing in java:
1. class BoxingExample1{
2. public static void main(String args[]){
3. int a=50;
4. Integer a2=new Integer(a);//Boxing
6. Integer a3=5;//Boxing
8. System.out.println(a2+" "+a3);
9. }
10. }
OUTPUT: 50 5
Simple Example of Unboxing in java:
The automatic conversion of wrapper class type into corresponding primitive type, is known
as Unboxing.
class UnboxingExample1{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);

12
BTech - II YEAR OOP THROUGH JAVA

}
}

Date and Time

The following packages contains classes for representing date and time.

 java.time,
 java.util,
 java.sql and
 java.text
Java has introduced a new Date and Time API since Java 8.

java.util.Date

 The java.util.Date class represents date and time in java.


 It provides constructors and methods to deal with date and time in java.
 It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
 After Calendar class, most of the constructors and methods of java.util.Date class has been deprecated.
Here, we are not giving list of any deprecated constructor and method.

java.util.Date Constructors

No. Constructor Description

1) Date() Creates a date object representing current date and time.

2) Date(long Creates a date object for the given milliseconds since January 1,
milliseconds) 1970, 00:00:00 GMT.

java.util.Date Methods

No. Method Description

1) boolean after(Date date) tests if current date is after the given date.

2) boolean before(Date date) tests if current date is before the given date.

3) Object clone() returns the clone object of current date.

4) int compareTo(Date date) compares current date with given date.

5) boolean equals(Date date) compares current date with given date for equality.

6) static Date from(Instant instant) returns an instance of Date object from Instant date.

13
BTech - II YEAR OOP THROUGH JAVA

7) long getTime() returns the time represented by this date object.

8) int hashCode() returns the hash code value for this date object.

9) void setTime(long time) changes the current date and time to given time.

java.util.Date Example
1. public class UtilDateExample1{
2. public static void main(String args[]){
3. java.util.Date date=new java.util.Date(); Output
4. System.out.println(date);
Tue Feb 16 10:12:02 IST 2021
5. long millis=System.currentTimeMillis(); Tue Feb 16 10:12:02 IST 2021
6. java.util.Date date1=new java.util.Date(millis);
7. System.out.println(date);
8. }}

java.sql.Date

 The java.sql.Date class represents only date in java. It inherits java.util.Date class.
 The java.sql.Date instance is widely used in JDBC because it represents the date that can be stored in
database.
java.sql.Date Constructor
No. Constructor Description

1) Date(long Creates a sql date object for the given milliseconds since
milliseconds) January 1, 1970, 00:00:00 GMT.

java.sql.Date Methods
No. Method Description

1) void setTime(long time) changes the current sql date to given time.

3) LocalDate toLocalDate() converts current sql date into LocalDate object.

4) String toString() converts this sql date object to a string.

5) static Date returns sql date object for the given LocalDate.
valueOf(LocalDate date)

6) static Date valueOf(String returns sql date object for the given String.
date)

14
BTech - II YEAR OOP THROUGH JAVA

java.sql.Date Example: get current date


Let's see the example to print date in java using java.sql.Date class.
1. public class SQLDateExample {
2. public static void main(String[] args) {
3. long millis=System.currentTimeMillis();
Output:
4. java.sql.Date date=new java.sql.Date(millis); 2021-02-16
5. System.out.println(date);
6. } }

Calendar Class

Java Calendar class is an abstract class that provides methods for converting date between a specific instant
in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and
implements the Comparable interface.

Example

1. import java.util.Calendar;
2. public class CalendarExample1 {
3. public static void main(String[] args) {
4. Calendar calendar = Calendar.getInstance();
5. System.out.println("The current date is : " + calendar.getTime());
6. calendar.add(Calendar.DATE, -15);
OUTPUT
7. System.out.println("15 days ago: " + calendar.getTime());
8. calendar.add(Calendar.MONTH, 4); The current date is : Tue Feb 16 10:17:39 IST 2021
9. System.out.println("4 months later: " + calendar.getTime()); 15 days ago: Mon Feb 01 10:17:39 IST 2021
4 months later: Tue Jun 01 10:17:39 IST 2021
10. calendar.add(Calendar.YEAR, 2); 2 years later: Thu Jun 01 10:17:39 IST 202
11. System.out.println("2 years later: " + calendar.getTime());
12. }
13. }

Some Important Methods

No Method Description

1. public void add(int field, int Adds the specified (signed) amount of time to the
amount) given calendar field.

2. public boolean after (Object when) The method Returns true if the time represented by
this Calendar is after the time represented by when
Object.

3. public boolean before(Object The method Returns true if the time represented by
when) this Calendar is before the time represented by

15
BTech - II YEAR OOP THROUGH JAVA

when Object.

4. public final void clear(int field) Set the given calendar field value and the time
value of this Calendar undefined.

5. public Object clone() Clone method provides the copy of the current
object.

6. public boolean equals(Object The equals() method compares two objects for
object) equality and Returns true if they are equal.

7. public static Calendar This method is used with calendar object to get the
getInstance() instance of calendar according to current time zone
set by java runtime environment

8. public final Date getTime() This method gets the time value of calendar object
and Returns date.

9. public void set(int field, int value) Sets the specified calendar field by the specified
value.

10. public final void setTime(Date Sets the Time of current calendar object. A Date
date) object id passed as the parameter.

Random class

Random class is used to generate pseudo-random numbers in java.

An instance of this class is thread-safe. This class provides various method calls to generate different
random data types such as float, double, int.

Constructors:

 Random(): Creates a new random number generator


 Random(long seed): Creates a new random number generator using a single long seed

1. // Java program to demonstrate


2. // method calls of Random class OutPut
3. import java.util.Random; 4
4. public class Test true
5. {
0.19674934340402916
6. public static void main(String[] args)
0.7372021
7. {
1.4877581394085997
8. Random random = new Random();
[-44 75 68 89 81 -72 -1 -66 -64 117 ]
158739962004803677 16
-1344764816
BTech - II YEAR OOP THROUGH JAVA

9. System.out.println(random.nextInt(10));
10. System.out.println(random.nextBoolean());
11. System.out.println(random.nextDouble());
12. System.out.println(random.nextFloat());
13. System.out.println(random.nextGaussian());
14. byte[] bytes = new byte[10];
15. random.nextBytes(bytes);
16. System.out.printf("[");
17. for(int i = 0; i< bytes.length; i++)
18. {
19. System.out.printf("%d ", bytes[i]);
20. }
21. System.out.printf("]\n");
22. System.out.println(random.nextLong());
23. System.out.println(random.nextInt());
24. }}

Formatter class

The java.util.Formatter class provides support for layout justification and alignment, common formats for
numeric, string, and date/time data, and locale-specific output.
Following are the important points about Formatter –
Important Format Specifiers
Format Description Example & Output
Specifier
Space When creating columns of numbers, it is formatter.format("% d", -
sometimes very useful to print a space 111);
before a positive number so that positive Output:
and negative number get aligned. To do -111
this, space format specifier can be used.

+ Sign This adds the + sign before positive Formatter().format("%+d",


numeric value, and has no effect on 111);
negative numeric value. Output:

+111

( specifier Formatter().format("%(d", -
111);
This specifier puts the negative numeric
values inside the parentheses, and has no Formatter().format("%(d",
effect on the positive numeric values. 111);

Output:

(111)

17
BTech - II YEAR OOP THROUGH JAVA

111

Comma, Formatter().format("%, d",


Specifier 1000000);
displaying large numbers, it is often
useful to add grouping separators by Output:
comma (, ).
1, 000, 000

Left Formatter().format("|%-
Justification 20.4f|", 1234.1234);

Output:
For Left Justification
| 1234.1234|

|1234.1234 |

The %n formatter.format("NECN
format %n CSE %nNELLORE");

Output:

New Line NECN

CSE

NELLORE

The %% formatter.format("10 %% 4
format = 2");
It is simply an escape sequence that
inserts a character into the output. The Output
%% inserts a % sign.
10 % 4 = 2

The %e %E formatter.format("%e",
format 123.1234);
The %e or %E format specifier is is Output
used to represent the Scientific Notation
of a value
1.231234e+02

18
BTech - II YEAR OOP THROUGH JAVA

Precision A precision specifier can be applied to


the %f, %e, %g, and %s format
specifiers

import java.util.Formatter;

public class GFG {

public static void main(String args[])

// Create the Formatter instance

Formatter formatter = new Formatter();

formatter = new Formatter();

formatter.format("%16.2e", 123.1234567);

System.out.println("Scientific notation to 2 places: " + formatter);

// Format 4 decimal places.

formatter = new Formatter();

formatter.format("%.4f", 123.1234567);

System.out.println("Decimal floating-point" + " notation to 4 places: " + formatter);

// Format 4 places.

// The %g format specifier causes Formatter

// to use either %f or %e, whichever is shorter

formatter = new Formatter();

formatter.format("%.4g", 123.1234567);

System.out.println("Scientific or Decimal floating-point "+ "notation to 4 places: " + formatter);

// Display at most 15 characters in a string.

formatter = new Formatter();

formatter.format("%.15s", "12345678901234567890");

System.out.println("String notation to 15 places: " + formatter);

// Format into 10 digit

19
BTech - II YEAR OOP THROUGH JAVA

formatter = new Formatter();

formatter.format("%010d", 88);

System.out.println("value in 10 digits: "+formatter);

}
}
Output:
Scientific notation to 2 places: 1.23e+02
Decimal floating-point notation to 4 places: 123.1235
Scientific or Decimal floating-point notation to 4 places: 123.1
String notation to 15 places: 123456789012345
value in 10 digits: 0000000088
RandomAccessFile class :
RandomAccessFile class is used for reading and writing to random access file.
A random access file behaves like a large array of bytes. There is a cursor implied to the array
called file pointer, by moving the cursor we do the read write operations.
If end-of-file is reached before the desired number of byte has been read than EOFExceptionis
thrown.
Constructor
Constructor Description

RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and
optionally to write to, the file specified by the File
argument.

RandomAccessFile(String name, String Creates a random access file stream to read from, and
mode) optionally to write to, a file with the specified name.
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));writeToFile(FILEPATH, "I love my country
and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile (filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];file.read(bytes);
file.close();
return bytes;

20
BTech - II YEAR OOP THROUGH JAVA

}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile (filePath, "rw");file.seek (position);
file.write(data.getBytes());file.close();
}
}

21
BTech - II YEAR OOP THROUGH JAVA

Unit -III :: Part- II


What is an Exception? Exception handling
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at
run time that disrupts the normal flow of the program’s instructions.
Error vs Exception
 Error: An Error indicates serious problem that a reasonable application should not try to catch.
 Exception: Exception indicates conditions that a reasonable application might try to catch.
Hierarchy
 All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy.
 One branch is headed by Exception.
 This class is used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.
 Another branch, Error are used by the Java run-time system (JVM) to indicate errors having to
do with the run-time environment itself (JRE). StackOverflowError is an example of such an error.

Types of Exceptions
Java’s exceptions can be categorized into two types:
1. Checked exceptions
2. Unchecked exceptions
1. Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler
at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored, the programmer should take care of (handle) these exceptions.
Examples of some Popular Checked Exceptions:
Name Description
IOException While using file input/output stream related exception
SQLException. While executing queries on database related to SQL syntax
Thrown when the JVM can’t find a class it needs, because of a
ClassNotFoundException
command-line error, a classpath issue, or a missing .class file

68
BTech - II YEAR OOP THROUGH JAVA

FileNotfound Exception Thrown when the if the file does not exist
DataAccessException Exception related to accessing data/database
InstantiationException Attempt to create an object of an abstract class or interface.

For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.

Example
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program, you will get the following exceptions.

Output
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can observe
that the compiler notifies to handle IOException, along with FileNotFoundException.
2. Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or
improper use of an API. Runtime exceptions are ignored at the time of compilation.
Examples of some of the Popular Unchecked Exceptions:
Name Description
NullPointerException Thrown when attempting to access an object with a reference
variable whose current value is null
ArrayIndexOutOfBound Thrown when attempting to access an array with an invalid
index value (either negative or beyond the length of the array)
IllegalArgumentException. Thrown when a method receives an argument formatted
differently than the method expects.
IllegalStateException Thrown when the state of the environment doesn’t match the
operation being attempted,e.g., using a Scanner that’s been
closed.
NumberFormatException Thrown when a method that converts a String to a number
receives a String that it cannot convert.
ArithmaticException Arithmetic error, such as divide-by-zero.

For example, if you have declared an array of size 5 in your program, and trying to call the 6 th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

69
BTech - II YEAR OOP THROUGH JAVA

Example
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following exception.

Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
3.Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation

Uncaught Exceptions in Java

 The uncaught exceptions are the exceptions that are not caught by the compiler but automatically
caught and handled by the Java built-in exception handler.
 When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the following
code.
Example

import java.util.Scanner;
public class UncaughtExceptionExample {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.println("Enter the a and b values: ");
int a = read.nextInt();
int b = read.nextInt();
int c = a / b;
System.out.println(a + "/" + b +" = " + c);
}}

When we execute the above code, it produce the following output for the value a = 10 and b = 0.

In the above example code, we are not used try and catch blocks, but when the value of b is zero the
division by zero exception occurs and it caught by the default exception handler.

70
BTech - II YEAR OOP THROUGH JAVA

Exception Handling
 Whenever inside a method, if an exception has occurred, the method creates an Object known as
Exception Object and hands it off to the run-time system (JVM).
 The exception object contains name and description of the exception, and current state of the
program where exception has occurred.
 Creating the Exception Object and handling it to the run-time system is called throwing an
Exception.
 There might be the list of the methods that had been called to get to the method where exception was
occurred. This ordered list of the methods is called Call Stack. Now the following procedure will
happen. 
 The run-time system searches the call stack to find the method that contains block of code that
can handle the occurred exception. The block of the code is called Exception handler.
 If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler
means the type of the exception object thrown matches the type of the exception object it can handle. 
 If run-time system searches all the methods on call stack and couldn’t have found the appropriate
handler then run-time system handover the Exception Object to default exception handler, which is part
of run-time system. This handler prints the exception information in the following format and terminates
program abnormally. 
// Java program to demonstrate how exception is thrown.
class ThrowsExecp{
public static void main(String args[]){
String str = null;
System.out.println(str.length());
}
}
Output :
Exception in thread "main" java.lang.NullPointerException
Let us see an example that illustrate how run-time system searches appropriate exception handling code
on the call stack:
class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){
int i = a/b; // this statement will cause ArithmeticException
return i;
}
// The runTime System searches the appropriate Exception handler
// in this method also but couldn't have found. So looking forward on to the call stack.
static int computeDivision(int a, int b) {
int res =0;
try {
res = divideByZero(a,b); // doesn't matches with ArithmeticException
}
catch(NumberFormatException ex) {
System.out.println("NumberFormatException is occured");
}
return res;
}
// In this method found appropriate Exception handler.

71
BTech - II YEAR OOP THROUGH JAVA

// i.e. matching catch block.


public static void main(String args[]){
int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b);
}
// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}}}
Output : / by zero.

Java Exception Keywords


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

Try The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.

Catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.

Throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.

Catching Exceptions :
A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following −
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Example :
The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the
array which throws an exception.

72
BTech - II YEAR OOP THROUGH JAVA

import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}}

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following −
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}

o The previous statements demonstrate three catch blocks, but you can have any number of them after
a single try.
o If an exception occurs in the protected code, the exception is thrown to the first catch block in the
list.
o If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement.
o This continues until the exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the previous method on the call
stack.
NOTE:
 When there are multiple catch blocks, the order of catch blocks must be from the most specific
exception handler to most general.
 The catch block with Exception class handler must be defined at the last.

73
BTech - II YEAR OOP THROUGH JAVA

public class TryCatchExample {


public static void main(String[] args) {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

Example
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (Exception i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid!
{
f.printStackTrace();
return -1;
}

Nested try statements


 A try block within another try block is known as nested try block.
 When there are nested try blocks, each try block must have one or more separate catch blocks.

Example

public class TryCatchExample {

public static void main(String[] args) {

try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {

74
BTech - II YEAR OOP THROUGH JAVA

System.out.println("Problem info: ArrayIndexOutOfBoundsException has occured.");


}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}

NOTE:In case of nested try blocks, if an exception occured in the inner try block and it's catch blocks are
unable to handle it then it transfers the control to the outer try's catch block to handle it.

The Throws/Throw:
throw keyword in Java
 The throw keyword is used to throw an exception instance explicitly from a try block to
corresponding catch block. That means it is used to transfer the control from try block to corresponding
catch block.
 The throw keyword must be used inside the try blcok.
 When JVM encounters the throw keyword, it stops the execution of try block and jump to the
corresponding catch block.
The following is the general syntax for using throw keyword in a try block.
Syntax

throw instance;

Example

import java.util.Scanner;
public class Sample {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
int num1, num2, result;
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero is not posible");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");

75
BTech - II YEAR OOP THROUGH JAVA

}
}

throws keyword in Java


 The throws keyword specifies the exceptions that a method can throw to the default handler and
does not handle itself. That means when we need a method to throw an exception automatically, we
use throws keyword followed by method declaration
 When a method throws an exception, we must put the calling statement of method in try-catch
block.
Example

import java.util.Scanner;
public class ThrowsExample {
int num1, num2, result;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException {
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
public static void main(String[] args) {
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}

finally keyword in Java


 The finally keyword used to define a block that must be executed irrespective of exception
occurence.
 The basic purpose of finally keyword is to cleanup resources allocated by try block, such as
closing file, closing database connection, etc.
 Only one finally block is allowed for each try block.
 Use of finally block is optional.

Let's look at the following example Java code to illustrate throws keyword.

76
BTech - II YEAR OOP THROUGH JAVA

Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Example

import java.util.Scanner;
public class FinallyExample {
public static void main(String[] args) {
int num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.print("Enter any two numbers: ");
num1 = input.nextInt();
num2 = input.nextInt();
try {
if(num2 == 0)
throw new ArithmeticException("Division by zero");
result = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + result);
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
finally {
System.out.println("The finally block executes always");
}
System.out.println("End of the program");
}
}

Built in Exception

 The Java programming language has several built-in exception class that support exception
handling.
 All the built-in exception classes in Java were defined a package java.lang

77
BTech - II YEAR OOP THROUGH JAVA

List of checked exceptions in Java:


The following table shows the list of several checked exceptions.
s.no Exception Class with Description
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified
class cannot be found in the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but that
the object's class does not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do not
allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance method
in class Class , but the specified class object cannot be instantiated because it is an interface or is
an abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a
NoSuchMethodException occurs during reflection when we try to access a method that does not
exist.

78
BTech - II YEAR OOP THROUGH JAVA

List of unchecked exceptions in Java


The following table shows the list of several unchecked exceptions.
S. Exception Class with Description
No.
1 ArithmeticException
It handles the arithmetic exceptions like dividion by zero
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is either
negative or greater than or equal to the size of the array.
3 ArrayStoreException
It handles the situations like when an attempt has been made to store the wrong type of object into
an array of objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or
inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has attempted
to notify other threads that wait on an object's monitor, without owning the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the state of
the thread when it is illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array , vector
, string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the
format of the input string is not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either negative,
or greater than the size of the string itself.
16 UnsupportedOperationException
It is thrown to indicate that the requested operation is not supported.

Creating our own exceptions(User-defined Exceptions)

79
BTech - II YEAR OOP THROUGH JAVA

User-defined Exceptions:
You can create your own exceptions in Java.

Key Points while creating own exception classes


 All exceptions must be a child of Throwable.
 If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below −


class MyException extends Exception {
}
You just need to extend the predefined Exception class to create your own Exception.
These are considered to be checked exceptions.

Example:
The following InsufficientFundsException class is a user-defined exception that extends the Exception
class, making it a checked exception. An exception class is like any other class, containing useful fields
and methods.
Example
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;

80
BTech - II YEAR OOP THROUGH JAVA

}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}

Output :

Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

81
BTech - II YEAR OOP THROUGH JAVA

Java-Stream Classes

In Java, a stream is a path along which the data flows. Every stream has a source and a destination. We
can build a complex file processing sequence using a series of simple stream operations.

Class Hierarchy of Stream Class

Types of Streams

The java.io package contains a large number of stream classes that provide capabilities for processing all
types of data. These classes may be categorized into two groups based on the data type on which they
operate.

 Byte stream classes


 Character stream classes
Byte Stream Classes
 Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes.
82
BTech - II YEAR OOP THROUGH JAVA

 Java provides two kinds of byte stream classes:


o input stream classes and
o output stream classes.

Input Stream Classes


Input stream classes that are used to read bytes include a super class known as “Inputstream” and a
number of subclasses for supporting various input-related functions. The super class InputStream is an
abstract class, and, therefore, we cannot create instances of this class. Rather, we must use the subclasses
that inherit from this class.

Output Stream Classes


Output stream classes are derived from the base class “Outputstream” like InputStream, the
OutputStream is an abstract class and therefore we cannot instantiate it. The several subclasses of the
OutputStream can be used for performing the output operations.

These two abstract classes have several concrete classes that handle various devices such as disk files,
network connection etc.
Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method


These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data

83
BTech - II YEAR OOP THROUGH JAVA

Example Input/Output Streams Reading and writing Files


Following Java program reads data from a particular file using FileInputStream and writes it to another,
using FileOutputStream.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileInputStream object
File file = new File("D:/myFile.txt");
FileInputStream fis = new FileInputStream(file);
byte bytes[] = new byte[(int) file.length()];
//Reading data from the file
fis.read(bytes);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileOutputStream outputStream = new FileOutputStream(out);
//Writing data to the file
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
Output
Data successfully written in the specified file

Character Stream Classes


Character streams can be used to read and write 16-bit Unicode characters. Like byte streams, there are
two kinds of character stream classes, namely, reader stream classes and writer stream classes.

Reader Stream Classes


Reader stream classes that are used to read characters include a super class known as Reader and a
number of subclasses for supporting various input-related functions. Reader stream classes are
functionally very similar to the input stream classes, except input streams use bytes as their fundamental
unit of information, while reader streams use characters. The Reader class contains methods that are
identical to those available in the InputStream class, except Reader is designed to handle characters.
Therefore, reader classes can perform all the functions implemented by the input stream classes.

Writer Stream Classes


Like output stream classes, the writer stream classes are designed to perform all output operations on
files. Only difference is that while output stream classes are designed to write bytes, the writer stream are

84
BTech - II YEAR OOP THROUGH JAVA

designed to write character. The Writer class is an abstract class which acts as a base class for all the
other writer stream classes. This base class provides support for all output operations by defining
methods that are identical to those in Outputstream class.

These two abstract classes have several concrete classes that handle unicode character.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

Example Reader/Writer Streams (Reading and writing Files)


Following Java program reads data from a particular file using FileReader and writes it to another, using
FileWriter.
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOStreamsExample {
public static void main(String args[]) throws IOException {
//Creating FileReader object
File file = new File("D:/myFile.txt");
FileReader reader = new FileReader(file);
char chars[] = new char[(int) file.length()];
//Reading data from the file
reader.read(chars);
//Writing data to another file
File out = new File("D:/CopyOfmyFile.txt");
FileWriter writer = new FileWriter(out);
//Writing data to the file

85
BTech - II YEAR OOP THROUGH JAVA

writer.write(chars);
writer.flush();
System.out.println("Data successfully written in the specified file");
}
}
Output
Data successfully written in the specified file

Reading console Input and Writing Console Output

In Java, there are three different ways for reading input from the user in the command line environment
(console).
1. Using Buffered Reader Class
 This is the Java classical method to take input, Introduced in JDK1.0.
 This method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the
command line.
Advantages
 The input is buffered for efficient reading.
Drawback:
 The wrapping code is hard to remember. 
Program:

// Java program to demonstrate BufferedReader


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test
{
public static void main(String[] args) throws IOException
{
//Enter data using BufferReader
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();

// Printing the read line


System.out.println(name);
}
}
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble().
2. Using Scanner Class
 This is probably the most preferred method to take input.

86
BTech - II YEAR OOP THROUGH JAVA

 The main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however it is also can be used to read input from the user in the command line.
Advantages:

 Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
 Regular expressions can be used to find tokens.
Drawback:
 The reading methods are not synchronized

// Java program to demonstrate working of Scanner in Java


import java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

int a = in.nextInt();
System.out.println("You entered integer "+a);

float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

3. Using Console Class


It has been becoming a preferred way for reading user’s input from the command line. In addition, it
can be used for reading password-like input without echoing the characters entered by the user; the
format string syntax can also be used (like System.out.printf()).
Advantages:
 Reading password without echoing the entered characters.
 Reading methods are synchronized.
 Format string syntax can be used.
Drawback:
 Does not work in non-interactive environment (such as in an IDE).

Console gives three ways to read the input:


 String readLine() – reads a single line of text from the console.
 char[] readPassword() – reads a password or encrypted text from the console with echoing
disabled
 Reader reader() – retrieves the Reader object associated with this console. Java program to read
console input with readLine()

87
BTech - II YEAR OOP THROUGH JAVA

Console readLine() method example


Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
String userName = console.readLine("Enter the username: ");
System.out.println("Entered username: " + userName);

Java program to read console input with readPassword()


Console readPassword() method example
Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
char[] password = console.readPassword("Enter the password: ");
System.out.println("Entered password: " + new String(password));

reader()

Console reader() method example


Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
Reader consoleReader = console.reader();
Scanner scanner = new Scanner(consoleReader);
System.out.println("Enter age:");
int age = scanner.nextInt();
System.out.println("Entered age: " + age);
scanner.close();

Writing Console Output in Java

 print() and println()


 Both print() and println() methods are used to direct the output to the console. These methods are
defined in the PrintStream class and are widely used.

 The basic differences between print() and println() methods is that print() method displays the
string in the same line whereas println() method outputs a newline character after its execution.

 The write() method


Alternatively, you can make use of the write() method for directing the output of your program to the
console. The easiest syntax of the write() method is:

void write(int b);

88
BTech - II YEAR OOP THROUGH JAVA

Where b is an integer of low order eight bits.

1. class writeEg
2. {
3. public static void main(String args[])
4. {
5. int a, b;
6. a = 'Q';
7. b = 65;
8. System.out.write(a);
9. System.out.write('\n');
10. System.out.write(b);
11. System.out.write('\n');
12. }
13. }

Java File Class


The File class is an abstract representation of file and directory pathname.
Constructors

Constructor Description

File(File parent, String child) It creates a new File instance from a parent abstract pathname and a child
pathname string.

File(String pathname) It creates a new File instance by converting the given pathname string into
an abstract pathname.

File(String parent, String child) It creates a new File instance from a parent pathname string and a child
pathname string.

File(URI uri) It creates a new File instance by converting the given file: URI into an
abstract pathname.
Useful Methods

Method Description

createNewFile() It atomically creates a new, empty file named by this abstract pathname if
and only if a file with this name does not yet exist.

canWrite() It tests whether the application can modify the file denoted by this abstract
pathname.String[]

canExecute() It tests whether the application can execute the file denoted by this abstract
pathname.

canRead() It tests whether the application can read the file denoted by this abstract
pathname.

isAbsolute() It tests whether this abstract pathname is absolute.

isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
isFile() It tests whether the file denoted by this abstract pathname is a normal file.

getName() It returns the name of the file or directory denoted by this abstract
pathname.

89
BTech - II YEAR OOP THROUGH JAVA

getParent() It returns the pathname string of this abstract pathname's parent, or null if
this pathname does not name a parent directory.

toPath() It returns a java.nio.file.Path object constructed from the this abstract path.

toURI() It constructs a file: URI that represents this abstract pathname.

listFiles() It returns an array of abstract pathnames denoting the files in the directory
denoted by this abstract pathname

getFreeSpace() It returns the number of unallocated bytes in the partition named by this
abstract path name.

list(FilenameFilter filter) It returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname that satisfy the specified filter.

mkdir() It creates the directory named by this abstract pathname.

Java File Example 1: New File Creation

1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }
Java File Example 2

1. import java.io.*;
2. public class FileDemo2 {
3. public static void main(String[] args)
4. {
5. String path = "";
6. boolean bool = false;
7. try {
8. // createing new files
9. File file = new File("testFile1.txt");
10. file.createNewFile();
11. System.out.println(file);
90
BTech - II YEAR OOP THROUGH JAVA

12. // createing new canonical from file object


13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists();
17. // returns absolute pathname
18. path = file2.getAbsolutePath();
19. System.out.println(bool);
20. // if file exists
21. if (bool) {
22. // prints
23. System.out.print(path + " Exists? " + bool);
24. }
25. } catch (Exception e) {
26. // if any error occurs
27. e.printStackTrace();
28. }
29. }
30. }

Java File Example 3


1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File f=new File("/Users/NECG/Documents");
5. String filenames[]=f.list();
6. for(String filename:filenames){
7. System.out.println(filename);
8. }
9. }
10. }
Java File Example 4

1. import java.io.*;
2. public class FileExample {
3. public static void main(String[] args) {
4. File dir=new File("/Users/NECG/Documents");
5. File files[]=dir.listFiles();
6. for(File file:files){
7. System.out.println(file.getName()+" Can Write: "+file.canWrite()+"
8. Is Hidden: "+file.isHidden()+" Length: "+file.length()+" bytes");
9. }
10. }
11. }

91
BTech - II YEAR OOP THROUGH JAVA

Scanner Class
1. The scanner class is a class in java.util, which allows the user to read values of various types.
2. A scanner object can read user input entered on the console or from a file.
3. A scanner breaks its input into separate tokens and returns them at a time.
4. The scanner provides methods to convert the tokens into values of different types.
5. A Scanner is not safe for multithreaded use without external synchronization.
Syntax:
Scanner s=new Scanner(System.in);
int i = s.nextInt( );
We can create scanners in two ways
1. To read from the console
Scanner s = new Scanner(System.in);
2. To read from a file
Scanner s = new Scanner(new FileStream(“filename.txt”));
Constructors:
Scanner(File source)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Scanner Methods :
Scanner Method Description
nextInt( ) Reads and converts next token to a integer value
nextLong( ) Reads and converts next token to a long value
nextDouble( ) Reads and converts next token to a double value
nextString( ) (or) next() Reads a String
nextBoolean( ) Reads and converts next token to a boolean value

92
BTech - II YEAR OOP THROUGH JAVA

UNIT - V
STRINGS: A String represents group of characters. Strings are represented as String
objects in java. The String class is defined in the java.lang package and hence is implicitly
available to all the programs in Java. The String class is declared as final, which means that it
cannot be subclassed. It extends the Object class and implements the Serializable, Comparable,
and CharSequence interfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlike
most of the other languages, Java treats a string as a single value rather than as an array of
characters.

Creating Strings:

 We can declare a String variable and directly store a String literal using
assignment operator.String str = "Hello";
 We can create String object using new operator
with some data.String s1 = new String ("Java");
 We can create a String by using
character array also. char arr[]
= { 'p','r','o',’g’,’r’,’a’,’m’};
 We can create a String by passing array
name to it, as: String s2 = new
String (arr);
 We can create a String by passing array name and specifying which
characters we need:String s3 = new String (str, 2, 3);
Here starting from 2nd character a total of 3 characters are copied into String s3.

String Class Methods:


Method call Task performed
1. s2=s1.toLowerCase( ); Converts the string s1 to all Lower case.
2. s2=s1.toUpperCase( ); Converts the string s1 to all uppercase.
3. s2=s1.replace(‘x’,’y’); Replace all appearances of ‘x’with ‘y’.
4. s2=s1.trim( ); Remove white spaces at the beginning and end of the string
s1
5. s1.equals(s2) Returns ‘true’ if s1 is equal to s2
6. s1 equalsIgnoreCase(s2) Returns true if s1=s2 ignoring the case of characters
7. s1.length( ) Gives the length of s1
8. s1.charAt(n) Gives nth character of s1
9. s1.compareTo(s2) Returns negative if s1<s2.positive if s1>s2 and zero if s1 is
equal to s2
10. s1.concat(s2) Concatenates s1 and s2

11. s1.substring(n) Gives substring starting from nth character.


12. s1.substring(n,m) Gives substring starting from nth character up to mth(
not including mth)
13. string.valueOf(p) Creates a string object of the parameter p(simple type
or object)

99
BTech - II YEAR OOP THROUGH JAVA

14. p. toString() Creates a string representation of the object p.


15. s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the
strings
16. s1.indexOf(‘x’,n) Gives the position of ‘x’ that occurs after nth position
in the string s1.
17. string.valueOf(variable) Converts the parameter value to string representation.

string represents a sequence of characters. It has fixed length of character sequence. Once a
string object has been created than we can't change the character that comprise that string. It is
immutable. This allows String to be shared. String object can be instantiated like any other object
String str = new String
("Stanford “); str +=
"Lost!!";

Accessor methods:
length(), charAt(i), getBytes(), getChars(istart,iend,gtarget[],itargstart), split(string,delim),
toCharArray(), valueOf(g,iradix), substring(iStart [,iEndIndex)]) [returns up to but not including
iEndIndex]
Modifier methods:
concat(g), replace(cWhich, cReplacement), toLowerCase(), toUpperCase(), trim().

Boolean test methods:


contentEquals(g), endsWith(g), equals(g), equalsIgnoreCase(g), atches(g),
regionMatches(i1,g2,i3,i4),egionMatches(bIgnoreCase,i1,g2,i3,i4), startsWith(g)
Integer test methods:
compareTo(g) [returns 0 if object equals parameter, -1 if object is before parameter in sort
order, +1 if otherwise], indexOf(g) [returns position of first occurrence of substring g in the
string, -1 if not found], lastIndexOf(g) [returns position of last occurrence of substring g in
the string, -1 if not found], length().
Constructors defined in the String class :
The String class defines several constructors. The most common constructor of the String
class is the onegiven below:

public String(String value):


This constructor constructs a new String object initialized with the same sequence of the
characters passed as the argument. In other words, the newly created String object is the copy of
the string passed as an argument to the constructor. Other constructors defined in the String class
are as follows:

public String():
This constructor creates an empty String object. However, the use of this constructor is
unnecessary becauseString objects are immutable.

public String(char[] value):


100
BTech - II YEAR OOP THROUGH JAVA

This constructor creates a new String object initialized with the same sequence of
characters currentlycontained in the array that is passed as the argument to it.

public String(char[] value, int startindex, int len):


This constructor creates a new String object initialized with the same sequence of characters
currently contained in the subarray. This subarray is derived from the character array and the two
integer values that are passed as arguments to the constructor. The int variable startindex
represents the index value of the starting character of the subarray, and the int variable len
represents the number of characters to be used to form the new String object.

StringBuffer:
StringBuffer objects are mutable, so they can be modified. The methods that directly
manipulate data ofthe object are available in StringBuffer class.

Creating StringBuffer:
 We can create a StringBuffer object by using new operator and pass the string to
the object, as:StringBuffer sb = new StringBuffer ("Dr. Suresh Babu");
 We can create a StringBuffer object by first allotting memory to the StringBuffer
object usingnew operator and later storing the String into it as:

StringBuffer sb = new StringBuffer (30);


In general a StringBuffer object will be created with a default capacity of 16 characters. Here,
StringBuffer object is created as an empty object with a capacity for storing 30 characters. Even
if we declare the capacityas 30, it is possible to store more than 30 characters into StringBuffer.
To store characters, we can use append () method as:
Sb.append (“jugunta”);
This represents growable and writeable character sequence. It is mutable in nature. StringBuffer
are safe to be used by multiple thread as they are synchronized but this brings performance
penalty.
It defines 3-constructor:
• StringBuffer(); //initial capacity of 16 characters
• StringBuffer(int size); //The initial size
• StringBuffer(String str);
StringBuffer str = new StringBuffer
("Stanford ");str.append("Lost!!");

Method Task
S1.setCharAt(n,’x’) Modifies the nth character to x.
S1.append(s2) Appends the string s2 to s1 at the end
S1.insert(n,s2) Inserts the string s2 at position n of the string s1
S1.setLength(n) Sets the length of the string s1 to n. If n<s1.length (), s1 is truncated. If
n>s1.length(), zeros are added to s1.
Program : Write a program using some important methods of StringBuffer class.
// program using StringBuffer class methods import java.io.*;
class Mutable
101
BTech - II YEAR OOP THROUGH JAVA

{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in)); System.out.print
("Enter sur name : ");
String sur=br.readLine ( );
System.out.print ("Enter mid name : ");
String mid=br.readLine ( );
System.out.print ("Enter last name : ");
String last=br.readLine ( );
// create String Buffer object StringBuffer sb=new StringBuffer ( );
// append sur, last to sbsb.append (sur);
sb.append (last);
// insert mid after sur int n=sur.length ( );
sb.insert (n, mid);
// display full name
System.out.println ("Full name = "+sb);
System.out.println ("In reverse ="+sb.reverse ( ));
}
}
Output:
D:/AIMLr>javac Mutable.java
D:/AIML>java Mutable
Enter sur name: suresh
Enter mid name: babu
Enter last name: jugunta
Full name=suresh babu jugunta
In reverse=jugunta suresh babu

CharSequence interface
In Java, the CharSequence interface is a way to access a sequence of characters, or a string, in a
readable and uniform manner. It provides a variety of methods for manipulating strings, including:
length(): Returns the length of the string
charAt(): Returns the character at a specified index
Searching and replacing characters: Methods for searching and replacing characters in a string
Comparing strings: Methods for comparing strings

String Methods for Character Extraction in Java

Introduction

Java provides several methods to extract characters from a string. These methods are useful for
manipulating and analyzing strings at the character level. This tutorial will cover the various methods
available for character extraction with examples.

Table of Contents

1. charAt()
2. getChars()
3. getBytes()
4. toCharArray()

102
BTech - II YEAR OOP THROUGH JAVA

1. charAt()

The charAt() method returns the character at a specified index in a string. The index is zero-based,
meaning the first character is at index 0.

Syntax:
public char charAt(int index)

Example:
public class CharAtExample {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = str.charAt(7);

System.out.println("Character at index 7: " + ch);


}
}

Output:
Character at index 7: W

2. getChars()

The getChars() method copies characters from a specified segment of a string into a destination
character array.

Syntax:
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

 srcBegin: The starting index (inclusive).


 srcEnd: The ending index (exclusive).
 dst: The destination array.
 dstBegin: The starting index in the destination array.

Example:
public class GetCharsExample {
public static void main(String[] args) {
String str = "Hello, World!";
char[] dst = new char[5];

str.getChars(7, 12, dst, 0);

System.out.println("Extracted characters: " + new String(dst));


}
}

Output:
Extracted characters: World

103
BTech - II YEAR OOP THROUGH JAVA

3. getBytes()

The getBytes() method encodes the string into a sequence of bytes using the platform's default charset
and returns the resulting byte array.

Syntax:
public byte[] getBytes()

Example:
import java.util.Arrays;

public class GetBytesExample {


public static void main(String[] args) {
String str = "Hello";
byte[] byteArray = str.getBytes();

System.out.println("Byte array: " + Arrays.toString(byteArray));


}
}

Output:
Byte array: [72, 101, 108, 108, 111]

4. toCharArray()

The toCharArray() method converts the string to a new character array.

Syntax:
public char[] toCharArray()

Example:
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "Hello";
char[] charArray = str.toCharArray();

System.out.println("Character array: " + Arrays.toString(charArray));


}
}

Output:
Character array: [H, e, l, l, o]

5. Complete Example Program

Here is a complete program that demonstrates the various character extraction methods discussed above.

104
BTech - II YEAR OOP THROUGH JAVA

Example Code:
import java.util.Arrays;

public class StringCharacterExtraction {


public static void main(String[] args) {
String str = "Hello, World!";

// Using charAt()
char ch = str.charAt(7);
System.out.println("Character at index 7: " + ch);

// Using getChars()
char[] dst = new char[5];
str.getChars(7, 12, dst, 0);
System.out.println("Extracted characters using getChars: " + new String(dst));

// Using getBytes()
byte[] byteArray = str.getBytes();
System.out.println("Byte array using getBytes: " + Arrays.toString(byteArray));

// Using toCharArray()
char[] charArray = str.toCharArray();
System.out.println("Character array using toCharArray: " + Arrays.toString(charArray));
}
}

Output:
Character at index 7: W
Extracted characters using getChars: World
Byte array using getBytes: [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
Character array using toCharArray: [H, e, l, l, o, ,, , W, o, r, l, d, !]

Compare Strings :
The string is a sequence of characters. In Java, objects of String are immutable which means they are
constant and cannot be changed once created.
Methods to Compare Strings in Java
Below are 5 ways to compare two Strings in Java:
1. Using user-defined function
2. Using String.equals()
3. Using String.equalsIgnoreCase()
4. Using Objects.equals()
5. Using String.compareTo()
Comparing strings is a common task in Java, especially in input validation and searching algorithms.
For a more in-depth exploration of string comparison methods and their performance implications,
the Java Programming Course covers string handling comprehensively with practical examples.
1. Using user-defined function:
Define a function to compare values with the following conditions :
1. if (string1 > string2) it returns a positive value.
2. if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
3. if (string1 < string2) it returns a negative value.
2. Using String.equals() :

105
BTech - II YEAR OOP THROUGH JAVA

In Java, string equals() method compares the two given strings based on the data/content of the string.
If all the contents of both the strings are same then it returns true. If any character does not match,
then it returns false.
Syntax:
str1.equals(str2);
Here str1 and str2 both are the strings that are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: false
Program:
Java
// Java program to Compare two strings
// lexicographically
public class GFG {
public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Practice");
String string3 = new String("Geeks");
String string4 = new String("Geeks");
String string5 = new String("geeks");

// Comparing for String 1 != String 2


System.out.println("Comparing " + string1 + " and "
+ string2 + " : "
+ string1.equals(string2));

// Comparing for String 3 = String 4


System.out.println("Comparing " + string3 + " and "
+ string4 + " : "
+ string3.equals(string4));

// Comparing for String 4 != String 5


System.out.println("Comparing " + string4 + " and "
+ string5 + " : "
+ string4.equals(string5));

// Comparing for String 1 != String 4


System.out.println("Comparing " + string1 + " and "
+ string4 + " : "
+ string1.equals(string4));
}
}

Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true

106
BTech - II YEAR OOP THROUGH JAVA

Comparing Geeks and geeks : false


Comparing Geeksforgeeks and Geeks : false
3. Using String.equalsIgnoreCase() :

The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper)
of the string. This method returns true if the argument is not null and the contents of both the Strings
are same ignoring case, else false. Syntax:
str2.equalsIgnoreCase(str1);
Here str1 and str2 both are the strings which are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: geeks
Input 2: Geeks
Output: true
Program:
Java
// Java program to Compare two strings
// lexicographically
public class GFG {
public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Practice");
String string3 = new String("Geeks");
String string4 = new String("Geeks");
String string5 = new String("geeks");

// Comparing for String 1 != String 2


System.out.println(
"Comparing " + string1 + " and " + string2
+ " : " + string1.equalsIgnoreCase(string2));

// Comparing for String 3 = String 4


System.out.println(
"Comparing " + string3 + " and " + string4
+ " : " + string3.equalsIgnoreCase(string4));

// Comparing for String 4 = String 5


System.out.println(
"Comparing " + string4 + " and " + string5
+ " : " + string4.equalsIgnoreCase(string5));

// Comparing for String 1 != String 4


System.out.println(
"Comparing " + string1 + " and " + string4
+ " : " + string1.equalsIgnoreCase(string4));
}
}

107
BTech - II YEAR OOP THROUGH JAVA

Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
Comparing Geeks and geeks : true
Comparing Geeksforgeeks and Geeks : false
4. Using Objects.equals() :
Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and
false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument
is null, false is returned. Otherwise, equality is determined by using the equals() method of the first
argument. Syntax:
public static boolean equals(Object a, Object b)
Here a and b both are the string objects which are to be compared.
Examples:
Input 1: GeeksforGeeks
Input 2: Practice
Output: false
Input 1: Geeks
Input 2: Geeks
Output: true
Input 1: null
Input 2: null
Output: true
Program:
Java
// Java program to Compare two strings
// lexicographically

import java.util.*;

public class GFG {


public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Geeks");
String string3 = new String("Geeks");
String string4 = null;
String string5 = null;

// Comparing for String 1 != String 2


System.out.println(
"Comparing " + string1 + " and " + string2
+ " : " + Objects.equals(string1, string2));

// Comparing for String 2 = String 3


System.out.println(
"Comparing " + string2 + " and " + string3
+ " : " + Objects.equals(string2, string3));

// Comparing for String 1 != String 4


System.out.println(
"Comparing " + string1 + " and " + string4
+ " : " + Objects.equals(string1, string4));
108
BTech - II YEAR OOP THROUGH JAVA

// Comparing for String 4 = String 5


System.out.println(
"Comparing " + string4 + " and " + string5
+ " : " + Objects.equals(string4, string5));
}
}

Output
Comparing Geeksforgeeks and Geeks : false
Comparing Geeks and Geeks : true
Comparing Geeksforgeeks and null : false
Comparing null and null : true
5. Using String.compareTo() for Comparing Two Strings
Syntax of String compareTo()
int str1.compareTo(String str2)
Working: It compares and returns the following values as follows:
1. if (string1 > string2) it returns a positive value.
2. if both the strings are equal lexicographically i.e.(string1 == string2) it returns 0.
3. if (string1 < string2) it returns a negative value.
Below is the implementation of the above method
Java
// Java program to Compare two strings
// Using String.compareTo()

import java.util.*;

// Diver Class
public class GFG {
public static void check(String string1, String string2)
{
if (string1.compareTo(string2)!=0) {
System.out.println(string1 + " " + string2
+ " : Not Equal");
}
else {
System.out.println(string1 + " " + string2
+ " : Equal");
}
}

// main function
public static void main(String args[])
{
String string1 = new String("Geeksforgeeks");
String string2 = new String("Geeks");
String string3 = new String("Geeks");
String string4 = " ";
String string5 = " ";

// Comparing for String 1 != String 2


check(string1, string2);

109
BTech - II YEAR OOP THROUGH JAVA

// Comparing for String 2 = String 3


check(string2, string3);

// Comparing for String 1 != String 4


check(string1, string4);

// Comparing for String 4 = String 5


check(string4, string5);
}
}

Output
Geeksforgeeks Geeks : Not Equal
Geeks Geeks : Equal
Geeksforgeeks : Not Equal
: Equal

Modify a String?

From the whole discussion that we’ve made above, we are very clear that strings are immutable i.e,
once created they cannot be changed. Thus, to modify them we use the following methods;
1) substring(): Using this method, you can extract a part of originally declared string/string object. This
method can be used in two ways:-
a) String substring(int startIndex): Using the startIndex, you specify the index from where your
modified string should start. Thus, your new string will from the specified index number and runs to the
end. For example, consider a string declared as, String S=”conversion”; thus, String S1=S.substring(2);
this gives us S1 as “nversion”.
b) String substring(int startIndex, int endIndex): In this method, you give the starting point as well
as the ending point of the new string. For example, String S2= S.substring(2,4); gives us S2=”nve”;

2) concat(): Using this function you can concatenate two strings. By this we mean, that you can
combine the two strings using concat(). You can even use this function to further add characters to the
original string. For instance, if you have a string, String S1=”Hello”; and you need to add more
characters to S1 then you can write, and String S2=S1.concat(” Everyone”);. This gives you the value of
S2 as “Hello everyone”.

3) replace(): This method is used to modify the original string by replacing some characters from it.
You can replace the characters in two ways:
a) String replace(char original, char replacement): This method replaces one and only character from
the original string. For example, String S=”Hello”.replace(‘e’, ‘x’); gives us Hwllo as the value of S.
b) String replace(CharSequence original, CharSequence replacement): Unlike the above method,
which replaces only one character at a time, using this method you can replace a sequence of characters
in one go. An example for this method can be given as String S=”He is a good boy”.replace(“good”,
“bad”); gives us an output; He is a bad boy.

4) trim(): Sometimes it may happen that you leave some extra spaces in the beginning or in the end of
your original string. When you print these kind of strings, they give an odd look. But since you cannot
change the value of these strings you can simply modify them by removing these extra white
spaces. For example, if you have declared a string by writing, String S1=”Hey there brown
cow”; which contains a lot of white spaces in the beginning as well as in the end. Thus, you can

110
BTech - II YEAR OOP THROUGH JAVA

improve it by using the trim function on it. You can write, String S2=S1.trim(); which removes the
extra white spaces.

Searching a Character in the String


Way 1: indexOf(char c)
It searches the index of specified characters within a given string. It starts searching from the
beginning to the end of the string (from left to right) and returns the corresponding index if found
otherwise returns -1.
Note: If the given string contains multiple occurrences of a specified character then it returns the
index of the only first occurrence of the specified character.
Syntax:
int indexOf(char c)
// Accepts character as argument, Returns index of
// the first occurrence of specified character
Way 2: lastIndexOf(char c)
It starts searching backward from the end of the string and returns the index of specified characters
whenever it is encountered.
Syntax:
public int lastIndexOf(char c)
// Accepts character as argument, Returns an
// index of the last occurrence specified
// character
Way 3: indexOf(char c, int indexFrom)
It starts searching forward from the specified index in the string and returns the corresponding index
when the specified character is encountered otherwise returns -1.
Note: The returned index must be greater than or equal to the specified index.
Syntax:
public int IndexOf(char c, int indexFrom)
Parameters:
 The character to be searched
 An integer from where searching
Return Type: An index of a specified character that appeared at or after the specified index in a
forwarding direction.
Way 4: lastIndexOf(char c, int fromIndex)
It starts searching backward from the specified index in the string. And returns the corresponding
index when the specified character is encountered otherwise returns -1.
Note: The returned index must be less than or equal to the specified index.
Syntax:
public int lastIndexOf(char c, int fromIndex)
Way 5: charAt(int indexNumber)
Returns the character existing at the specified index, indexNumber in the given string. If the specified
index number does not exist in the string, the method throws an unchecked exception,
StringIndexOutOfBoundsException.
Syntax:
char charAt(int indexNumber)
Example:

111
BTech - II YEAR OOP THROUGH JAVA

 Java

// Java Program to Illustrate to Find a Character

// in the String

// Importing required classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// String in which a character to be searched.

String str

= "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of character.

int firstIndex = str.indexOf('s');

System.out.println("First occurrence of char 's'"

+ " is found at : "

+ firstIndex);

// Returns index of last occurrence specified

// character.

int lastIndex = str.lastIndexOf('s');

System.out.println("Last occurrence of char 's' is"

+ " found at : " + lastIndex);

112
BTech - II YEAR OOP THROUGH JAVA

// Index of the first occurrence of specified char

// after the specified index if found.

int first_in = str.indexOf('s', 10);

System.out.println("First occurrence of char 's'"

+ " after index 10 : "

+ first_in);

int last_in = str.lastIndexOf('s', 20);

System.out.println("Last occurrence of char 's'" + " after index 20 is : "

+ last_in);

// gives ASCII value of character at location 20

int char_at = str.charAt(20);

System.out.println("Character at location 20: "

+ char_at);

// Note: If we uncomment it will throw

// StringIndexOutOfBoundsException

// char_at = str.charAt(50);

Output
First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111
Way 6: Searching Substring in the String
The methods used for searching a character in the string which are mentioned above can also be used
for searching the substring in the string.

113
BTech - II YEAR OOP THROUGH JAVA

Example
 Java

// Java Program to illustrate to Find a Substring

// in the String

// Importing required classes

import java.io.*;

// Main class

class GFG{

// Main driver method

public static void main(String[] args)

// A string in which a substring

// is to be searched

String str

= "GeeksforGeeks is a computer science portal";

// Returns index of first occurrence of substring

int firstIndex = str.indexOf("Geeks");

System.out.println("First occurrence of char Geeks"

+ " is found at : "

+ firstIndex);

// Returns index of last occurrence

int lastIndex = str.lastIndexOf("Geeks");

System.out.println(

"Last occurrence of char Geeks is"

114
BTech - II YEAR OOP THROUGH JAVA

+ " found at : " + lastIndex);

// Index of the first occurrence

// after the specified index if found

int first_in = str.indexOf("Geeks", 10);

System.out.println("First occurrence of char Geeks"

+ " after index 10 : "

+ first_in);

int last_in = str.lastIndexOf("Geeks", 20);

System.out.println("Last occurrence of char Geeks "

+ "after index 20 is : "

+ last_in);

Output
First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8
Way 7: contains(CharSequence seq): It returns true if the string contains the specified sequence of
char values otherwise returns false. Its parameters specify the sequence of characters to be searched
and throw NullPointerException if seq is null.
Syntax:
public boolean contains(CharSequence seq)
Note: CharSequence is an interface that is implemented by String class, Therefore we use string as an
argument in contains() method.
Example
 Java

// Java Program to Illustrate How to Find a Substring

115
BTech - II YEAR OOP THROUGH JAVA

// in the String using contains() Method

// Importing required classes

import java.io.*;

import java.lang.*;

// Class

Class GFG {

// Main driver method

public static void main(String[] args)

// String in which substring

// to be searched

String test = "software";

CharSequence seq = "soft";

boolean bool = test.contains(seq);

System.out.println("Found soft?: " + bool);

// Returns true substring if found.

boolean seqFound = test.contains("war");

System.out.println("Found war? " + seqFound);

// Returns true substring if found

// otherwise return false

boolean sqFound = test.contains("wr");

System.out.println("Found wr?: " + sqFound);

116
BTech - II YEAR OOP THROUGH JAVA

Output
Found soft?: true
Found war? true
Found wr?: false
Way 8: Matching String Start and End
 boolean startsWith(String str): Returns true if the string str exists at the starting of the given
string, else false.
 boolean startsWith(String str, int indexNum): Returns true if the string str exists at the starting
of the index indexNum in the given string, else false.
 boolean endsWith(String str): Returns true if the string str exists at the ending of the given
string, else false.
Example:
 Java

// Java Program to Match ofstart and endof a Substring

// Importing required classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Input string in which substring

// is to be searched

String str

= "GeeksforGeeks is a computer science portal";

// Print and display commands

System.out.println(str.startsWith("Geek"));

117
BTech - II YEAR OOP THROUGH JAVA

System.out.println(str.startsWith("is", 14));

System.out.println(str.endsWith("port"));

Output
true
true
false

118
BTech - II YEAR OOP THROUGH JAVA

Multithreading
A thread is similar to a program that has single flow of control. It has a beginning, a body and an end and
execute commands sequentially. All the main programs in our earlier examples can be called single
threaded programs. Every program will have at least one thread as shown below.

class Chakry  Begin


{
........
........  Single Threaded body of
........ execution
....
..
}  End
A program that contains multiple flows of control is known as multithreaded program. The following diagram shows
a java program with four threads, one main thread and three others.
Main Thread

Main Thread Program

start() start() start()

switching switching
Thread A Thread B Thread C
Whatis Thread?
 A thread is a single sequential flow of control within a program.
 A thread is a lightweight sub-process, the smallest unit of processing.
 Multithreading in Java is a process of executing multiple threads simultaneously.
 Multithreading use a shared memory area, they don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than process.
 It differs from a “process” in that a process is a program executing in its own address space whereas
a thread is a single stream of execution within a process.
 Java Multithreading is mostly used in games, animation, etc.

What is Multithreading in Java?


MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum
utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is
also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate
separate memory area, hence they save memory. Also, context switching between threads takes less time

Advantages of Java Multithreading


1. It doesn't block the user because threads are independent and you can perform multiple operations
at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

The Java Thread Model (Explain Java Thread Model)


In java, threads are implemented in the form of objects that contain a method called run() method. The
run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only
method in which the threads behavior can be implemented. The run() appear as follows.
public void run()
{
…………….
……………. // Statements for implementing thread
}

99
BTech - II YEAR OOP THROUGH JAVA

The run() method should be invoked by an object of the concerned thread. This can be achieved by creating
the thread and initiating it with the help of another thread method called “start()”. Some of the methods
which are available in Thread class as shown below:
S.No Modifier Method Description
and Type

1) void start() It is used to start the execution of the thread.

2) void run() It is used to do an action for a thread.

3) static void sleep() It sleeps a thread for the specified amount of time.

4) static Thread currentThread() It returns a reference to the currently executing thread object.

5) void join() It waits for a thread to die.

6) int getPriority() It returns the priority of the thread.

7) void setPriority() It changes the priority of the thread.

8) String getName() It returns the name of the thread.

9) void setName() It changes the name of the thread.

10) long getId() It returns the id of the thread.

11) boolean isAlive() It tests if the thread is alive.

12) static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.

13) void suspend() It is used to suspend the thread.

14) void resume() It is used to resume the suspended thread.

15) void stop() It is used to stop the thread.

16) void destroy() It is used to destroy the thread group and all of its subgroups.

17) Thread.State getState() It is used to return the state of the thread.

18) void notify() It is used to give the notification for only one thread which is
waiting for a particular object.

19) void notifyAll() It is used to give the notification to all waiting threads of a
particular object.

LIFE CYCLE OF A THREAD


During the life time of a thread, there are many states it can enter. They include
1.New born state
2.Runnable state
3.Running state
4.Blocked state
5.Dead state
A thread is always in one of these 5 states. It can move from one state to another in many ways as
shown below.

100
BTech - II YEAR OOP THROUGH JAVA

New Thread New Born

stop( )
start( )

stop( )
Active Thread Running Runnable Killed Thread
Dead
yield()

sleep( ) resume( )
suspend( ) notify( ) stop( )
wait( )
Idle Thread Blocked
( Not
( Not Run)
Runnable)
( Not Run)
1. New born state: In this phase, the thread is created using class "Thread class".It remains in this state till
the program starts the thread. It is also known as born thread.
2. Runnable state: In this state, the instance of the thread is invoked with a start() method. The thread
control is given to scheduler to finish the execution. It depends on the scheduler, whether to run the
thread.
3. Running state: When the thread starts executing, then the state is changed to "running" state. The
scheduler selects one thread from the thread pool, and it starts executing in the application.
4. Waiting(Blocked) state: This is the state when a thread has to wait. As there multiple threads are
running in the application, there is a need for synchronization between threads. Hence, one thread has to
wait, till the other thread gets executed. Therefore, this state is referred as waiting state.
5. Dead state: This is the state when the thread is terminated. The thread is in running state and as soon as
it completed processing it is in "dead state".
The program uses the following methods yield( ),sleep( ) and stop( ).
Program:
class A extends Thread
{
public void run ( )
{
for(int i=1; i<=20; i++)
{
if (i==3)
yield ( );
System.out.println(“From thread A: i= “+i);
}
}
}
class B extends Thread
{
public void run ( )
{
for (int j=1;j<=20;j++)
{
if (j==10)
stop ( );
System.out.println(“From thread B: j=”+j);
}
}
}

101
BTech - II YEAR OOP THROUGH JAVA

class C extends Thread


{
public void run ( )
{
for (int k=1;k<=20;k++)
{
try
{
sleep(1000);
}
catch (Exception e) { }
System.out.println(“From thread C: k=”+k);
}
}
}
class ThreadMethods
{
public static void main(String args[ ])
{
A p=new A( );
B q=new B( );
C r=new C( );
p.start( );
q.start( );
r.start( );
}
}
Creating threads
A new thread can be created in two ways.
1. By creating a thread class: Define a class that extends thread class and override its run() method with
the code required by the thread.
2. By converting a class to a thread(Using Runnable interface): Define a class that implements
Runnable interface. The Runnable interface has only one method, run( ), i.e., to be defined in the method
with the code to be executed by the thread.
I. EXTENDING THE THREAD CLASS
We can make our class runnable as thread by extending the class java.lang. Thread. This allows us to
access all the thread methods directly. It includes the following steps.
1. Declare the class as extending the Thread class.
2. Implement the run() method .
3. Create a thread object and call the start().
1. Declaring the thread class:
The thread can be extended as follows
class MyThread extends Thread
{
……….…….
……………..
} //Now we have a new type of thread MyThread.
2. Implementing the run ( ) method
The run ( ) method has been inherited by the class ‘MyThread’. We have to override this method in order to
implement the code to be executed by our thread. The basic implementation of run( ) is as follows
public void run()
{
…………..
………….. // Thread code here
}
When we start the new thread, java calls the threads run( ) method.
102
BTech - II YEAR OOP THROUGH JAVA

3. Starting New Thread:To create and run an instance of our thread class we must write the following.
MyThread aThread=new MyThread ( ); //Creation
aThread.start( ); //invokes run( ) method
The thread is also started by using the following statement.
new MyThread ( ).start( );
STOPPING AND BLOCKING A THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do by calling its stop( ) method.
aThread.stop( );
Here aThread is a thread object.
This statement causes the thread to move to the Dead state. A thread will also move to the dead state
automatically when it reaches the end of its method. The stop( ) method may be used when the thread is to
be stopped before its completion.
Blocking a thread
A thread can also be temporarily suspended (or) blocked from entering into the runnable and running state
by using the following thread methods.
sleep ( ) // blocked for a specified time.
suspend ( ) // blocked until further orders.
wait ( ) // blocked until certain conditions occur.
These methods cause the thread to go into the blocked state. The thread will return to the runnable
state when the specified time is elapsed in the case of sleep ( ), the resume ( ) method is invoked in the
case of suspend ( ), and the notify ( ) method is called in the case of wait( ) method.

2) Java Thread Example by implementing Runnable interface


The second method to create the threads is by using the Runnable interface. The Runnable
interface declares the run( ) method that is required for implementing threads in our programs. To do this,
we must perform the following steps.
(1) Declare the class as implementing the Runnable interface
(2) Implementing the run( ) method
(3) Create a thread by defining an object that is instantiated from the runnable class as the target of the
thread. Calls the thread’s start( ) method to run the thread.
1. class Multi3 implements Runnable{
2. public void run(){
3. System.out.println("thread is running...");
4. }
5. Output:thread is running...
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1);
9. t1.start();
10. }
11. }
NOTE
If you are not extending the Thread class,your class object would not be treated as a thread object.
So you need to explicitely create Thread class object.
We are passing the object of your class that implements Runnable so that your class run() method
may execute.
Sleep() method in java
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Syntax of sleep() method in java
The Thread class provides two methods for sleeping a thread:
 public static void sleep(long miliseconds)throws InterruptedException
 public static void sleep(long miliseconds, int nanos)throws InterruptedException
103
BTech - II YEAR OOP THROUGH JAVA

Example of sleep method in java


1. class TestSleepMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<5;i++){
4. try{
5. Thread.sleep(500);
6. }
7. catch(InterruptedException e){System.out.println(e);}
8. System.out.println(i);
9. }
10. }
11. public static void main(String args[]){
12. TestSleepMethod1 t1=new TestSleepMethod1();
13. TestSleepMethod1 t2=new TestSleepMethod1();
14. t1.start();
15. t2.start();
16. }
17. }

NOTE
Can we start a thread twice (2m)
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is
thrown. In such case, thread will run once but for second time, it will throw exception.
What if we call run() method directly instead start() method(2m)
 Each thread starts in a separate call stack.
 Invoking the run() method from main thread, the run() method goes onto the current call
stack rather than at the beginning of a new call stack.
The join() method
The join() method waits for a thread to die. In other words, it causes the currently running threads to stop
executing until the thread it joins with completes its task.
Syntax:
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Example of join() method
1. class TestJoinMethod1 extends Thread{
2. public void run(){
3. for(int i=1;i<=5;i++){
4. try{
5. Thread.sleep(500);
6. }catch(Exception e){System.out.println(e);}
7. System.out.println(i);
8. } }
9. public static void main(String args[]){
10. TestJoinMethod1 t1=new TestJoinMethod1();
11. TestJoinMethod1 t2=new TestJoinMethod1();
12. TestJoinMethod1 t3=new TestJoinMethod1();
13. t1.start();

104
BTech - II YEAR OOP THROUGH JAVA

14. try{
15. t1.join();
16. }catch(Exception e){System.out.println(e);}
17. t2.start();
18. t3.start();
19. } }

Naming Thread and Current Thread


The Thread class provides methods to change and get the name of a thread. By default, each thread has a
name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and getName() methods are given below:
1. public String getName(): is used to return the name of a thread.
2. public void setName(String name): is used to change the name of a thread.
Example of naming a thread
1. class TestMultiNaming1 extends Thread{
2. public void run(){
3. System.out.println("running...");
4. }
5. public static void main(String args[]){
6. TestMultiNaming1 t1=new TestMultiNaming1();
7. TestMultiNaming1 t2=new TestMultiNaming1();
8. System.out.println("Name of t1:"+t1.getName());
9. System.out.println("Name of t2:"+t2.getName());
10. t1.start();
11. t2.start();
12. t1.setName("NECN");
13. System.out.println("After changing name of t1:"+t1.getName());
14. }
15. }

Thread Priority
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread
schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which scheduling it chooses.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is10.

Example of priority of a Thread:


1. class TestMultiPriority1 extends Thread{
2. public void run(){
3. System.out.println("running thread name is:"+Thread.currentThread().getName());
4. System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
5. }
6. public static void main(String args[]){
105
BTech - II YEAR OOP THROUGH JAVA

7. TestMultiPriority1 m1=new TestMultiPriority1();


8. TestMultiPriority1 m2=new TestMultiPriority1();
9. m1.setPriority(Thread.MIN_PRIORITY);
10. m2.setPriority(Thread.MAX_PRIORITY);
11. m1.start();
12. m2.start();
13. } }

Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for
an object lock, that is acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization (2M)
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
1.1 Synchronized method.
1.2 Synchronized block.
1.3 static synchronization.
2. Cooperation (Inter-thread communication in java)

1. Java synchronized method


 If you declare any method as synchronized, it is known as synchronized method.
 Synchronized method is used to lock an object for any shared resource.
 When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.

Understanding the problem without Synchronization (Generating 5 thTable 10thTable )


In this example, there is no synchronization, so output is inconsistent. Let's see the example:
1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(1000);

106
BTech - II YEAR OOP THROUGH JAVA

7. }catch(Exception e){System.out.println(e);}
8. } } }
9. class MyThread1 extends Thread{
10. Table t;
11. MyThread1(Table t){
12. this.t=t;
13. }
14. public void run(){
15. t.printTable(5);
16. } }
17. class MyThread2 extends Thread{
18. Table t;
19. MyThread2(Table t){
20. this.t=t;
21. }
Output: 5
22. public void run(){ 100
23. t.printTable(100); 10
24. } } 200
25. 15
26. class TestSynchronization1{ 300
27. public static void main(String args[]){ 20
400
28. Table obj = new Table();//only one object
25
29. MyThread1 t1=new MyThread1(obj);
500
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }
From the above output that both the 5th Table and 100th Table values are jumbles and messed with each
other, since “void printTable(int n)” is not synchronized .
Generating 5th Table 10th Table using synchronized Method
1. class Table{
2. synchronized void printTable(int n){//synchronized method
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. } } }
9. class MyThread1 extends Thread{ Output: 5
10. Table t; 10
11. MyThread1(Table t){ 15
12. this.t=t; 20
13. } 25
100
14. public void run(){
200
15. t.printTable(5); 300
16. } } 400
17. class MyThread2 extends Thread{ 500
18. Table t;
19. MyThread2(Table t){
107
BTech - II YEAR OOP THROUGH JAVA

20. this.t=t;
21. }
22. public void run(){
23. t.printTable(100);
24. } }
25. public class TestSynchronization2{
26. public static void main(String args[]){
27. Table obj = new Table();//only one object
28. MyThread1 t1=new MyThread1(obj);
29. MyThread2 t2=new MyThread2(obj);
30. t1.start();
31. t2.start();
32. } }
Now, the output is clear and printed one after another (5th Table then 100th Table)
2. Synchronized Block in Java
1.Synchronized block can be used to perform synchronization on any specific resource of the method.
2.Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use
synchronized block.
3.If you put all the codes of the method in the synchronized block, it will work same as the synchronized
method.
Points to remember for Synchronized block
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
1. synchronized (object reference expression) {
2. //code block
3. }
Example of synchronized block Let's see the simple example of synchronized block.
1. class Table{
2. void printTable(int n){ Output:5
3. synchronized(this){//synchronized block 10
4. for(int i=1;i<=5;i++){ 15
5. System.out.println(n*i); 20
6. try{ 25
100
7. Thread.sleep(400);
200
8. }catch(Exception e){System.out.println(e);}
300
9. } 400
10. } 500
11. }//end of the method
12. }
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. } }

108
BTech - II YEAR OOP THROUGH JAVA

21. class MyThread2 extends Thread{


22. Table t;
23. MyThread2(Table t){
24. this.t=t;
25. }
26. public void run(){
27. t.printTable(100);
28. } }
29.
30. public class TestSynchronizedBlock1{
31. public static void main(String args[]){
32. Table obj = new Table();//only one object
33. MyThread1 t1=new MyThread1(obj);
34. MyThread2 t2=new MyThread2(obj);
35. t1.start();
36. t2.start();
37. } }

Inter-thread communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate
with each other.Cooperation (Inter-thread communication) is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in the same critical section to
be executed.
Example for Inter-thread communication
Producer-Consumer Problem
The producer-consumer problem (also known as the bounded-buffer problem) is a classic example of a
multi-thread synchronization problem. The problem describes two threads/processes, the producer and the
consumer, which share a common, fixed-size buffer used as a queue.
 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a
time.
Problem
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t
try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time the consumer
removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same
way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data
into the buffer, it wakes up the sleeping consumer.
It is implemented by following methods of Object class:
 wait()
 notify()
 notifyAll()
1) wait() method
 Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed.
 The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

109
BTech - II YEAR OOP THROUGH JAVA

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws InterruptedException waits for the specified amount of time.
2) notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object,
one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the
implementation. Syntax:
public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
completed.

Example of inter thread communication in java(as withdraw– Consumer; Deposit- Producer)


Let's see the simple example of inter thread communication.
1. class Customer{
2. int amount=10000;
3. synchronized void withdraw(int amount){
4. System.out.println("going to withdraw...");
5. if(this.amount<amount){
6. System.out.println("Less balance; waiting for deposit...");
7. try{wait();}catch(Exception e){}
8. }
9. this.amount-=amount;
10. System.out.println("withdraw completed...");
11. }
12. synchronized void deposit(int amount){
13. System.out.println("going to deposit...");
14. this.amount+=amount;
15. System.out.println("deposit completed... ");
16. notify();
17. }
18. }
110
BTech - II YEAR OOP THROUGH JAVA

19. class Test{


20. public static void main(String args[]){
21. final Customer c=new Customer();
22. new Thread(){ This is called “anonymous calling” ,
23. public void run(){c.withdraw(15000);} i.e without creating an object.
24. }.start();
25.
26. new Thread(){
27. public void run(){c.deposit(10000);}
28. }.start();
29. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

JDBC : (Java Data Base Connectivity) JDBC is an API(Application Programming Interface) that helps a
programmer to write java programs to connect to a database, retrieve data from the database and perform
various operations on the data in the java program.
There are FOUR types of JDBC drivers in use:
Type 1: JDBC-ODBC bridge.
Type 2: partial Java driver.
Type 3: pure Java driver for database middleware.
Type 4: pure Java driver for direct-to-database.

JDBC Driver: JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact with it by sending
SQL or database commands then receiving results with Java.
The Java.sql package that ships with JDK, contains various classes with their behaviors defined and their actual
implementations are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in
their database driver.
Type 1: JDBC-ODBC Bridge Driver: In a Type 1 driver, a JDBC bridge is used to access ODBC drivers
installed on each client machine. Using ODBC, requires configuring on your system a Data Source Name
(DSN) that represents the target database.
When Java first came out, this was a useful driver because most databases only supported ODBC access but
now this type of driver is recommended only for experimental use or when no other alternative is available.
Advantages: the JDBC-ODBC bridge allows access to almost any database, since the database’s ODBC drivers
are already available on the client machine.
Disadvantages: The performance of this driver is less, since the JDBC call goes through the bridge to the
ODBC driver, then to the native database connectivity library.

111
BTech - II YEAR OOP THROUGH JAVA

Type 2: JDBC-Native API: In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls,
which are unique to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client machine.
If we change the Database, we have to change the native API, as it is specific to a database and they are mostly
obsolete now, but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's
overhead.
Advantages: Type 2 drivers typically offer better performance than the JDBC-ODBC bridge.
Disadvantages: The vendor database library needs to be loaded on each client machine. This is the reason type-
2 drivers cannot be used for the internet. And it is show lower performance than type-3 and type-4 drivers.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java: In a Type 3 driver, a three-tier approach is used to access databases. The JDBC
clients use standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required by the DBMS,
and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can
actually provide access to multiple databases.
Advantages: This driver is server-based , so there is no need for any vendor database library to be present on
the client machine.
Disadvantages: This driver require database-specific coding to be done in the middle tier(Net server).
Maintenance of the middle-tier server becomes costly.

112
BTech - II YEAR OOP THROUGH JAVA

Type 4: 100% Pure Java: In a Type 4 driver, a pure Java-based driver communicates directly with the
vendor's database through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client or server.
Further, these drivers can be downloaded dynamically.
Advantages: This driver has better performance than type-1 and type-2. Here also no need to install any
special software on the client or server.
Disadvantages: the user needs a different driver for each database. For example, to communicate with oracle
server, we need oracle driver and to communicate with sybase server, we need sybase driver.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols,
database vendors usually supply type 4 drivers.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general,
JDBC Architecture consists of two layers.
JDBC API: This provides the application-to-JDBC Manager connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the
JDBC drivers and the Java application: Common JDBC Components

The JDBC API provides the following interfaces and classes −


1. DriverManager: This class manages a list of database drivers. Matches connection requests from the java
application with the proper database driver using communication sub protocol. The first driver that recognizes a
certain subprotocol under JDBC will be used to establish a database Connection.
2. Driver: This interface handles the communications with the database server. You will interact directly with
Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also
abstracts the details associated with working with Driver objects.
3. Connection: This interface with all methods for contacting a database. The connection object represents
communication context, i.e., all communication with database is through connection object only.
113
BTech - II YEAR OOP THROUGH JAVA

4. Statement: You use objects created from this interface to submit the SQL statements to the database. Some
derived interfaces accept parameters in addition to executing stored procedures.
5. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
6. SQLException: This class handles any errors that occur in a database application. After you've installed the
appropriate driver, it is time to establish a database connection using JDBC. The programming involved to
establish a JDBC connection is fairly simple.
JDBC classes and Interfaces
The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API
are given below:
1. Driver interface
2. Connection interface
3. Statement interface
4. PreparedStatement interface
5. CallableStatement interface
6. ResultSet interface
7. ResultSetMetaData interface
8. DatabaseMetaData interface
9. RowSet interface

A list of popular classes of JDBC API are given below:


1. DriverManager class
2. Blob class
3. Clob class
4. Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute the query with the database. But,
ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is
why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Creating JDBC Application (or) Establishing JDBC Database Connections


There are following six steps involved in building a JDBC application:
Import the packages: Requires that you include the packages containing the JDBC classes needed for database
programming. Most often, using import java.sql.* will suffice.
Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with
the database.
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with the database.
Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to
the database. Extract data from
result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result
set.
Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's
garbage collection.
importjava.sql.*;
classDBDemo{

114
BTech - II YEAR OOP THROUGH JAVA

publicstaticvoidmain(Stringargs[]){
try{
Class.forName(“oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",“scott",”tiger");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select*from emp");
while(rs.next())
System.out.println(rs.getInt(“eno”)+"…"+rs.getString(“ename”)+"…"+rs.getString(“Designation”));
con.close();
}catch(Exceptione)
{System.out.println(e);}
}
}

ResultSet in Interface
 ResultSet interface represents the result set of a database query by using SQL.
 When we use PreparedStatement for performing SQL query statements, it will return the
PreparedStatement object.
 Then we call the executeQuery() by using the PreparedStatement object and this result is assigned
to the ResultSet object.
 This ResultSet object contains the result of the SQL query.
 Now we will explore this concept to understand this concept in a better way. In this article, we learn
about ResultSet in JDBC and Its functionality and how to retrieve data from a ResultSet in JDBC.

Syntax:
The below statements is representing the syntax of ResultSet with PreparedStatement object.

PreparedStatement preparedStatement = connection.prepareStatement(sql_query);


ResultSet resultSet = preparedStatement.executeQuery();
We can observe syntax of ResultSet, which gets the ResultSet by using preparedStatement. This
preparedStatement is used for executing the SQL queries.

ResultSet in JDBC
The ResultSet is an interface available in JDBC which is used for data handling by using result object of
preparedStatement class.

Implementation of ResultSet
 First, we need create One class in our Java project.
 After that need to establish the connection with MySQL Database by using JDBC and We need one
jar file that is mysql-connector.jar file.
 Once complete connection then create table in database with some data in it.
 Now, write the SQL query for retrieving all data from Table by using prepared Statement.
 After that prepared Statement object is call the execute Query method for executing the SQL query
once the query is successfully executed then we get result of data based this SQL query.
 Now this result is assigned to ResultSet object.

115
BTech - II YEAR OOP THROUGH JAVA

Java FX GUI

Java FX Application Structure

JavaFX application is divided hierarchically into three main components known as Stage, Scene and nodes.
We need to import javafx.application.Application class in every JavaFX application. This provides the
following life cycle methods for JavaFX application.

o public void init()


o public abstract void start(Stage primaryStage)
o public void stop()
in order to create a basic JavaFX application, we need to:

1. Import javafx.application.Application into our code.


2. Inherit Application into our class.
3. Override start() method of Application class.

Stage

Stage in a JavaFX application is similar to the Frame in a Swing Application. It acts like a container for all
the JavaFX objects. Primary Stage is created internally by the platform. Other stages can further be created
by the application. The object of primary stage is passed to start method. We need to call show method on
the primary stage object in order to show our primary stage. Initially, the primary Stage looks like
following.

DISPLAYING TEXT AND IMAGE

JavaFX IMAGES: The javafx.scene.image.Image class is used to load an image into a JavaFX
application. This supports BMP, GIF, JPEG, and, PNG formats.

JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the
loaded image.

To display an image in JavaFX −

 Create a FileInputStream representing the image you want to load.


 Instantiate the Image class bypassing the input stream object created above, as a parameter to its
constructor.
 Instantiate the ImageView class.
 Set the image to it by passing above the image object as a parameter to the setImage() method.
 Set the required properties of the image view using the respective setter methods.
 Add the image view mode to the group object.

JavaFX Text Node


The text node in JavaFX is represented by the class named Text, which belongs to the
package javafx.scene.text.

This class contains several properties to create text in JavaFX and modify its appearance. This
class also inherits the Shape class which belongs to the package javafx.scene.shape.

116
BTech - II YEAR OOP THROUGH JAVA

Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc. It
also inherits the basic shape node properties such
as strokeFill, stroke, strokeWidth, strokeType etc.

Creating a Text Node


Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you can
create a text by instantiating this class as follows −

Text text = new Text();

The class Text contains a property named text of string type, which represents the text that is to
be created.

After instantiating the Text class, you need to set value to this property using
the setText() method as shown below.

String text = "Hello how are you"


Text.setText(text);

You can also set the position (origin) of the text by specifying the values to the properties x and
sing their respective setter methods namely setX() and setY() as shown in the following code
block

text.setX(50);

text.setY(50);

Java Event Handling


Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces
for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

117
BTech - II YEAR OOP THROUGH JAVA

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:

 Button
public void addActionListener(ActionListener a){}
 MenuItem
public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.

118
BTech - II YEAR OOP THROUGH JAVA

16. //add components and set size, layout and visibility


17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that
sets the position of the component it may be button, textfield etc.

2) Java event handling by outer class


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new Button("click me");
10. b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(tf);
16. setSize(300,300);
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new AEvent2();
22. }
23. }
1. import java.awt.event.*;

119
BTech - II YEAR OOP THROUGH JAVA

2. class Outer implements ActionListener{


3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=obj;
6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welcome");
9. }
10. }

3) Java event handling by anonymous class


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent3 extends Frame{
4. TextField tf;
5. AEvent3(){
6. tf=new TextField();
7. tf.setBounds(60,50,170,20);
8. Button b=new Button("click me");
9. b.setBounds(50,120,80,30);
10.
11. b.addActionListener(new ActionListener(){
12. public void actionPerformed(){
13. tf.setText("hello");
14. }
15. });
16. add(b);add(tf);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public static void main(String args[]){
22. new AEvent3();
23. }
24. }

Mouse Events

An event which indicates that a mouse action occurred in a component. This event is used both
for mouse events (click, enter, exit) and mouse motion events (moves and drags).

This low-level event is generated by a component object for:

 Mouse Events
o a mouse button is pressed
o a mouse button is released
o a mouse button is clicked (pressed and released)
o the mouse cursor enters a component
o the mouse cursor exits a component
 Mouse Motion Events
o the mouse is moved
o the mouse is dragged

A MouseEvent object is passed to every MouseListener or MouseAdapter object which registered to


receive the "interesting" mouse events using the component's addMouseListener method.
120
BTech - II YEAR OOP THROUGH JAVA

(MouseAdapter objects implement the MouseListener interface.) Each such listener object gets
a MouseEvent containing the mouse event.

A MouseEvent object is also passed to every MouseMotionListener or MouseMotionAdapter object which


registered to receive mouse motion events using the component's addMouseMotionListener method.
(MouseMotionAdapter objects implement the MouseMotionListener interface.) Each such listener object
gets a MouseEvent containing the mouse motion event.

When a mouse button is clicked, events are generated and sent to the registered
MouseListeners, with the button mask set in the modifier field. For example, if the first mouse
button is pressed, events are sent in the following order:
MOUSE_PRESSED: BUTTON1_MASK
MOUSE_RELEASED: BUTTON1_MASK
MOUSE_CLICKED: BUTTON1_MASK

When multiple mouse buttons are pressed, each press, release, and click results in a separate
event. The button mask in the modifier field reflects only the button that changed state, not the
current state of all buttons.

For example, if the user presses button 1 followed by button 2 and releases them in the same
order, the following sequence of events is generated:
MOUSE_PRESSED: BUTTON1_MASK
MOUSE_PRESSED: BUTTON2_MASK
MOUSE_RELEASED: BUTTON1_MASK
MOUSE_CLICKED: BUTTON1_MASK
MOUSE_RELEASED: BUTTON2_MASK
MOUSE_CLICKED: BUTTON2_MASK

If button2 is released first, the MOUSE_RELEASED/MOUSE_CLICKED pair


for BUTTON2_MASK arrives first, followed by the pair for BUTTON1_MASK.

See Also:
MouseAdapter,
MouseListener,
MouseMotionAdapter,
MouseMotionListner,
Tutorial: Writing a Mouse Listener,
Tutorial: Writing a Mouse Motion Listener,
Reference: The Java Class Libraries (update file), Serialized Form

Field Summary
(package clickCount
private) int Indicates the number of quick consecutive clicks of a mouse button.
static int MOUSE_CLICKED
The "mouse clicked" event.
static int MOUSE_DRAGGED
The "mouse dragged" event.
static int MOUSE_ENTERED
The "mouse entered" event.
static int MOUSE_EXITED
The "mouse exited" event.
static int MOUSE_FIRST
121
BTech - II YEAR OOP THROUGH JAVA

The first number in the range of ids used for mouse events.
static int MOUSE_LAST
The last number in the range of ids used for mouse events.
static int MOUSE_MOVED
The "mouse moved" event.
static int MOUSE_PRESSED
The "mouse pressed" event.
static int MOUSE_RELEASED
The "mouse released" event.
(package popupTrigger
private) boolean A property used to indicate whether a Popup Menu should appear with a certain gestures.
private serialVersionUID
static long
(package x
private) int The mouse events x coordinate.
(package y
private) int The mouse events y coordinate.

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified against MouseEvent. The
MouseListener interface is found in java.awt.event package. It has five methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
122
BTech - II YEAR OOP THROUGH JAVA

22. l.setText("Mouse Exited");


23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }
Output:

Java MouseListener Example 2


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21. public static void main(String[] args) {
22. new MouseListenerExample2();
23. }
24. }
Output:

123
BTech - II YEAR OOP THROUGH JAVA

124

You might also like