r23 Java Material
r23 Java Material
UNIT-1
Introduction:
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)
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.
AECN, ATMAKUR 2
OOP THROUGH JAVA (R23)
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.
5. Distributed :
Java is a distributed language designed for creating applications on networks. It has the ability to share
both data and programs.
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
AECN, ATMAKUR 3
OOP THROUGH JAVA (R23)
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)
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)
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: 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
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.
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.
AECN, ATMAKUR 6
OOP THROUGH JAVA (R23)
3) Unicode Characters.
4) Escape Sequence characters (\n, \t, \f, \r, \b etc)
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:
Expression Result
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.
In the above syntax, the operator can be either +=, –=, *=, /= or %= Variable
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
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 )
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
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
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.
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.
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
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).
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.
The java object frame work for java virtual machine is as shown below.
AECN, ATMAKUR 14
OOP THROUGH JAVA (R23)
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.
class CommandLineExample
{
public static void main(String args[ ])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Output:
Your first argument is: raheem
class A
{
public static void main(String args[ ])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Output:
abdul
raheem
nellore
AECN, ATMAKUR 15
OOP THROUGH JAVA (R23)
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.
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.
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);
}
}
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
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.
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
Variable names may consist of alphabets, digits, underscores and dollar characters.
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.
A variable must be declared before it is used in the program. Syntax for declaration of a variable is as
follows.
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”.
The readLine( ) method reads the input from the keyboard as a string.
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.
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: 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’);
System.out.print(“hai”);
System.out.print(‘\n’);
System.out.print(“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
Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or
interface.
b = (byte) a;
OUTPUT
System.out.println("b = " + b );
b = 94
}
}
AECN, ATMAKUR 20
OOP THROUGH JAVA (R23)
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.
Primitive Non-Primitive
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)
Control Statements
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”);
T Cond-1 F
T Cond-2 F T Cond-3 F
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”);
}
}
}
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
► 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
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
AECN, ATMAKUR 28
OOP THROUGH JAVA (R23)
UNIT-II
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
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.
►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;
}
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)
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
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.
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");
}
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:
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.
The methods that are declared with the static keyword are called static methods
The static variable and static methods can be called without using the objects. They are also available for
use by other classes.
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.
Nesting of methods
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)
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.
The methods that are declared with the static keyword are called static methods
The static variable and static methods can be called without using the objects. They are also available for
use by other classes.
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.
Nesting of methods
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) ;n1
// 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);
}
}
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.
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
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
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.
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
{
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;
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.
public int b = 2;
protected int c = 3;
int d = 4;
}
Compiling the above program:
9
BTech - II YEAR OOP THROUGH JAVA
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
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
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:
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
}
}
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
java.util.Date Constructors
2) Date(long Creates a date object for the given milliseconds since January 1,
milliseconds) 1970, 00:00:00 GMT.
java.util.Date Methods
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.
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
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.
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
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. }
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
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:
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.
+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
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:
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
import java.util.Formatter;
formatter.format("%16.2e", 123.1234567);
formatter.format("%.4f", 123.1234567);
// Format 4 places.
formatter.format("%.4g", 123.1234567);
formatter.format("%.15s", "12345678901234567890");
19
BTech - II YEAR OOP THROUGH JAVA
formatter.format("%010d", 88);
}
}
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
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
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
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.
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
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
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;
}
Example
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
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 {
75
BTech - II YEAR OOP THROUGH JAVA
}
}
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");
}
}
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
78
BTech - II YEAR OOP THROUGH JAVA
79
BTech - II YEAR OOP THROUGH JAVA
User-defined Exceptions:
You can create your own exceptions in Java.
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.
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.
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.
These two abstract classes have several concrete classes that handle various devices such as disk files,
network connection etc.
Stream class Description
DataOutputStream An output stream that contain method for writing java standard data type
83
BTech - II YEAR OOP THROUGH JAVA
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.
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
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:
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
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);
}
}
87
BTech - II YEAR OOP THROUGH JAVA
reader()
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.
88
BTech - II YEAR OOP THROUGH JAVA
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. }
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.
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.
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.
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
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.
99
BTech - II YEAR OOP THROUGH JAVA
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().
public String():
This constructor creates an empty String object. However, the use of this constructor is
unnecessary becauseString objects are immutable.
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.
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:
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
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);
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)
Example:
public class GetCharsExample {
public static void main(String[] args) {
String str = "Hello, World!";
char[] dst = new char[5];
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;
Output:
Byte array: [72, 101, 108, 108, 111]
4. toCharArray()
Syntax:
public char[] toCharArray()
Example:
public class ToCharArrayExample {
public static void main(String[] args) {
String str = "Hello";
char[] charArray = str.toCharArray();
Output:
Character array: [H, e, l, l, o]
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;
// 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");
Output
Comparing Geeksforgeeks and Practice : false
Comparing Geeks and Geeks : true
106
BTech - II YEAR OOP THROUGH JAVA
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");
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.*;
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 = " ";
109
BTech - II YEAR OOP THROUGH JAVA
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.
111
BTech - II YEAR OOP THROUGH JAVA
Java
// in the String
import java.io.*;
// Main class
class GFG {
String str
+ firstIndex);
// character.
112
BTech - II YEAR OOP THROUGH JAVA
+ first_in);
+ last_in);
+ char_at);
// 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
// in the String
import java.io.*;
// Main class
class GFG{
// is to be searched
String str
+ firstIndex);
System.out.println(
114
BTech - II YEAR OOP THROUGH JAVA
+ first_in);
+ 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
115
BTech - II YEAR OOP THROUGH JAVA
import java.io.*;
import java.lang.*;
// Class
Class GFG {
// to be searched
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
import java.io.*;
// Main class
class GFG {
// is to be searched
String str
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.
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.
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
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.
12) static void yield() It causes the currently executing thread object to pause and allow
other threads to execute temporarily.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
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.
100
BTech - II YEAR OOP THROUGH JAVA
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
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.
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. } }
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.
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)
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
109
BTech - II YEAR OOP THROUGH JAVA
Method Description
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()
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
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.
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
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
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.
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
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.
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.
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.
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.
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.
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);
ActionEvent ActionListener
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
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){}
1. Within class
2. Other class
3. Anonymous class
118
BTech - II YEAR OOP THROUGH JAVA
119
BTech - II YEAR OOP THROUGH JAVA
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).
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
(MouseAdapter objects implement the MouseListener interface.) Each such listener object gets
a MouseEvent containing the mouse 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
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.
123
BTech - II YEAR OOP THROUGH JAVA
124