Você está na página 1de 109

Chapter 1 - Object Oriented Concepts

The following are the major features of Object Oriented


Objects
Classes
Data Abstraction
Data Encapsulation
Inheritance
Polymorphism
The details description of every feature is given below

Object
An object is a real time entity which has identity, state, and behavior.
For example let us consider a Car as an Object then we can give the following ID, State and
behavior

Class
A class is a collection of related Objects. A class is a collection of data members and methods.
The State of an object will act as data members in the class and the behavior of an object will
act as methods in the class.
eg:
class Employee
{
int empNum;
String empName;
double empSalary;
void setEmpDetails()
{}
void dispEmpDetails()
{}
}
1 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Once the class is created, the members of the class are accessed by using objects.
Creating Objects
The following example gives the way to create the objects
Employee e;//CPP
Employee e = new Employee();//Java
Once the object is created the members of the class are accessed using object with dot (.)
operator as follows
e.empNum = 111;
e.empName = "Raj";
e.setEmpDetails();

Abstraction
Showing only essential details and hiding unnecessary details is called as abstraction
We can even define an abstraction as hiding the implementation details is also known as
abstraction
As an example if we consider the method Arrays.sort() which is used to sort the elements of
the array, here the implementation of sort() method is hidden to us.

Encapsulation
The wrapping upof data and methods together into a container called class and by
providing security to data is called as encapsulation
For example consider the following class
class Emp
{
private int age;
void setAge(int a)
{
if (a >=18 & < 60)
age = a;
else
print Invalid age;
}
}
Emp e;
e.age = -20;//Error
e.setAge(30);
In the above example we cannot access age directly outside the class as age variable is private.
Private members are accessible only within the class. In order to give value to age, it is done

2 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

only using a method setAge() since we can validate whether the value given to age is valid or
not. By giving private to a data member of a class, the data member will be secured so that we
cannot give invalid data to the data member
A class is fully encapsulated (secured) when all data members are private

Inheritance
Creating a new class from an existing class is called as inheritance. The process of arranging the
classes in the form of hierarchy is also known as inheritance. Through inheritance we can
achieve reusability of the code. The new class which is creating using exiting class is called as
sub class or derived class or child class. The exiting class is called as super class or base class or
parent class. The Derived class object can access the members of its own class and the
members of Base class.
For example
class Vehicle
{}
class Car extends Vehicle
{}
Some more examples of inheritance

Forms/Types of Inheritance

3 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Polymorphism
Polymorphism means many forms
Following are the types of polymorphism

Given additional functionality to an operator is called as operator overloading. For example +


operator is used to add two numbers and concatenate two strings
In Method Overloading, method name is same but the signature is different. Signature means
number of arguments or type of arguments.
For example, following are the overloaded methods
int area(int n1,int n2,int n3){}
int area (int n1,int n2){}
float area(float n1,float n2){}
In Method Overriding, method name is same and signature is also same. Overriding is
applicable only in inheritance.
For example
class Vehicle
{
void drive()
{}
}
class Car extends Vehicle
{
void drive() //Overridden
{}
}

4 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 2 - Java Introduction


Introduction
Java is object oriented programming language developed James Gosling at Sun Microsystems
in 1995. Sun Microsystems is now merged with Oracle Corporation

Java Versions
Following are the different versions released by Java
- JDK 1.0 (Java Development Kit)
- JDK 1.1
- JDK 1.2
- JDK 1.3
- JDK 1.4
- J2SE =>Java 2 standard edition - used to develop standalone applications
- J2EE =>Java 2 Enterprise Edition - used to develop web applications
- J2ME =>Java 2 Micro/Mobile Edition - used to develop mobile applications
- Java 5/Java1.5
- JSE
- JEE
- JME
- Java 6/Java 1.6
- Java 7/Java 1.7
- Java 8/Java 1.8 (March 2014)

Java Features (Buzzwords)


Following are the important features of Java
1. Simple
Java Programming is simple as it contains lots of APIs (Application Programming
Interfaces) called as libraries.
2. Object Oriented
By using Java, we can develop the applications using Object Oriented Approach. Java
supports all the features of Object Oriented
3. Robust
Robust means strong. If any abnormal situation occurs during the execution of the
Program, the program should not terminate automatically, should provide proper
message to the user and continue with the remaining program. We can develop robust
applications in Java using Exception Handling
4. Platform Independent
A Java Program can run on any platform either 32-bit OS or 64-bit OS. If a java program
is developed on 32-bit OS, it can be executed on 64-bit OS without doing any modifications in
the program. A Java program is like Write Once Run Anywhere. A Java program is a collection
of classes.

5 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Consider the following example


X.java
class A
{
main(){}
}
class B
{
main(){}
}
In the above program X. java, it contains two class A and B. In order to compile the Java
program use the following command
> javac X. java
this command will generates two files A.class and B.class which are called as Byte Codes.
These byte codes are platform independent
To Run a Java program, at least one class should contain the main().
To run java program use the following command
>java A => which runs the program from A class main()
>java B => which runs the program from B class main()
5. Interpreted
An interpreter converts the source code object code line by line. In Java, java command
is an interpreter which converts the Java byte code into machine understandable code.
6. Portable
Java is highly portable. In Java the program from one platform to other platform is
shifted with doing any modifications to the program as in Java the size of all primitive data
types is same on all the platforms.
7. Secure
Java is secure as Java does not support pointers. A pointer is a variable which stores the
address of another variable. The disadvantage of pointers is to violate the security.
8. Multithreaded
A thread is a light weight process under execution with in a process. Multithreading is
used to increase the performance of an application. In Java we can develop multi threaded
applications in order to increase the performance of Java application.
9. Dynamic
In Java memory allocation for arrays, strings and any object is done during runtime which is
dynamic.

6 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

10. Distributed
By using Java we can develop distributed applications. A distributed application which is
present in the remote machine can be accessed by the other machine without giving the code.
In Java we can develop distributed applications using with RMI (Remote Method Invocation),
EJB (Enterprise Java Beans) and Web Services.

Downloading and Installing Java


We can download and install the latest version of Java Development Kit (JDK) from the
following URL
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Once the Java is downloaded and installed, it will get installed in C:\Program
Files\Java\jdk1.8.0 by default which is termed as JAVA_HOME.
We find the javac.exe and java.exe files in JAVA_HOME\bin folder. The commands are used to
compile and run Java programs.
To use these command in our folder we need to set the path to JAVA_HOMe\bin folder as
follows at the command prompt.
>set path = C:\Program Files\jdk1.8.0\bin;%path%;
here %path% is used to append the previous path settings.
The path setting which is done at the command prompt is temporary setting means once we
close the command prompt window, the path settings will also gets removed.
To set the path permanently do the following the steps.
Right Click on Computer Properties Click on Advanced System Settings Click on
Environment Variables Click on New
Variable Name : path
Variable Value : C:\Program Files\jdk1.8.0\bin
Click Ok.

Developing a Java Application at command prompt


Follow the steps to develop a Java Application at command prompt
Open Command prompt by typing cmd in Start -> Run
Which displays as follows
C:\>
Change the drive to D: (Optional) as follows
C:\>D:
D:\>
Create a folder/directory RT-Java as follows
D:\>md RT-Java
md means Make Directory

7 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Change the folder to RT-Java as follows


D:\>cd RT-Java
D:\RT-Java>
cd means Change Directory
Create a file Welcome.java as follows
D:\RT-Java>notepad Welcome.java
Type the following code in Welcome.java file
1. //To display Welcome to Raj Technologies message onto the screen
2. class Welcome
3. {
4.
public static void main(String[] args)
5.
{
6.
System.out.println(Welcome to Raj Technologies);
7.
}
8. }
Note: Save the file (ctrl + s)
Compile Welcome.java as follows
D:\RT-Java>javac Welcome.java
Which creates Welcome.class file called as byte code
Run Welcome.class file as follows
D:\RT-Java>java Welcome
Which displays Welcome to Raj Technologies onto the screen.
Explanation of the above program
In the above program Line 1 is the comment line. Comments are ignored by compiler. Java has
three types of comments which are given below.
Single line Comment - //
Multi line Comment - /* . */
Document Comment - /** .. */
Line 2 is the class. In Java everything including main() should be inside the class.
Line 3 & 8 are opening and closing of class Welcome.
Line 4 is the main() where the program execution begins from main(). The main() should be in
the format public static void main(String[] args).
A Java program is executed by JVM (Java Virtual Machine) which acts as an interface between
Java Byte Code and Operating System. Since JVM is outside of the class, to access main() of the
class, the main() should be public as public members are accessible outside the class.
The members of the class are accessed by using object. Here we are not creating object of
Welcome class to access main(). To access main() directly with the class name the main() should
be static as static members are accessible directly with the class name without creating objects.
main() return type is void as main() does not return anything back to JVM.
The argument in main() is String[] args which is used to store command line arguments which
are passed during program execution

8 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

For example
>java Welcome X Y Z
In the above example X Y and Z are command line arguments which are stored in the String[]
args of main().
Line 5 and 8 are opening and closing braces of main().
Line 7 System.out.println() which is used to display messages or the value of variables onto
the screen. Here System is a predefined class, out is data member of System class which is an
object of PrintStream class and it is static and println() is a method belongs to PrintStream class.

Command Line Arguments


We can pass the values to the main() of a Java program from the Command Line when
we are running the program.
Consider the following example program which is used to find the sum of two numbers using
command line arguments
//Sum of two numbers using Command line arguments
class Sum
{
public static void main(String[] args)
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int sum = n1 + n2;
System.out.println(Sum = +sum);
}
}
To Run
>java Sum 10 20
In the above program 10 and 20 are the command line arguments which are stored in args
array which is of type String. args[0] contains value 10 and args[1] contains value 20.
Integer.parseInt() is used to convert a String into int type.

Scanner class
Scanner class is used to read the values into variables from keyboard during program execution.
Scanner class is added in Java 5 version. Scanner class is present in the package java.util
package. To the Scanner class in the program we need to import java.util.Scanner as follows
import java.util.Scanner;
Methods in Scanner class
- byte nextByte() which is used to read a byte value
- short nextShort() which is used to read a short value
- int nextInt() which is used to read an int value

9 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

long nextLong() which is used to read long value


float nextFloat() which is used to read a float value
double nextDouble() which is used to a double value
boolean nextBoolean() which is used to a Boolean value
String next() which is used to read a String value without spaces
String nextLine() which is used to read a String value with spaces

Creating Scanner class object


Scanner in = new Scanner(System.in);
Here in and object of Scanner class. System.in refers to the keyboard.
Consider the following example program Student.java which uses Scanner class to read the
values into variables from keyboard
Student.java
//To find total and average of given three marks
import java.util.Scanner;
class Student
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println(Enter Roll No );
int rollno = in.nextInt();
System.out.println(Enter Name );
String name = in.next();
System.out.println(Enter 3 Marks );
double mark1 = in.nextDouble();
double mark2 = in.nextDouble();
double mark3 = in.nextDouble();
double total = mark1 + mark2 + mark3;
double avg = total/3;
System.out.println(Roll No =+rollno);
System.out.println(Name = +name);
System.out.println(Total = +total);
System.out.println(Average = +avg);
}
}

10 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 3 Java Basics


Introduction to Data Types:
Here we examine Javas most fundamental elements such as:

Data types

Variables

Arrays.
Like all modern programming languages, Java supports several types of data. In order to
store data we have to think of types of data to be stored. Hence java provides lot of data
types to declare variables and to create arrays.
Data Types:
Name

Types

Integer

byte, short, int, long

Float

float, double

Character

char

Integers: This group includes


byte, short, int, and long, which
are for whole-valued signed
Boolean
boolean
numbers.
Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false
values.
You can use these as simple data types, or user defined data types such as constructing
arrays, or class types. Thus, they form the basis for all other types of data that you can
create.
Java supports integer types such as

byte
short
int
long

11 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The table below discuss about the size and range of values to be kept with the variables of
respective types.
Name
Type

Description

Size

Sample Declaration
& initialization

Range

byte

Signed integer

1 byte

-128 to 127

byte myByte = 100;

short

Signed integer

2 byte

-32768 to 32767

short myShort = 1000;

int

Signed integer

4 byte

-2147483648 to 2147483647

int myInt = 100000;

long

Signed integer

8 byte

-9223372036854775808
9223372036854775807

to long myLong = 0;

Floating Point Numbers


Floating-point numbers, also known as real numbers, are used for storing fractional
precision.
Their size and ranges are shown in the following table:
Characters
The data type used to store characters such as any alphabet is char. This data type in Java
is not the same as char in C or C++. In C/C++, char is of 8 bits wide. In Java char data type
supports multi byte size. This is so because while storing some characters of local language
it takes more than one byte. It is a unification of dozens of character sets, such as Latin,
Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
Following table discuss about the char data type.
Name
Type

Sample Declaration
Description

Char

Unicode
Character

Size

Range

2 bytes

\u0000 to \uFFFF

& initialization
char myChar = 'a';

Booleans
Java has a simple type for storing logical values, called Boolean. It can consist of one of two
possible values, true or false. This is the type returned by all relational operators, such as a
< b. boolean is also the type required by any conditional expressions that govern the
control statements such as if and for.
Name
Type
boolean

Description
true or false

Size
1 bit

Range
{true, false}

Sample Declaration &


initialization
boolean myBool = true;

12 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Java Keyword List


Keywords are special reserved words in Java that cannot be used as identifiers (names) for
classes, methods, or variables.
Table shows list of Java keywords and reserved words, which are updated through Java
5.0. const and goto are reserved but are not implemented. enum is the latest keyword
and was added to the language in Java 5.0 (displayed in bold letter in Figure). Remember
that none of the words in this list can be used as identifiers in Java programs.

Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
The Simple Assignment Operator
One of the most common operators that you'll come upon is the simple assignment
operator "=". You saw this operator in the Bicycle class; it assigns the value on its right and
the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references, as discussed in
Simple Data Objects.
The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their
counterparts in basic mathematics. The only symbol that might look new to you is "%",. The
symbol "%", which divides one operand by another and returns the remainder as its result.

13 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

additive operator
subtraction operator
multiplication operator
division operator
Remainder operator

+
*
/
%

The Unary Operators


The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value
of a boolean.
+
++
-!

Unary plus operator; indicates positive value


Unary minus operator; negates an expression
Increment operator; increments a value by 1
Decrement operator; decrements a value by 1
Logical complement operator; inverts the value of a boolean

The increment/decrement operators can be applied before (prefix) or after (postfix) the
operand. The code result++; and ++result; will both end in result being incremented by one.
The only difference is that the prefix version (++result) evaluates to the incremented value,
whereas the postfix version (result++) evaluates to the original value. If you are performing
a simple increment/decrement, it doesn't really matter which version you choose. But if
you use this operator in part of a larger expression, the one that you choose may make a
substantial difference.
The Equality and Relational Operators
The equality and relational operators determine if one operator is greater than, less than,
equal to, or not equal to another operand. The majority of these operators will probably
look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if
two primitive values are equal.
==

Equal to

!=

not equal to

>

greater than

>=

greater than or equal to

<

less than

<=

less than or equal to

14 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The Conditional Operators


The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that
the second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR
The Type Comparison Operator instanceof
The instanceof operator compares an object to a specified type. You can use it to test if an
object is an instance of a class, an instance of a subclass, or an instance of a class that
implements a particular interface.
The Java programming language also provides operators that perform bitwise and bit shift
operations on integral types. The operators discussed in this section are less commonly
used. Therefore, their coverage is brief; the intent is to simply make you aware that these
operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any
of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte
contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would
change its pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left by one position. The signed
right shift operator ">>" shifts a bit pattern to the right by one position. The unsigned right
shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position
after ">>" depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
For & and | above, the result has a 1 in each bit position for which both of the operands
have a 1.
The following program named BitDemo.java, uses the bitwise AND operator to print the
number "2" to standard output.
BitDemo.java
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}

15 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

As we explore the operators of the Java programming language, it may be helpful for you to
know ahead of time which operators have the highest precedence/importance. The
operators in the following table are listed according to precedence/importance.
The closer to the top of the table an operator appears, the higher its precedence. Operators
with higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence
appear in the same expression, a rule must govern which is evaluated first. All binary
operators except for the assignment operators are evaluated from left to right; assignment
operators are evaluated right to left.
Operators
Postfix
Unary
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR
Logical AND
Logical OR
Conditional
Assignment

Precedence
expr++ expr-++expr --expr +expr -expr ~ !
*/%
+<< >> >>>
< > <= >= instanceof
== ! =
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>= >>>=

Control Statements
The computer programs are written with statements which helps in organizing the
program structure and its meaning. When you write a program, you type statements into a
file. In programs, the individual statement, instructions or function calls of an imperative or
functional program are executed. With the increasing demand of conditions and
complications arising in a particular work or in solving a program, it is necessary to control
the flow of the program. Without control flow statements, the interpreter executes the
statements in the order they appear in the file from left to right, top to bottom. What if you
wanted to change the flow?
For example, you want the program to take some decisions and do different things
depending on different situations such as printing 'Good Morning' or 'Good Evening'
depending on the time of the day?
As you might have guessed, this is achieved using control flow statements.

16 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Control flow Statements


A program is a group of statements that are executed to achieve a predetermined task.
Statements in a program are generally executed in a sequential manner, which is called
sequential execution or sequential control flow. However, by putting the decision-making
statement in the program, the normal flow of the program can be controlled. Statements
that control the flow of the program are called control statements.
Control statements are used in programming languages to cause the flow of control to
advance and branch based on changes to the state of a program.In Java, control statements
can be divided under the following three categories:

Selection statements
Iteration statements
Jump statements

Table 1 shows categories of control flow statements available in Java and keywords list for
each categories.
Control flow statement category
Selection statements

Keyword list
if, else, switch, case

Iteration statements

while, do, for

Jump statements

return, break, continue

Table 1: Control flow statements and related keywords list


Selection statements in Java
A program is a group of statements that are executed to achieve a predetermined task.
Statements in a program are generally executed in a sequential manner, which is called
sequential execution or sequential control flow. Selection statements are used in a program
to choose different paths of execution based upon the outcome of an expression or the state
of a variable. Java supports two selection statements: if and switch.
The if statement
The if statement executes a block of code only if the specified expression is true. The
condition to the if statement must be an expression that evaluates to a boolean value. . If
the condition evaluates to true, the statement following the if statement is executed. If the
value is false, then the if block is skipped and execution continues with the rest of the
program. You can either have a single statement or a block of code within an if statement.

17 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The simple if statement has the following syntax:


if (condition)
{
statement1;
}
The following example demonstrates conditional execution based on if statement
condition.
public class IfStatementDemo {

public static void main(String[] args) {


int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}

Output
b>a
The If-else Statement

The "if-else" statement is an extension of if statement that provides another option when
'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. You can
either have a single statement or a block of code within if-else blocks. The else statement is
optional,but if it is present,it must be placed immediately after the code block attached to
the if statement. The code block attached to the else statement is executed when the
condition to the if statement evaluates to false.
The general form of the if statement is given below:
if (condition)
{
statement1;
}
else
{
statement2;
}

18 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The following example demonstrates conditional execution based on if-else statement


condition.
public class IfElseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
} else {
System.out.println("b > a");
}
}
}
Output
b>a
The chained If-else Statement

Under the chained format the execution evaluates all conditional expressions beginning
from Expression1 (given below) until the first expression is found that evaluates to true.
Then the corresponding statement sequence is executed, or, if none of the expressions
evaluated to true, the statement sequence of the final else part.
The general form of the if statement is given below:
if ( Expression1 ) {
Statement1a
Statement1b
...
} else if ( Expression2 ) {
Statement2a
Statement2b
...
} else if ( Expression3 ) {
Statement3a
Statement3b
...
} else {
Statement4a
Statement4b
...
}

19 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The Switch Case Statements

The switch case statement, also called a case statement is a multi-way branch with several
choices. A switch is easier to implement than a series of if/else statements. The switch
statement begins with a keyword, followed by an expression that equates to a no long
integral value. Following the controlling expression is a code block that contains zero or
more labeled cases. Each label must equate to an integer constant and each must be unique.
When the switch statement executes, it compares the value of the controlling expression to
the values of each case label. The program will select the value of the case label that equals
the value of the controlling expression and branch down that path to the end of the code
block. If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases where
there are no matches. We can have a nested switch within a case block of an outer switch.
The general form of a switch statement is given below:
switch(expression){
case val1:
code_block1
case val2:
code_block2
.
.
.
default:
code_default;
}
The break statement is used within the code block attached to the switch statement to
terminate a statement sequence. Therefore, if you want to exit in the middle of the switch
statement code block, you must insert a break statement, which causes the program to
continue executing after the current code block.
The argument to the switch must be an integral expression that must evaluate to a 32-bit or
smaller integer type: byte,short,char,or int. Moreover,the legal range of the argument's data
type must cover all the case constants used in the code block. For example,the following
code fragment will not compile successfully:
byte b = 10;
switch( b ){
case 10 :
System.out.print("ten");
break ;
20 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

case 10 :
System.out.print("10") ;
break ;
}
Iteration Statements in Java
Iteration statements enable program execution to repeat one or more statements, i.e.
iteration statements form loops. In Java, there are three iteration statements: for, while and
do. An enhanced for loop has been added in J2SE 5.
The for statement
The for loop is the most versatile looping construct. It is used to continuously execute a
block of code until a particular condition is satisfied. It comprises three parts: initialization,
condition and iteration.
The initialization portion is generally an expression that sets the value of the loop control
variable. The loop control variable acts as a counter and controls the execution of the loop.
The initialization portion executes only once. The condition portion must be a boolean
expression. It usually tests the loop control variable against a target value and hence works
as a loop terminator. The iteration portion is usually an expression that increments or
decrements the loop control variable.
The general form of the for loop is:
for(initialization; condition; iteration)
{
//body of the loop
}
All the three components, i.e., initialization, condition and iteration are optional. In case
there is only a single statement in the body of the loop, the curly braces can be omitted.
The for loop executes in the following three steps:

When the loop first starts, the initialization expression is executed and then the control is
transferred to step 2.
The condition is evaluated. If the condition evaluates to true, the body of the loop executes and the
program control is transferred to step 3. If the condition evaluates to false, the loop terminates.
The iteration expression executes and then the control is transferred to step 2.

All the sections in the for-header are optional. Any one of them can be left empty, but the
two semicolons are mandatory. In particular, leaving out the <condition> signifies that the
loop condition is true. The (;;) form of for loop is commonly used to construct an infinite

21 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

loop. Below is an example that demonstrates the looping construct namely for loop used to
print numbers from 1 to 10.
public class ForLoopDemo {

public static void main(String[] args) {


System.out.println("Printing Numbers from 1 to 10");
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}

The for-each statement

The general form of the for-each loop is as follows:


for(type itrvar: collection)
{
//body of the loop
}
where, itrvar is the variable that iterates through the elements of the collection.
The for-each loop is an enhanced for loop, used to iterate over arrays and collections. This
feature is added to Java to make the access and retrieval of elements of arrays and
collections faster. The EnhancedForDemo.java program, uses the enhanced for to loop
through the array and produces the same output as shown in the previous example:
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
System.out.println("Printing Numbers from 1 to 10");
for (int item : numbers) {
System.out.println(item);
}
}
}
The While Statement
The while statement is a looping construct control statement that executes a block of code
while a condition is true. You can either have a single statement or a block of code within
the while loop. The loop will never be executed if the testing expression evaluates to false.
The loop condition must be a boolean expression.

22 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The general form of the while loop is as follows:


while(condition)
{
block
}
where, the condition may be any expression that evaluates to a boolean value. The code
block attached to the while statement is repeatedly executed unless the condition evaluates
to false. Below is an example that demonstrates the looping construct namely while loop
used to print numbers from 1 to 10.
public class WhileLoopDemo {

public static void main(String[] args) {


int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}

You can implement an infinite loop using the while statement as follows:
while (true)
{
// your code goes here
}
Do-while Loop Statement
This statement is similar to the while statement discussed above. The only difference in
this case is that the code block attached to the do statement is executed before the
condition is checked. Therefore, even in the case of the condition evaluating to false, the
code block executes at least once. A do-while loop begins with the keyword do, followed by
the statements that make up the body of the loop. Finally, the keyword while and the test
expression complete the do-while loop. When the loop condition becomes false, the loop is
terminated and execution continues with the statement immediately following the loop.
You can either have a single statement or a block of code within the do-while loop.
The syntax of the do-while loop is
do
{
code_block
} while(condition);
23 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Below is an example that demonstrates the looping construct namely do-while loop used to
print numbers from 1 to 10.
public class DoWhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
Jump statements
Jump statements are used to unconditionally transfer the program control to another part
of the program. Java has three jump statements: break, continue and return.
The break statement
A break statement is used to abort the execution of a loop. The general form of the break
statement is given below:
break;
class BreakDemo
{
public static void main(String[]s)
{
int count = 5;
while(true) {
if(count == 5) {
System.out.println("jump out of the while block");
break;
}}}}
A break may be used with or without a label. When it is used without a label, it aborts the
execution of the innermost switch, for, do, or while statement enclosing the break
statement. When used with a label, the break statement aborts the execution of any
enclosing statement matching the label. When used with a label the syntax is:
break label;
Note: A label is an identifier that uniquely identifies a block of code.
24 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The continue statement


A continue statement stops the iteration of a loop (while, do or for) and causes execution to
resume at the top of the nearest enclosing loop. You use a continue statement when you do
not want to execute the remaining statements in the loop, but you do not want to exit the
loop itself.
The syntax of the continue statement is
continue;
//
the
unlabeled
form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement.
The label name is optional, and is usually only used when you wish to return to the
outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers
between 1 to 10.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "\t");
}
}
}
Output
Odd Numbers
1
3
5
7
9
The return statement
A return statement is used to transfer the program control to the caller of a method. The
general form of the return statement is given below:
return expression;
If the method is declared to return a value, the expression used after the return statement
must evaluate to the return type of that method. Otherwise, the expression is omitted.
To return a value, simply put the value (or an expression that calculates the value) after the
return keyword.
return ++count;

25 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 4 - Arrays
Introduction
An array is a contiguous block of memory locations referred by a common name. The type
of the elements of the array is called the base type of the array. The number of elements it
holds is a fixed attribute called its length. Java supports arrays of all primitive and
reference types.
For e.g.
To store the marks of 5000 students, you can declare an array called marks, of size 5000
and can store the marks of as many students.
int marks[] = new int[5000];

Arrays

Why array is needed?

You might come across a situation where you need to store similar type of values for a large
number of data items.
For e.g.
To store the marks of all the students of a university, you need to declare thousands of
variables. In addition, each variable name needs to be unique. It would not be practical to
hold each in a separately named variable. To avoid such situations, you can use arrays.
Instead of using individual variables, we will use a whole number of variables.
An array consists of a name and the number of elements of the array. You can refer to a
specific array element by the array name and the element number, which is known as the
index number.
You should always remember that array index element number always starts with 0(zero).

Array: A pictorial depiction

An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed.
This section discusses arrays in greater detail.

26 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Fig. 1: An Array of Ten Elements


Each item in an array is called an element, and each element is accessed by its numerical
index. As shown in the above illustration, numbering begins with 0. The 9th element, for
example, would therefore be accessed at index 8.
Creating Arrays
The length of an array is fixed at the time of its creation. An array represents related
entities having the same data type in contiguous or adjacent memory locations. The related
data having data items form a group and are referred to by the same name.
For e.g.
employee[5];
Here, the employee is the name of the array and of size 5. The complete set of values is
known as an array and the individual entities are called as elements of the array.
A specific value in an array is accessed by placing the index value of the desired element in
a square bracket.
Advantages of using Arrays
You can refer to a large number of elements by just specifying the index number and the
array name.
Arrays make it easy to do calculations in a loop.
The various types of arrays in java are:

One-dimensional arrays
Two-dimensional arrays
Multi-dimensional arrays

One-dimensional Arrays

One-dimensional array is a list of variables of the same data type.


Syntax to declare a one-dimensional array
type array_name []; //type is the datatype of the array.
For e.g.
String designations []; // designations is name of the array.

27 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Allocating Memory to Arrays

The new operator is used to allocate memory to an array.


Syntax to allocate memory is
array_name = new type[size];
For e.g. designations = new String[10]; //size of the array is 10.

Length of an array

Each array has a constant (final) instance variable that has its length. You can find out how
many elements an array can hold by writing the array name followed by .length. In the
previous example, a.length would be 100. Remember that this is the number of elements in
the array, one more than the maximum subscript.

Accessing Arrays

You need to access various elements of an array to assign, retrieve, and manipulate the
values stored in the array.

Assigning values to the Elements of an Array

To access a specific array,

You need to specify the name of the array and the index number of the element.
The index position of the first element in the array is 0.

For e.g.
String designations[];
designations = new String[2];
designations[0] = General Manager;
designations[1]=Managing Director;
You can declare and allocate memory to a user-defined array in a single statement.
Syntax:
type arr [] = new type[size];

28 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

For e.g.
int employees[] = new int[10];
You can also declare and initialize arrays in the same statement.
For e.g.
String designations[] = {General Manager, Managing Director};
Declaring a Variable to Refer to an Array
ArrayDemo.java declares an Array with the following line of code:
int[] anArray;

// declares an array of integers

Two-dimensional Arrays

In addition to one-dimensional arrays, you can create two-dimensional arrays. To declare


two-dimensional arrays, you need to specify multiple square brackets after the array name.
Syntax to declare a two dimensional array
type array_name = new type[rows][cols];
For e.g.
int multidim[] = new int[3][];
In a two-dimensional array,

You need to allocate memory for only the first dimension.


You can allocate the remaining dimensions separately.
When you allocate memory to the second dimension, you can also allocate different number to each
dimension.

For e.g.
int multidim[] = new int[3][];
multidim[0] = new int[1];
multidim[1] = new int[4];
If you think of a one-dimensional array as a column of values you can think of a twodimensional array as a table of values like so:

29 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

c0 c1 c2 c3
r0 0 1

2 3

r1 1 2

3 4

r2 2 3

4 5

r3 4
3 5
4
r4

5 7
6
6

Here we have an array with five rows and four columns. It has twenty total elements.
However, we say it has dimension five by four, not dimension twenty. This array is not the
same as a four by five array like this one:
c0 c1 c2 c3 c4
r0 0 1 2 3 4
r1 1 2 3 4 5
r2 2 3 4 5 6
r3 3 4 5 6 7
We need to use two numbers to identify a position in a two-dimensional array. These are
the element's row and column positions. For instance if the above array is called J then
J[0][0] is 0, J[0][1] is 1, J[0][2] is 2, J[0][3] is 3, J[1][0] is 1, and so on.
Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one dimensional
arrays. However we have to specify two dimensions rather than one, and we typically use
two nested for loops to fill the array.
The array examples above are filled with the sum of their row and column indices. Here's
some code that would create and fill such an array:
class FillArray {
public static void main (String args[]) {
int[][] M;
M = new int[4][5];
for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
M[row][col] = row+col;
}
}
}
}

30 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Of course the algorithm you would use to fill the array depends completely on the use to
which the array is to be put. Here is a program that calculates the identity matrix for a
given dimension. The identity matrix of dimension N is a square matrix, which contains
ones along the diagonal and zeros in all other positions.
class IDMatrix {
public static void main (String args[]) {
double[][] ID;
ID = new double[4][4];
for (int row=0; row < 4; row++) {
for (int col=0; col < 4; col++) {
if (row != col) {
ID[row][col]=0.0;
}
else {
ID[row][col] = 1.0;
}
}
}
}
}
Multidimensional Arrays

You do not have to stop with two dimensional arrays. Java lets you have arrays of three,
four or more dimensions. However chances are pretty good that if you need more than
three dimensions in an array, you're probably using the wrong data structure. Even three
dimensional arrays are exceptionally rare outside of scientific and engineering
applications.
The syntax for three dimensional arrays is a direct extension of that for two-dimensional
arrays. Here is a program that declares, allocates and initializes a three-dimensional array:
class Fill3DArray {
public static void main (String args[]) {
int[][][] M;
M = new int[4][5][3];
for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
for (int ver=0; ver < 3; ver++) {
M[row][col][ver] = row+col+ver;
}
}
}
}
}

31 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

We need three nested for loops here to handle the extra dimension.
The syntax for still higher dimensions is similar. Just add another pair of brackets and
another dimension.
Finally, you can use the built-in length property to determine the size of any array. The
code for that is
System.out.println(anArray.length);

32 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 5 Java OOP


Class
A class is a collection of data members (fields) and methods.
Consider the following example
class Employee
{
int empNum;
Data Members
String empName;
double empSalary;
void setEmpDetails()
{
...
}
Methods
void dispEmpDetails()
{
...
}
}

Object
An instance of a class is called as object. The members of the class are accessed by using
objects.
Creating Objects
The following syntax gives the creation of object in Java
ClassName ObjName = new ClassName();
eg:
Employee e = new Employee();
Once the object is created for the class, the members of the class are accessed by using object
with dot( . ) operator. For example,
e.empNum=111;
e.empName = "Raj";
e.setEmpDetails();
e.dispEmpDetails();
this reference
this reference is used to refer to the current object. this reference is generally used to
differentiate data members of a class and arguments of a method when the name are same.

33 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Example Program
//EmployeeDemo.java
class Employee
{
int empNum;
Stirng empName;
double empSalary;
void setEmpDetails(int empNum,String empName,double empSalary)
{
this.empNum = empNum;
this.empName = empName;
this.empSalary = empSalary;
}
void dispEmpDetails()
{
System.out.println(Emp Num = +empNum);
System.out.println(Emp Name =+empName);
System.out.println(Emp Salary =+empSalary);
}
}
class EmployeeDemo
{
public static void main(String[] args)
{
Employee e1 = new Employee();
e1.setEmpDetails(111,Venu,5000);
e1.dispEmpDetails();
Employee e2 = new Employee();
e2.setEmpDetails(222,Raj,6000);
e2.dispEmpDetails();
}
}
Compiling and Running above EmployeeDemo.java
>javac EmployeeDemo.java
>java EmployeeDemo
Which displays the following output
Emp Num = 111
Emp Name = Venu
Emp Salary = 5000
Emp Num = 222
Emp Name = Raj
Emp Salary = 6000
34 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Constructors
A Constructor is a special method whose name is same as the class name which is used to
initialize an object and does not return anything not even void.
Consider the following example
class Sample
{
int i;
int j;
Sample() //constructor
{
i=10;
j=20;
}
}
Sample s = new Sample();
When the object object is created the values of i and j for the object s will be 10 and 20
respectively.
Points on Constructors
If a class does not contain a constructor, Java provides a default constructor which looks as
follows
class Sample
{
Sample(){} //default constructor added implicitly
}
If a class contains a parameterized constructor then it is the responsibility of the
programmer to create default constructor
For a top level class we can give only default and public as access modifiers. The access
modifier given to the default constructor is same as the access modifier given to the class.
A constructor can be private. If a constructor is private then the object of the class need to
be created within the class.
If a method name is same as the class name with return type then this method is treated as
ordinary method but not as a constructor
Example Program
//ConstructorDemo.java
class Rectangle
{
int length;
int breadth;

35 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Rectangle(int length,int breadth)


{
this.length = length;
this.breadth = breadth;
}
Rectangle(){} //default constructor
int area()
{
return length * breadth;
}
}
class ConstructorDemo
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(10,5);
System.out.println(Area of Rectangle = +r.area());
}
}
Output
Area of Rectangle = 50

static keyword
static keyword can be used for data members(variables) of a class, methods of the class
and inner classes. static keyword cannot be used for top level class and local variables. static
members are accessible directly with the class name without creating objects. Objects can even
access static members. A static variable acts as a global variable within class means all the
objects of the class can share static variable memory. When the class gets loaded into JVM, first
it will allocate memory for static variables and this memory is allocated only once then object
gets created by allocating memory for instance variables. Static methods can only other static
members directly. A non static member cannot be referenced from static context.
Consider the following example program for static keyword
//StaticDemo.java
class Sample
{
int m;//instance variable or non-static variable
static int n;//class or static variable
void xxx() //instance or non-static method
{
m = 10;
n = 20;
}
36 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

static void yyy() //class or static method


{
//m=30; //Error non-static cannot be referenced from static context
n = 40;
}
void display()
{
System.out.println(m=+m+ +n=+n);
}
}
class StaticDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.xxx();
s1.display();//m=10 n=20
Sample s2 = new Sample();
s2.display();//m=0 n=20
s2.yyy();
s1.display();//m=10 n=40
s2.display();//m=0 n=40
Sample.n=50;
s1.display();//m10 n=50
s2.display();//m=0 n=50
}
}

Inheritance
The process of creating a new class from an existing class is called as inheritance. The existing
class is called as base class or parent class or super class. The new class which is created using
existing class is called as derived class or child class or sub class. Through inheritance we
achieve reusability of the code means the object of derived class can access the members of
base class.
In Java extends keyword is used to create a new class from an existing class. For example,
class Vehicle
{
.
}
class Car extends Vehicle
{
.
}
37 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

In the above example Vehicle is the base class and Car is the derived class created using the
base class Vehicle.
Java does not support multiple inheritance due to ambiguities.
Examples of inheritance

Inheritance is a is-a relationship. When we use extends keyword from one class to another
class, is-a meaning should come between the class.
Example Program
//InheritanceDemo1.java - Simple Inheritance
class Base
{
int i;
int j;
void inputIJ(int i,int j)
{
this.i=i;
this.j=j;
}
void displayIJ()
{
System.out.println("i="+i+" "+"j="+j);
}
}
class Derived extends Base
{
int k;
void inputK(int k)
{
this.k=k;
}
void displayK()
{
System.out.println("k="+k);
}
}

38 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

class InheritanceDemo1
{
public static void main(String[] args)
{
Base b = new Base();
b.inputIJ(10,20);
b.displayIJ();//i=10 j=20
Derived d = new Derived();
d.inputIJ(30,40);
d.displayIJ();//i=30 j=40
d.inputK(50);
d.displayK();//k=50
}
}

Polymorphism
Polymorphism means many forms. Polymorphism is of two types Compile time polymorphism
and run time polymorphism.

Java does not support Operator overloading due to ambiguities to the programmers.

39 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Difference between Method Overloading and Method Overriding


Method Overloading
Method Overriding
Compile time Polymorphism
Run Time Polymorphism
Method name is same but the signature is Method name is same signature is also same
different.
Signature means number of arguments and
type of arguments
Applicable within the same class as well as sub Applicable only in sub classes
classes
Examples:
Example:
area(int n1,int n2,int n3){}
class Vehicle
area(int n1,int n2){}
{
area(float n1,float f2){}
void drive()
{

}
}
class Car extends Vehicle
{
void drive() //overridden method
{

}
}
Car c = new Car();
c.drive();//invokes drive() in Car
If a derived class method invokes the
overridden method , it will invoke the method
present in derived class
Example Program
//InheritanceDemo2.java - Method Overloading and Method Overridding
class Base
{
int i;
int j;
void input(int i,int j)
{
this.i=i;
this.j=j;
}

40 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

void display()
{
System.out.println("i="+i+" "+"j="+j);
}
}
class Derived extends Base
{
int k;
void input(int k) //overloading
{
this.k=k;
}
void display() //Overridden
{
super.display();
System.out.println("k="+k);
}
}
class InheritanceDemo2
{
public static void main(String[] args)
{
Base b = new Base();
b.input(10,20);
b.display();//i=10 j=20
Derived d = new Derived();
d.input(30,40);
d.display();//i=30 j=40 k=0
d.input(50);
d.display();//i=30 j=40 k=50
}
}
super reference
super is used to refer to the base class members from derived class method
super() is the first statement added implicitly to every constructor
To call parameterized constructor of base class from derived class constructor, call it
explicitly
call to super() must be the first statement in constructors

41 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Constructors in Inheritance
Example Program
//InheritanceDemo3.java - Constructors in Inheritance
class Base
{
int i;
int j;
Base(int i,int j)
{
this.i=i;
this.j=j;
}
Base(){}
void display()
{
System.out.println("i="+i+" "+"j="+j);
}
}
class Derived extends Base
{
int k;
Derived(int k)
{
//super();//added implicitly
super(30,40);//call it explicitly
this.k=k;
}
void display() //Overridden
{
super.display();
System.out.println("k="+k);
}
}
class InheritanceDemo3
{
public static void main(String[] args)
{
Base b = new Base(10,20);
b.display();//i=10 j=20
Derived d = new Derived(50);
d.display();//i=30 j=40 k=50
}
}

42 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Note:
If a Base class reference refers to the sub class object, it can invoke only the overridden
methods of sub class.
final keyword
final keyword can be used for a variable, method and class.
Consider the following table for the final keyword
Variable
Method
Class
- It is a constant means the - It cannot be overridden - It cannot be sub classed
final variable value cannot be means final methods of base means final class cannot have
modified
class cannot be overridden in sub classes
Example:
sub classes
Example:
final int MAX_VALUE = 100;
Example:
final class Base{}
MAX_VALUE = 200;//Error
class Base
class Derived extends Base{}
{
//Error
final void xxx()
{}
}
Class Derived extends Base
{
void xxx() //Error
{}
}

Predefined final classes


String
System
Math
Byte
Short
Character
Integer
Long
Float
Double
Boolean

Abstract classes

Abstract classes are used to form the rules or specifications


A method which is just declared is called as abstract method
An abstract class contains zero or more abstract methods

43 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

eg:
abstract class Sample
{
void xxx(){} //defined or implemented
abstract void yyy(); //declared
}
If a class extends an abstract class then we need to override all abstract methods else
make the class as abstract
eg
class Sample1 extends Sample
{
void yyy()
{}
void zzz(){}
}
abstract class Sample2 extends Sample
{
void ppp(){}
}

We cannot create the objects for abstract classes but we can create references referring
to the sub class object

eg:
Sample s = new Sample();//Error
Sample s1 = new Sample1();//valid
Vehicle v1 = new Car();

Forces "is-a" relationship

Example Program
//AbstractDemo.java
abstract class Vehicle
{
abstract void drive();
void applyBreak()
{
System.out.println("Applying Break");
}
}

44 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

class Car extends Vehicle


{
void drive()
{
System.out.println("Driving a Car");
}
void changeGear()
{
System.out.println("Changing Gear");
}
}
class AbstractDemo
{
public static void main(String[] args)
{
//Vehicle v = new Vehicle();//Error
Car c = new Car();
c.drive();
c.applyBreak();
c.changeGear();
Vehicle v1 = new Car();
v1.drive();
v1.applyBreak();
//v1.changeGear();//Error
}
}

Interfaces
It is used to form the rules or specifications
Does not force "is-a" relationship
In an interface all methods are public and abstract by default
In an interface all variables are public, static and final by default
eg:
interface I1
{
int n;
void xxx();
void yyy();
}
If a class implements an interface, then we need override all methods else make the
class as abstract

45 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

eg:
class C1 implements I1
{
void xxx(){}
void yyy(){}
}
A class can implement multiple interfaces
eg:
interface I2
{
void ppp();
}
class C2 implements I1,I2
{
void xxx(){}
void yyy(){}
void zzz(){}
}
class to class we use extends keyword
class to interface we use implements keyword
interface to interface we use extends keyword
eg:
interface I3 extends I1,I2
{}

We cannot create objects for interfaces but we can create references referring to the
sub class object

Example Program
//InterfaceDemo.java
interface Shape
{
void draw();
}
class Circle implements Shape
{
public void draw()
{
System.out.println("Drawing a Circle");
}
}

46 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

class InterfaceDemo
{
public static void main(String[] args)
{
Circle c = new Circle();
c.draw();
}
}
/*
When implementing interface methods, the overridden method should be public
*/
Note: abstract and final are illegal combination of modifiers

Packages
- A package is a collection of related classes and interfaces (.class files)
- "package" keyword is used to create package
eg:
package mypack;
- package statement should be the first statement in the source code file
eg
package mypack;
import ...
import ...
class A
{}
class B
{}
- we can have only one package statement in a source code file
- The classes under the package should be stored in a folder whose name is same as the
package name
- Only public classes / members are accessible outside the package
- To use the classes of one package into another package, we need to import the package
import mypack.A;
import mypack.B;
or
import mypack.*; * indicates all classes
Predefinded packages
- java.lang
- java.util
- java.io
- java.sql
- java.awt
47 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Access Modifiers
- private => accessible only within the class
- default => accessible only within the package
- protected => accessible within the package and sub class of another package
- public => accessible everywhere
Example Program
//Calculator.java
package mypack1;
public class Calculator {
public int add(int n1,int n2)
{
return n1+n2;
}
public int multiply(int n1,int n2)
{
return n1*n2;
}
}
//PackageDemo.java
package mypack2;
import mypack1.*;
public class PackageDemo {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println("Sum = "+c.add(10,20));
System.out.println("Product = "+c.multiply(10,20));
}
}

48 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 6 - java.lang package


java.lang package contains the classes and interfaces which are used in almost all in Java
programs. java.lang package is imported to all java programs implicitly.
Following are some of the class commonly used in most of the programs are under java.lang
package

Object
String
System
StringBuffer
StringBuilder
Byte
Short
Character
Integer
Long
Float
Double
Boolean

Object class
Object is the top most class sitting in Java Hierarchy. All the classes under java are sub classes of
Object class. If a class does not extend other class, the by default the class extends Object class.
Object class is also known as Cosmic super class
Object class contains 11 methods which are given below.
1. clone()
- used to create a duplicate object
eg:
Emp e = new Emp();
Emp e1 = e.clone();//e1 is duplicate Object
2. equals()
- used to compare the hashcodes of objects
eg:
e.equals(e1);//true
3. finalize()
- used to do the cleanup operations like closing of files,
closing of database connections etc
- finalize() is called just prior to the garbage collection
4. getClass()
- used to return the name of the class of an object

49 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

eg:
Item i = new Item();
..
..
SOP(i.getClass());//Item
5. hashCode()
- used to return the hashcode of an object
6. toString()
- used to represent an object in String format. When an object is displayed in
System.out.println(), it invokes toString() of Object class implicitly which returns the name of
the class of the object along with the hashcode of the object. To represent an object in
readable format we need to override toString() in out class.
Consider the following example program
//toString()
class Sample
{
int i;
int j;
Sample(int i,int j)
{
this.i=I;
this.j=j;
}
public String toString()
{
return i=+i+ +j=+j;
}
}
class ToStringDemo
{
public static void main(String[] args)
{
Sample s = new Sample(10,20);
System.out.println(s);//i=10 j=20 - invokes toString() of Sample class implicitly
}
}
7. wait()
8. wait(long)
9. wait(int,long)
10. notify()
11. notifyAll()
The above methods wait(), notify() and notifyAll() are discussed in Multitheading.

50 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

String class
A String in java is a predefined class. A String is a collection of characters. In Java a String is
immutable means once the String is created in the memory the value of String memory cannot
be modified.
Consider the following diagrams related to Strings.

In the above diagram s1 refers to an object Hello in the heap memory. In Java objects are
created in heap memory. When you make s1 to refer to the object World, the object Hello
will not be replaced with World instead of that Java will allocate another memory for World
and s1 will be now referring the object World. The object Hello is no longer referenced by
s1. Now the object Hello is ready for garbage collection. The objects which are no longer
referenced are ready for garbage collection and these objects will be removed from heap
memory during garbage collection process.

In the above diagram s1 and s2 refers to the same object Hello in the head memory. To check
whether the both the references are referring to the same object we use ==. To check
whether the values present in the objects are same or not we use equals().

51 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Question : If (s1.equals(s2)) returns true then will it always s1 == s2 returns true?


Answer: No (Explanation in the below diagram)

Example Program
//StringDemo.java
public class StringDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println(s1.hashCode()+" "+s2.hashCode());
String s3 = new String("Welcome");
String s4 = new String("Welcome");
System.out.println(s3==s4);//false
System.out.println(s3.equals(s4));//true
}
}
StringBuffer class
StringBuffer is mutable means the object value present in StringBuffer can be modified.
All the methods in StringBuffer class are synchronized
For Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append("World");
System.out.println(sb);//HelloWorld
StringBuilder class
StringBuilder is mutable means the object value present in StringBuilder can be modified.

52 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

All the methods in StringBuilder class are not synchronized


For Example:
StringBuilder sb = new StringBuilder("Hello");
sb.append("World");
System.out.println(sb);//HelloWorld
System.gc()
System.gc() method is used to send a request to do garbage collection somewhat prior. When
we send the request to garbage collector, it is not guaranteed that garbage collection will do
the garbage collection process immediately. Garbage collection may do garbage collection.

Wrapper classes

For every primitive type there is a corresponding reference type called as wrapper class
All wrapper classes are final
Wrapper classes are used to convert reference type to primitive type

Consider the following table for wrapper classes


Primitive Data Type
Reference Data Type (Wrapper Class)
byte
Byte
short
Short
char
Character
int
Integer
long
Long
float
Float
double
Double
boolean
Boolean
Examples
String s = "100";
int n = Integer.parseInt(s);
which converts String value 100 into int value
String s = "3.14";
double d = Double.parseDouble(s);
which converts String value 3.14 into double value

53 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 7 - Exception Handling


Types of Errors
In a programming language there are three types of errors which are given below
- Syntax errors or compile time errors
- Semantic errors or logical errors
- Run time Errors or Exceptions
Exception
An exception is a runtime error which occurs during program execution and terminates the
program abnormally.
Consider the following example code
class ExceptionDemo
{
public static void main(String[] args)
{
System.out.println(Begin of the program);
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int result = n1/n2;
System.out.println(Result = +result);
System.out.println(End of the Program);
}
}
When we run the program as given below
>java ExceptionDemo 10 5
Will result to the following output
Begin of the program
Result = 2
End of the program
When we run the program as given below
>java ExceptionDemo 10 0
Will result to the following output
Begin of the program
Exception in thread main java.lang.ArithmeticException :/ Zero
and terminates the program abnormally by throwing an exception by Java Runtime without
executing the remaining part of the program as divide by zero is an exception in Java

54 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Exception Handling
Exception Handling in Java is used to avoid abnormal termination of program. Exception
Handling is used to make the program robust (Strong). When an exception occurs during
runtime, the Java Runtime will throw an exception where this exception is handled using
exception handling and continuous running the remaining part of the program.
In Exception handling, we have five keywords which are given below

try
catch
finally
throw
throws

In the above keywords try, catch, finally are called as blocks where as throw and throws
keywords are called as clauses.
try & catch block
The syntax of try and catch block is given below
try
{
st-1;
st-2;
..
st-n;
}
catch(Exception e)
{
//handle the exception
}
The statements which may throw an exception will be written in try block. When an exception
occurs in try block, the java runtime will throw an exception which is caught by the catch block
and handles this exception in the catch block and remaining part of the program executed
without terminating the program.

55 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Consider the following example program using try and catch block
//ExceptionDemo.java
class ExceptionDemo
{
public static void main(String[] args)
{
System.out.println("Begin of Program");
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
try
{
int result = n1/n2;
System.out.println("Result = "+result);
}
catch(Exception e)
{
System.out.println("Divide by zero not allowed");
}
System.out.println("End of Program");
}
}
When we run the above program as below
>java ExceptionDemo 10 0
will result the output as
Begin of program
Divide by zero not allowed
End of Program

56 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Exception Hierarchy
The following diagram gives the Exception Hierarchy

The top most class in Exception Hierarchy is Throwable.


Categories of Exceptions
There are two categories of Exceptions which are given belo

Checked Exceptions
UnChecked Exceptions

Checked Exceptions
The exceptions which are taken care during compilation by following the specifications are
checked exceptions. Other than RuntimeExceptions like IOException, InterruptedException,
SQLException etc are checked exceptions.
If a method throws an exception, then this method need to be caught(try & catch) or declared
to be thrown (throws)
UnChecked Exceptions
The exceptions which occurs during runtime are not checked during compilation are unchecked
exceptions. All RuntimeExceptions like ArithmeticException,ArrayIndexOutOfBoundsException,
NumberFormatException etc are UnChecked Exceptions.

57 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Consider the following Example Code for RuntimeExceptions


//ExceptionTypesDemo.java
class ExceptionTypesDemo
{
public static void main(String[] args)
{
//ArithmeticException
/*int n = 10/0;*/
//ArrayIndexOutOfBoundsException
/*int[] n = {10,20,30,40,50};
System.out.println(n[8]);*/
//StringIndexOutOfBoundsException
/*String s = "Hello";
System.out.println(s.charAt(8));*/
//NegativeArraySizeException
/*int[] n = new int[-5];*/
//NumberFormatException
/*String s = "xx";
int n = Integer.parseInt(s);*/
//NullPointerException
String s = null;
System.out.println(s.equals("Hello"));
}
}
Explanation of above program
- ArithmeticException
- trying to divide with zero
- ArrayIndexOutOfBoundsException
- trying to access an array out of index
- StringIndexOutOfBoundsException
- trying to access a character from a string which is out of index
- NegativeArraySizeException
- when the array size is negative
- NumberFormatException
- trying to convert a string into number which is not possible
- NullPointerException
- trying to access a member of a class using object when the object is pointing to null

try with multiple catch blocks


try with multiple catch blocks is used to give a proper message to the user based on the
exception type.

58 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Syntax
try
{
st-1;
st-2;
...
st-n;
}
catch(ExceptionType1 e)
{
sts;
}
catch(ExceptionType2 e)
{
sts;
}
..
..
catch(ExceptionTypen e)
{
sts;
}
Note:
In case of try with multiple catch blocks, the order of catch blocks cannot be from super class to
sub class
Consider the following example program for try with multiple catch blocks.
//MultipleCatchDemo.java
class MultipleCatchDemo
{
public static void main(String[] args)
{
try
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int res = n1/n2;
System.out.println("Result = "+res);
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide by zero");
}
59 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Cannot access out of index");
}
catch(NumberFormatException e)
{
System.out.println("Cannot convert String to number");
}
catch(RuntimeException e)
{
System.out.println("Runtime exception");
}
catch(Exception e)
{
System.out.println("Exception Occured");
}
}
}
finally block
finally block is executed irrespective of exception present in try block. Finally block is generally
used to do the clean up operations like closing of files, database connections. If an exception
occurs in try block or not we need to close the connections, these closing operations are
written in finally block
syntax
try
{
sts;
}
catch(Exception e)
{
sts;
}
finally
{
sts;
}
Question: For a try block is catch block mandatory
Answer: No
Reason: For a try block either we can have catch block or finally block or both

60 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

User Defined Exceptions


User Defined Exceptions are also known as Custom Exceptions which are used to give a user
defined name to the exception. User defined exceptions are created by creating a sub class of
Exception.
For Example,
class MyException extends Exception
{
MyException(String s)
{
super(s);
}
MyException(){}
}
Consider the following example program which creates a user defined exception
WithdrawException. WithdrawException is thrown when the user withdraws an amount
which is more than the current balance from the account.
//CustomExceptionDemo.java
class WithdrawException extends Exception
{
WithdrawException(String s)
{
super(s);
}
WithdrawException(){}
}
class Account
{
void withdraw(int amt) throws WithdrawException
{
if (amt > 5000)
throw new WithdrawException("Balance is less");
else
System.out.println("Balance = "+(5000-amt));
}
}
class CustomExceptionDemo
{
public static void main(String[] args)
{
Account a = new Account();

61 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

try
{
a.withdraw(6000);
}catch(WithdrawException e)
{
//System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Methods of Throwable class
- String getMessage() which returns the message for the exception
- String toString() which returns the exception object in String format
- void printStackTrace() which displays the root cause of the exception
Rules for Overriding methods in Exceptions
Consider the following examples for overriding methods in Exceptions
Example 1
class Base
{
void xxx()
{}
}
class Derived extends Base
{
void xxx() throws Exception //Error
{}
}
If a base method is not throwing any exception then overriden method should not throw any
exception

62 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Example 2
class Base
{
void xxx() throws IOException
{}
}
class Derived extends Base
{
void xxx() //valid
{}
void xxx() throws IOException //valid
{}
void xxx() throws EOFException //valid
{}
void xxx() throws Exception //Error
{}
}
If a Base class method throws an exception, then the overridden method may not throw an
exception, may throw an exception which is same as the exception thrown by base class
method, may throw an exception which is sub class to the exception thrown by base class
method. The overridden method should not throw an exception which is super class to the
exception thrown by base class method.

63 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 8 - Multithreading
In multitasking the CPU can share the resource to multiple tasks. A thread is a light weight
process under execution with in a process. Multithreading is used to increase the performance
of an application. In Multithreading the CPU will allocate its time to multiple threads so that
the performance of the application is increased.
Creating Threads in Java
A Thread can be created in Java by the following ways
By creating a class which extends Thread class
(OR)
By creating a class which implements Runnable interface
For example,
Using Thread class
class MyThread extends Thread
{
public void run()
{
//logic goes here
}
}
MyThread t = new MyThread();
t.start();//invokes the run() of MyThread class
Using Runnable interface
class MyThread implements Runnable
{
public void run()
{
//logic goes here
}
}
MyThread t1 = new MyThread();
Thread t = new Thread(t1);
t.start();//invokes run() of MyThread class
When we want to create a thread, the class should override the run() method and we need to
invoke the run() by calling start() method using Thread object. When we call start() of Thread
class, a thread will get created and the CPU will allocate separate time to execute the thread
during running of the application which in turn increases the performance of the application.

64 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Advantages of Runnable interface over Thread class


If a class already extends another class, to create a thread in the class, the class should
implement Runnable interface as java does not support multiple inheritance
Ensures that run() of overridden
State Transition Diagram of a Thread

When the object of the Thread class is created , the state of the thread is New state, we the
thread calls the method start() it creates a thread and the thread will be waiting for the CPU
resource and is ready to run when the CPU becomes free and this state is Runnable state, when
the CPU is free it executes the run() and the thread will be in the state Running state. A thread
goes to blocked state when the thread performs Input Output operations, when sleep() is
invoked on the thread, when wait() is called on the thread. A thread will return back to
Runnable state from Bloked state, after completion of IO operations, when the milli seconds
expire in the sleep() method, when notify() or notifyAll() methods called. A thread goes to Dead
state when the stop() method is invoked.

Methods of Thread class


Following are the methods of Thread class
Thread currentThread()
void setName(String)
String getName()
void setPriority(int)
int getPriority()
void sleep(long)
void start()
void run()
void join()
void yield()
String toString()

65 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Thread priorities
For a thread we can give the priorities between 1 to 10. When a thread has low priority, CPU
will allocate less time to the thread. When a thread has high priority, CPU will allocate more
time to the thread. Following are the priorities which are declared in the Thread class
class Thread implements Runnable
{
public static final int MAX_PRIORITY = 10;
public static final int NORM_PRIORITY = 5;
public static final int MIN_PRIORITY = 1;
public void run(){}
}
When a thread is created, it gives NORM_PRIORITY for a thread.
Consider the following example program which uses Thread class methods
//ThreadDemo.java
//Methods of Thread class
class MyThread extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
System.out.println(t);//Thread[Thread-0,5,main]
t.setName("MyThread");
System.out.println(t);//Thread[MyThread,5,main]
System.out.println(t.getName());//MyThread
t.setPriority(8);
/* If the prority is <1 or >10, it will
throw an exception IllegalArgumentException
*/
System.out.println(t);//Thread[MyThread,8,main]
System.out.println(t.getPriority());//8
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}

66 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Consider the following example program where two threads are executed by CPU
//ThreadDemo2.java
class ThreadX extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
t.setName("ThreadX");
for(int i=1;i<=10;i++)
{
System.out.println(t.getName()+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadY extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
t.setName("ThreadY");
for(int i=10;i>=1;i--)
{
System.out.println(t.getName()+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
ThreadX t1 = new ThreadX();
t1.start();
ThreadY t2 = new ThreadY();
t2.start();
}}
67 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The output of the above program may be as follows


ThreadX:1
ThreadY:10
ThreadX:2
ThreadY:9
ThreadX:3
ThreadY:8

ThreadX:10
ThreadY:1
join()
join() is used in between parent thread and child thread
When join() is invoked on a thread, until the thread completes run(), the other threads
will not use CPU resource
Note:
If start() is invoked multiple times, it will throw an IllegalThreadStateException
If an exception occurs in a thread, it will terminate only the thread, not the program
yield()
When yield() is invoked on a thread, it will a chance to other threads with the same priority. If
there are no threads with the same priority, the current thread will continue using the cpu
resource
Creating Threads using Runnable interface
Consider the following example program to create a thread using Runnable interface
//RunnableDemo.java
class ThreadR implements Runnable
{
public void run()
{
for(int i=1;i<=10;i++)
System.out.println(i);
}
}
public class RunnableDemo {
public static void main(String[] args) {
ThreadR t1 = new ThreadR();
Thread t = new Thread(t1);
t.start();
}
}
68 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

In the above program, the object of ThreadR class is given to the constructor of Thread class, so
that when the start() is invoked by using Thread class object, it executes the overridden run()
defined in ThreadR class.

Synchronization

If two or more threads access the same resource, then there is a getting concurrency
problems
Synchronization is used to avoid concurrency problems
"synchronized" keyword is used for synchronization
synchronized keyword can be used for a method or block of statements

Consider the following diagram where two threads access the same resource.

Inter-thread communication

Interthread communication is done using wait(),notify() and notifyAll() methods


These methods belongs to Object class
These methods need to be used in synchronized context only else it will throw
IllegalMonitorStateException

Example Program
//InterThreadDemo.java
class ThreadSum extends Thread
{
int sum;
public void run()
{
for(int i = 1;i<=100;i++)
sum = sum + i;
69 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

synchronized(this)
{
notify();
}
}
}
public class InterThreadDemo {
public static void main(String[] args) throws InterruptedException {
ThreadSum ts = new ThreadSum();
ts.start();
synchronized(ts)
{
ts.wait();
}
System.out.println("Sum = "+ts.sum);
}
}

Deadlock
When threads are waiting for the resource for longer period of time leads to deadlock
Consider the following diagram,

In the above diagram Thread t1 has kept a lock on recourse R1 and thread t2 has kept a lock on
resource R2. When Thread t1 wants to use resource R2 and thread t2 wants to use resource R1,
but the these resources are not released the locks and these threads will be waiting for the
resources for longer time and this leads to deadlock.

70 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 9 Collection Framework


Collection framework is used to collect the elements of variable size and manage the elements
easily like inserting, deleting, traversing will be simple using collection framework.
Arrays vs Collections
Arrays is a collection of elements of similar type where as Collections are used to collect
the elements of different type
Arrays are fixed size where as Collections are variable size(not fixed)
In Arrays we can store primitive type as well as reference type where as in Collections
we can store only reference type
Collections Hierarchy
The top most interfaces in Collections are Collection and Map
Consider the following Collection Hierarchy diagram.

Following will give the difference between different collection classes and interfaces.
Collection vs Map
Collection is used to collect the elements where as Map is used to collect key-value
pairs
List vs Set
List is ordered where as Set is unordered
List allows duplicates where as Set does not allow duplicates

71 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

ArrayList vs LinkedList
In ArrayList the elements are stored in continuous memory locations where as in
LinkedList the elements are stored in non continuous memory locations
The cost of insert and delete operations is high in case of ArrayList where as the cost of
insert and delete operations is less in case of LinkedList
Stack
Stack is used to collect the elements in the form of Last In First Out(LIFO)
Methods of Stack class
push() - adds an element at the top of the stack
pop() - delete an element from the top of the stack
peek() - retrives the top element from the stack
empty() - returns true if the stack is empty
ArrayList vs Vector
In ArrayList the methods are not synchronized where as in Vector the methods are
synchronized
ArrayList is not thread safe where as Vector is thread safe
HashSet vs LinkedHashSet
HashSet is unordered where as LinkedHashSet is ordered
HashSet vs TreeSet
The elements in HashSet are not sorted where as the elements in TreeSet are sorted
HashMap vs Hashtable
In HashMap the methods are not synchronized where as in Hashtable the methods are
synchronized
HashMap is not thread safe where as Hashtable is thread safe
HashMap vs LinkedHashMap
HashMap is unordered where as LinkedHashMap is ordered based on keys
HashMap vs TreeMap
The elements in HashMap are not sorted where as the elements in TreeMap are sorted
based on keys
Methods of List interface
boolean add(Object o) adds an element at the last
void add(int index,Object o) adds an element at the given position
Object set(int index,Object o) modifies an element at the given position
Object remove(int index) deletes an element at the given position
72 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

boolean remove(Object) deletes an element from the list

Object get(int index) ruturns the element at the given position


int size() returns the size (no of elements) of the list

Consider the example program which uses these methods using ArrayList class
//ArrayListDemo.java
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);//al.add(new Integer(10));//prior to Java 5
al.add(20);
al.add("xxx");
al.add("yyy");
System.out.println(al);//[10,20,xxx,yyy]
al.add(2,"ppp");
System.out.println(al);//[10,20,ppp,xxx,yyy]
al.set(2,"qqq");
System.out.println(al);//[10,20,qqq,xxx,yyy]
al.remove(2);
System.out.println(al);//[10,20,xxx,yyy]
al.remove("xxx");
System.out.println(al);//[10,20,yyy]
String s = (String)al.get(2);
System.out.println(s);//yyy
System.out.println("Size = "+al.size());//Size = 3
}
}
Additional methods in LinkedList class

addFirst()
addLast()
removeFirst()
removeLast()

Iterator interface
Iterator interface is used to traverse the elements of list or set from first to last

73 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Methods of Iterator interface


boolean hasNext()
Object next()
ListIterator
ListIterator interface extends Iterator interface
ListIterator is used to traverse the elements of list or set from first to last as well as last
to first
Methods of ListIterator
boolean hasPrevious()
Object previous()
Example program using Iterator and ListIterator interfaces to traverse the list
//IteratorDemo.java
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(10);
ll.add(20);
ll.add("xxx");
ll.add("yyy");
System.out.println(ll);//[10,20,xxx,yyy]
Iterator iter = ll.iterator();
while(iter.hasNext())
System.out.println(iter.next());
ListIterator listIter = ll.listIterator();
while(listIter.hasNext())
System.out.println(listIter.next());
while(listIter.hasPrevious())
System.out.println(listIter.previous());
}
}
Using Generics in collections
In a collection we can collect the elements of different types. In order to collect the elements of
similar type into the collection we can make of use of generics, which are added in Java 5
version, in the collections. Using generics in collection, the traversing of list or set can be done
using enhanced for loop added in Java version5

74 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Example Program
//UsingGenericsDemo.java
import java.util.*;
public class UsingGenericsDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("xxx");
al.add("yyy");
al.add("zzz");
for(String s : al)
System.out.println(s);
for(int i=al.size()-1;i>=0;i--)
System.out.println(al.get(i));
}
}
Set interface
Set interface is used to collect the elements. In Set the elements are unordered and duplicates
are not allowed.
Example Program
//SetDemo.java
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
//HashSet
HashSet hs = new HashSet();
hs.add("c");
hs.add("a");
hs.add("e");
hs.add("b");
hs.add("d");
hs.add("a");//not an error - will not be added into the set
System.out.println(hs);//[d,e,b,c,a]
//LinkedHashSet
LinkedHashSet lhs = new LinkedHashSet();
lhs.add("c");
lhs.add("a");
lhs.add("e");
lhs.add("b");
lhs.add("d");
System.out.println(lhs);//[c,a,e,b,d]

75 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

//TreeSet
TreeSet ts = new TreeSet();
ts.add("c");
ts.add("a");
ts.add("e");
ts.add("b");
ts.add("d");
System.out.println(ts);//[a,b,c,d,e]
}
}
When we add elements into TreeSet, it will arrange the elements in the form of tree using
binary search tree
The arrangement of elements is shown below in the diagram.

Once the elements are arranged in TreeSet, the elements are traversed using inorder traversal
which traverses the elements in ascending order.
Comparator interface
Comparator interface is used to add the elements into TreeSet by comparing the elements
Methods
int compare(Object,Object)
The TreeSet class implements the Comparator interface and overrides the method compare().

76 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The default compare() method present in TreeSet will return the elements in ascending order.
To display the elements in descending order we need to create our own Comparator which
implements Comparator interface and override the method compare() method. The TreeSet
object will refer to our Comparator object in the constructor so that it executes the code in the
overridden compare().
Consider the following example program using Comparator interface.
//ComparatorDemo.java
import java.util.*;
public class ComparatorDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet(new MyComparator());
ts.add(5);
ts.add(8);
ts.add(6);
ts.add(4);
ts.add(7);
//ts.add("xx");//ClassCastException
/* In TreeSet all the elements should be of same type else it will throw
ClassCastException */
System.out.println(ts);//[4,5,6,7,8]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
if (i1 < i2)
return +1; //connect towards left
else
if (i1 > i2)
return -1;//connect towards right
else
return 0;//no change
}
}

77 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Stack class
Stack is a collection of elements in the form of Last In First Out (LIFO) operations.
The operations which are performed at the top of the Stack are
push inserts an element at the top of the stack.
Pop deletes an element from the top of the stack
Peek returns the element from the top of the stack
Methods
boolean empty()
Object push(Object o)
Object pop()
Object peek()
Example program
//StackDemo.java
import java.util.*;
public class StackDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack st = new Stack();
int ele,ch;
while(true)
{
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Peek");
System.out.println("4.Display");
System.out.println("5.Exit");
System.out.println("Enter Choice");
ch = in.nextInt();
switch(ch)
{
case 1:System.out.println("Enter element");
ele = in.nextInt();
st.push(ele);break;
case 2:if (st.empty())
System.out.println("Stack Underflow");
else
{
ele = (int)st.pop();
System.out.println("Poped Element "+ele);
} break;

78 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

case 3:if (st.empty())


System.out.println("Stack is empty");
else
{
ele = (int)st.peek();
System.out.println("Peeked element "+ele);
}
break;
case 4: System.out.println(st);break;
case 5:System.exit(1);
}
}
}
}

Vector class
Vector is a collection of elements which are ordered. The methods present in Vector class are
synchronized.
The following example programs create a Vector and traverses the elements of the Vector using
Enumeration interface (legacy interface).
//VectorDemo.java
import java.util.*;
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add("xxx");
v.add("yyy");
System.out.println(v);//[10,20,xxx,yyy]
Enumeration e = v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Map interface
Map interface is used to collect the elements in the form of key-value pairs. Map is unordered
and Map does not allow duplicates.
Consider the following example program for Map
//MapDemo.java
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
79 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

//HashMap
HashMap hm = new HashMap();
hm.put("monitor",5000);
hm.put("keyboard",300);
hm.put("mouse",250);
hm.put("ups",2000);
hm.put("speakers",1000);
System.out.println(hm);
//LinkedHashMap
LinkedHashMap lhm = new LinkedHashMap();
lhm.put("monitor",5000);
lhm.put("keyboard",300);
lhm.put("mouse",250);
lhm.put("ups",2000);
lhm.put("speakers",1000);
System.out.println(lhm);
//TreeMap
TreeMap tm = new TreeMap();
tm.put("monitor",5000);
tm.put("keyboard",300);
tm.put("mouse",250);
tm.put("ups",2000);
tm.put("speakers",1000);
System.out.println(tm);
}
}
/*
output
{mouse=250, keyboard=300, monitor=5000, speakers=1000, ups=2000}
{monitor=5000, keyboard=300, mouse=250, ups=2000, speakers=1000}
{keyboard=300, monitor=5000, mouse=250, speakers=1000, ups=2000}
*/
Iterating Maps
To traverse Maps convert Map into Set by using entrySet() method then apply the Iterator
interface on the Set.
The following program is used to iterate Maps
//IterateMapDemo.java
import java.util.*;
public class IterateMapDemo {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("monitor",5000);
hm.put("keyboard",300);
80 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

hm.put("mouse",250);
hm.put("ups",2000);
hm.put("speakers",1000);
System.out.println(hm);
Set s = hm.entrySet();//used to convert Map into Set
Iterator iter = s.iterator();
while(iter.hasNext())
{
Map.Entry me = (Map.Entry)iter.next();
System.out.println(me.getKey()+":"+me.getValue());
}
}
}
/*
output
{mouse=250, keyboard=300, monitor=5000, speakers=1000, ups=2000}
mouse:250
keyboard:300
monitor:5000
speakers:1000
ups:2000
*/

81 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 10 IO Package
I/O Basics
Java I/O has come up with simple facilities that include standardized API for reading and
writing character and byte data from various data sources. This chapter will reflect the
inside out of java.io package, scrutinizing I/O classes, methods, and various techniques for
handling I/O in your Java code.
Streams

Java I/O is based on the concept of streams. A stream is defined as a flowing sequence of
characters. Most of the programs work with external data stored either in local files or they
come from other computers on the network. Javas concept allows it to work with the
streams of data. When the physical data storage is mapped to a logical stream of data, a
Java program reads data serially from this stream. The term serially here means byte after
byte and character after character. Some of the types of streams are byte streams
(InputStream, OutputStream) and character streams (Reader and Writer). There are
different types of data, and hence different types of streams. You can see the flow of data in
Fig. 1.

Fig. 1: Flow of Data


You need to know the following steps to work with a stream:

Open a stream pointing a specific data source: a file, a socket, URL, etc.

Then read or write data from/to this stream.

Close the stream.

82 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

When sending a stream of data it is said that we are writing a stream. When receiving a
stream of data we are said to be reading a stream. If an error occurs when reading or
writing a stream, an exception (usually IOException) is thrown. This kind of exception can
be handled by surrounding your stream statements with a try - catch block.
Predefined Stream Objects
Three streams are made available to the programmer by the System class, i.e.
System.out - standard output stream
System.in - standard input stream
System.err - standard error stream
The following example accepts a character from the user and prints it back in the prompt.
import java.io.*;
public class InOutDemo
{
public static void main(String s[]) throws IOException
{
System.out.println((char)System.in.read());
}
}

In the above example you can see that the data read by System.in.read is casted into char,
because read() method returns a byte. The input and output stream read and write bytes
respectively. This means readers can read and writers can write characters.

83 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Classes Hierarchy of java.io package

Fig. 2: java.io hierarchy of classes


Basic input and output classes
The java.io package includes a large number of classes dealing with all input and output
operations. These classes consist of:

Byte streams (subclasses of InputStream or OutputStream).

Character streams (subclasses of Reader and Writer).

Byte Streams
A program can use any one of the subclass of the InputStream or OutputStream, if there is
necessity of reading or writing program respectively. InputStream and OutputStream
define the lowest level interface for all byte streams because they are abstract classes.
These streams contain methods that help in reading or writing an unstructured flow of
byte-level data. But being abstract classes, generic input or output stream cannot be
generated. Their subclasses are implemented by Java for activities such as reading from
and writing to files and communicating with sockets.
84 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Character Streams
Streams, handling only character data are actually introduced by java.io Reader and Writer
character stream classes. While using these classes any programmer can think it only in
terms of characters and string data that allows the underlying implementation to handle
the conversion of bytes to a specific character encoding. The character streams main
advantage is that they make it easy to write programs that do not depend upon a specific
character encoding. Hence, they are easy to internationalize. Unicode is an international
standard character encoding that has the capability to represent most of the world's
written languages. Java stores strings in this Unicode. The second main advantage of
character streams is their efficiency.
Streams
InputStream Class
The java.io.InputStream class fall under abstract superclass for all input streams. When
there is need to read bytes of data from a stream, it declares three basic methods.
Moreover, it has methods to close and flush streams, to check the number of bytes of data
available to be read, to skip over input, to mark a position in a stream and reset back to that
position and also to determine whether marking and resetting back are supported. The
following list provides the details of some important methods in the InputStream class.
public abstract int read() throws IOException
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length) throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close() throws IOException
Output Streams
OutputStream Class
There are three basic methods declared by java.io.OutputStream class to write bytes of data
onto a stream. It also has methods for closing and flushing streams. OutputStream is an
abstract class. Their subclass provides the abstract write(int b) method implementations. It
may be possible that four nonabstract methods are overridden. The following example of
the FileOutputStream class overrides all five methods with original methods knowing how
to write bytes into files on the host platform.
public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException

85 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

public void write(byte[] data, int offset, int length) throws IOException
public void flush() throws IOException
public void close() throws IOException
The File Class

When we construct a File object, it represents that a physical file or directory on the disk.
When we call its methods, we manipulate the underlying disk file.
The methods for File objects are:

Constructors

Test methods

Action methods

List methods

Constructors
There are several constructors in the File class ther allow Java code to specify the initial
values of an object. Constructors for the File class are:
File(String filename)
File(String pathname, String filename)
File(File directory, String filename)
Test Methods
Public methods in the File class perform tests on the specified file. For example:

The exists() method asks if the file actually exists.

The canRead() method asks if the file is readable.

The canWrite() method asks if the file can be written to.

The isFile() method asks if it is a file (as opposed to a directory).

The isDirectory() method asks if it is a directory.

The isHidden() method asks if a file or directory object is Hidden

These methods are all of the boolean type and that is why they return a true or false.
Action methods
Public instance methods in the File class perform actions on the specified file. Let's take a
look at them:

86 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The renameTo() method renames a file or directory.

The delete() method deletes a file or directory.

The mkdir() method creates a directory specified by a File object.

The mkdirs() method creates a list of directory in nested format.

The return type of all above methods is boolean to indicate whether the action was
successful.
The following example demonstrates several methods of file class :
Example of File .class:
import java.io.*;
public class FileDemo1
{
public static void main(String []s) throws IOException
{
File f=new File("C:/raj.txt");
if(f.exists())
{
System.out.println("raj.txt exists");
}else
{
System.out.println("The new file getting created");
f.createNewFile();
//f.mkdir() can be used to create a directory
}
System.out.println("Is it a File
? : " + f.isFile());
System.out.println("Is it a Directory ? : " + f.isDirectory());
System.out.println("Is it Hidden
? : " + f.isHidden());
System.out.println("Is it Readable ? : " + f.canRead());
System.out.println("Its length is ? : " + f.length());
if(f.length()==0)
{
System.out.println("Deleting the file now");
f.delete();
}
}
}

The following example demonstrates the use of listFiles() method along with recursion
principle to extract the list of files and directory names under the C:/WINDOWS directory.

87 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

import java.io.*;
public class ListFileDemo
{
static int filecount=0;
static int foldercount=0;
public static void main(String []s) throws IOException
{
File f=new File("C:/WINDOWS");
recursion(f);
System.out.println("Total files is : " + filecount);
System.out.println("Total directory is : " + foldercount);
}
static void recursion(File ff)
{
File [] arr=ff.listFiles();
String name;
for(int x=0;x<arr.length;x++)
{
File f1=arr[x];
name=f1.getName();
if(f1.isFile())
{
System.out.println(name);
filecount++;
}
else
{
System.out.println("[ " + name + " ] ");
foldercount++;
recursion(f1); // recursion call
}
}
}
}

The RandomAccessFile Class


The java.io.RandomAccessFile class is another way to read or modify files. The constructors
for the class are as follows:
RandomAccessFile(String file, String mode)
RandomAccessFile(File file, String mode)
The mode string should be either r or rw. You can take r to open the file, only for
reading and take rw to open the file for both reading and writing. In addition to that, you
can see that seek( ) is used to move about in the file and change one of the values. The
following example prints its own source code on the prompt:

88 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Example:
import java.io.*;
public class RandomAccessDemo
{
public static void main(String []s) throws IOException
{
RandomAccessFile f=new RandomAccessFile("C:/RandomAccessDemo.java","r");
String str="";
while(str!=null)
{
try
{
System.out.println(str=f.readLine());
}
catch(Exception e)
{
System.exit(0);
}
}
}
}
File Streams

Most of the examples in this chapter have used the streams System.in and System.out.
These are convenient for examples, but in real life, you will more commonly attach streams
to data sources like files and network connections. You will use the java.io.FileInputStream
and java.io.FileOutputStream classes, which are concrete subclasses of InputStream and
OutputStream, to read and write files.
Reading Files:
FileInputStream is a pure subclass of InputStream that provides an input stream connected
to a particular file.
public class FileInputStream extends InputStream
FileInputStream has all the usual methods of input streams, such as read(), available(),
skip(), and close().These are used exactly as they are for any other input stream. There are
three FileInputStream() constructors:
public FileInputStream(String fileName) throws IOException
public FileInputStream(File file) throws FileNotFoundException
public FileInputStream(FileDescriptor fd)

89 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The following program reads Sample.txt file and prints it back.


import java.io.*;
public class ReadBytes
{
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C:/Sample.txt");
int n;
while ((n = fis.available()) > 0) {
byte[] b = new byte[n];
int result = fis.read(b);
if (result == -1) break;
String s = new String(b);
System.out.print(s);
} // End while
} // End try
catch (IOException e)
{
System.err.println(e);
}
System.out.println();
}
}

Writing Files :
The FileOutputStream class is a concrete subclass of OutputStream that provides output
streams connected to files.
public class FileOutputStream extends OutputStream
This class has all the usual methods of output streams, such as write(), flush(), and
close().They are used exactly as they are for any other output stream. There are three main
FileOutputStream() constructors:
public FileOutputStream(String filename) throws IOException
public FileOutputStream(File file) throws IOException
public FileOutputStream(FileDescriptor fd)

The following program creates a file called Sample.txt and writes a string into the file.
import java.io.*;
public class WriteBytes
{
public static void main(String[] args) {
try
{
File f=new File("C:/Sample.txt");
FileOutputStream fos = new FileOutputStream(f);

90 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

String str="HAPPY B DAY TO U";


byte []b=str.getBytes();
for(int n=0;n<b.length;n++)
{
fos.write(b[n]);
}
}
catch (IOException e)
{
System.err.println(e);
System.out.println();
}
}
}

Character Streams
Reader class
You know that Readers are character based input streams that can read Unicode
characters.
The read() method reads a single character and also returns a character that can be read
as an integer in the range from 0 to 65535 or it can be -1 if the end of the stream is reached.
The abstract read() method reads characters into a portion of an array that starts at the
offset up to length number of characters. It returns the number of characters read or 1
only if the end of the stream is reached.
Character input streams
Java.io package has different character input streams. They are:
If you look at the different character input streams in the java.io package, they are

Strings

Character arrays

Pipes

As InputStreamReader is a character input stream, it uses a byte input stream as its data
source, converting it into Unicode characters. LineNumberReader is a character input
stream and a subclass of BufferedReader that tracks the number of lines of text that have
been read from it. PushbackReader, is a character input stream and a subclass of
FilterReader, that uses another input stream as its input source. It also adds the ability to
push characters back onto the stream.

91 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The following example used the InputStreamReader to read its source file.
import java.io.*;
public class IsrDemo{
public static void main(String argv[]){
try{
FileInputStream in = new FileInputStream("c:/IsrDemo.java");
InputStreamReader isr = new InputStreamReader(in);
int ch=0;
while((ch = in.read())> -1){
StringBuffer buf = new StringBuffer();
buf.append((char)ch);
System.out.print(buf.toString());
}
} catch (IOException e){System.out.println(e.getMessage());}
}
}

Writer class:
The writer class consists of character based output streams called writers that can write
character bytes and turn Unicode into bytes. The methods that includes these methods are
as follows:

The void write() method They take a character and writes single character in 16 loworder bits.

The abstract void write() method They take a character array and writes a portion of
an array of characters

Character output streams


In the java.io package, you will find many character output streams. There you can view
branches of this inheritance tree. It has not only Readers, but also other important
branches available.
The Writer output having Sinks can be:
Strings
CharArray
Pipes

The destination for the data in OutputStreamWriter is used with the help of byte output
stream. Buffering is employed by BufferedWriter to a character output stream. Therefore, it
enhances the efficiency of the output by combining many small write requests into a single
large request. An abstract class FilterWriter functions as a superclass for character output
streams. The stream helps in filtering the data written to them before writing it to some
other character output stream.
PrintWriter is a character output stream having print() and println()methods. These
methods give textual representations of primitive values and objects as output.

92 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

InputStreamReader
InputStreamReader, which is discussed earlier, reads bytes from an InputStream and
converts them to characters. An InputStreamReader uses the default character encoding
for the bytes, which is usually ASCII. If the bytes that are being read are ASCII bytes, only a
single byte at a time is used to form a character. If the bytes are not ASCII, such as Chinese
or another language, you want its conversion to Unicode as well. Specific encoding of the
byte stream is necessary, and the InputStreamReader converts it to Unicode. With an
alternate constructor, you can specify the encoding of the bytes on the InputStream.
OutputStreamReader
OutputStreamWriter is similar to InputStreamReader. The output characters, which are in
Unicode, are converted to the underlying format of the machine using an
OutputStreamWriter. The converted characters are written to an OutputStream. The
underlying default format is typically ASCII. However, you can state a specific encoding
scheme with an alternate constructor.
Buffering
Buffering is used to increase the performance of write and read operations.
How Buffering works:
Buffered input streams as shown in Fig.5,read more data than they initially need into a
buffer (an internal array of bytes). When one of the stream's read( ) methods is invoked,
data is removed from the buffer rather than from the underlying stream. When the buffer
runs out of data, the buffered stream refills its buffer from the underlying stream. Likewise,
buffered output streams store data in an internal byte array until the buffer is full or the
stream is flushed; then the data is written out to the underlying output stream in one
swoop. In situations where it is almost as fast to read or write several hundred bytes from
the underlying stream, as it is to read or write a single byte, a buffered stream can provide
a significant performance boost.

Fig. 5: Buffering of Streams


A program can convert an unbuffered stream into a buffered stream using the wrapping,
where the unbuffered stream object is passed to the constructor for a buffered stream
class, for example,

93 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

inputStream = new BufferedReader(new FileReader("xanadu.txt"));


outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
This section introduces buffering and covers the following topics:

BufferedInputStream and BufferedOutputStream

BufferedReader and BufferedWriter

New-line characters

Buffering input and output streams

BufferedInputStream
Our BufferedInputStream is going to put a buffer onto an InputStream that is specified in
the constructor. The actual data source is what you pass it as an InputStream. The
BufferedInputStream reads large chunks of data from the InputStream. Then you read
individual bytes or small chunks of bytes from the BufferedInputStream. The default buffer
size is 512 bytes, but there's a constructor that allows you to specify the buffer size if you
want something different.
To improve your efficiency, you read from the object of BufferedInputStream instead of
reading directly from the underlying InputStream. And you will not have to go back to the
operating system to read individual bytes. See Fig. 6:

Fig. 6: Buffering
Here is an example of using the BufferedInputStream, note how similar it is with the
previous example when InputStreamReader is replaced by BufferedInputStream:
import java.io.*;
public class BufIn{
public static void main(String argv[]){
try{
FileInputStream fin = new FileInputStream("c:\BufIn.java");
BufferedInputStream bin = new BufferedInputStream(fin);
int ch=0;

94 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

while((ch=bin.read())> -1){
StringBuffer buf = new StringBuffer();
buf.append((char)ch);
System.out.print(buf.toString());
}
}catch(IOException e){System.out.println(e.getMessage());};
}
}

BufferedOutputStream
BufferedOutputStream extends FilterOutputStream. When you apply it to an OutputStream,
you have a buffered output stream. Instead of going to the operating system for every byte
you write, you have the intermediary that provides a buffer and you write to that. When
that buffer is full, it is written all at once to the operating system. And it is written
automatically if the buffer gets full, if the stream is full, or if the flush() method is used. The
flush() method forces any output buffered by the stream to be written to its destination. So
for creating a BufferedOutputStream, you have to specify:
The output stream you are going to use.
The buffer size if you don't like the default.

Fig. 7: BufferedOutputStream
BufferedReader and BufferedWriter
A BufferedReader and a BufferedWriter act like BufferedOutputStream and
BufferedInputStream, except they deal with reading and writing characters. For a
BufferedReader, you specify an underlying Reader and optionally a buffer size. For a
BufferedWriter, you specify an underlying Writer and optionally a buffer size.
BufferedReader has one additional method, called readLine(), which allows us to simply
read an entire line of characters from the underlying Reader.
Serialization
Serialization of a class is enabled by the class implementing the java.io.Serializable
interface. Classes that do not implement this interface will not have any of their state
serialized or deserialized. All subtypes of a serializable class are themselves serializable.
95 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The serialization interface has no methods or fields and serves only to identify the
semantics of being serializable. There are a couple of other features of a serializable class.
First, it has to have a zero parameter constructor. When you read the object, it needs to be
able to construct and allocate memory for an object, and it is going to fill in that memory
from what it has read from the serial stream. The static fields, or class attributes, are not
saved because they are not part of an object. If you do not want a data attribute to be
serialized, you can make it transient.
An Example of a serialized class is provided below:
import java.io.*;
public class Student implements Serializable
{
int roll;
String name;
transient String phone;
}

The ObjectOutputStream class


An ObjectOutputStream writes primitive data types and graphs of Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams. The default serialization mechanism for an object writes the class of the object, the
class signature, and the values of all non-transient and non-static fields. References to other
objects (except in transient or static fields) cause those objects to be written also. Multiple
references to a single object are encoded using a reference sharing mechanism so that
graphs of objects can be restored to the same shape as when the original was written.
For example to write an object of the student class into a file that can be read by the
example in ObjectInputStream:
import java.io.*;
public class ObjectWriter
{
public static void main(String []s) throws Exception
{
Student st=new Student();
st.roll=12;
st.name="Raj";
st.phone="23467549";
File f=new File("C:/Demo.txt");
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(st);
}
}

96 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

ObjectInputStream:
An ObjectInputStream deserializes primitive data and objects previously written using an
ObjectOutputStream. The method readObject is used to read an object from the stream.
Java's safe casting should be used to get the desired type. In Java, strings and arrays are
objects and are treated as objects during serialization. When read they need to be cast to
the expected type.
Sample code for reading the object stored in the previous example:
import java.io.*;
public class ObjectReader
{
public static void main(String []s) throws Exception
{
File f=new File("C:/Demo.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream oos = new ObjectInputStream(fis);
Object ob=oos.readObject();
Student st=(Student)ob;
System.out.println("The roll is " + st.roll);
System.out.println("The name is " + st.name);
System.out.println("The phone number is " + st.phone);//transient member
}
}

Externalizable
Externalizable interface are implemented by a class to give the class complete control over
the format and contents of the stream for an object and its supertypes. These methods
must explicitly coordinate with the supertype to save its state. These methods supercede
customized implementations of writeObject and readObject methods.

97 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Chapter 11 JDBC
Introduction to JDBC
In simple language JDBC means the connectivity mechanism to connect a database through
a java program. The Java Database Connectivity (JDBC) API provides universal data access
from the Java applications to the backend database. You can use the JDBC API, to access any
data source, from relational databases to spreadsheets to flat files. The JDBC technology
also provides a common base on which alternate interfaces and tools can be built.

SQL - Structured Query Language


SQL is a standardized language, which is used to create, manipulate, manage and examine
any relational databases.
Once you learn SQL, you can migrate from one database to another as the SQL is going to
be the same for almost all relational databases.
The purpose of this section of the chapter is to provide the basics of the Structured Query
Language. Some basic points about SQL:

is a Structured Query Language

allows access to a database

is an ANSI standard computer language

can make simple queries to any database

can retrieve the data from database as a result of query

can insert new rows, update existing rows and delete the non-required
rows from tables

can make new tables and other database objects

is portable, so moving from one database to another with little


modification is possible

Is easy to learn

The same way let us understand related terms of database.

A database is essentially a smart container for tables.

A table is a container comprised of many rows.

A row is a container comprised of columns.

A column is a single data item having a name, type, and value.

98 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Database Drivers
Database drivers are software programs that establish a connection between a client
application and a database. The drivers convert the query made by the application into the
database specific calls and thereby establishing communication. Drivers send SQL
statements generated by the client application to a database server and receive result and
other responses from the server. There are several types of drivers available. Some of them
are discussed below.
ODBC and JDBC drivers
Many database servers use vendor specific protocols. In other words, the programmer has
to learn a new language each time, to talk to a different database. Microsoft solved the
problem by providing a common standard for communicating with databases, called Open
Database Connectivity (ODBC).
(See Fig. 1 a database client connected to many databases)
Java applications and applets use JDBC drivers to communicate with database servers.
Java application

JDBC Driver Manager

JDBC/ODBC
Bridge

JDBC DRIVERS

ODBC driver

Vendorsupplied JDBC
driver

Database

Database

Fig. 1: A database client connected to many database servers

JDBC provides a common database programming API for Java programs. JDBC drivers do
not communicate with the databases directly, instead many JDBC drivers communicate
with databases using ODBC.
However, JDBC is a better solution. Java applications and applets use JDBC due to the
following reasons:

99 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

ODBC is a C language API, not a Java language API. Java is object-oriented and C is not. C uses
pointers that Java does not support.
ODBC drivers must be installed on each client machines, and means that an applets access to a
database would be constrained by the requirement to download and install a JDBC driver.
As ODBC is developed in C, it is not portable across different hardware platform.

See Fig. 2 - JDBC Driver in Client Server application.

See Fig. 2 - JDBC Driver in Client Server application.


Types of JDBC drivers
Ever since the release of JDBC API, a number of JDBC drivers have been developed. These
drivers provide varying levels of capability. JDBC drivers into the following types:
Type1. JDBC-ODBC Bridge plus ODBC Driver
This is a combination of the JDBC-ODBC bridge and an ODBC driver. This driver translates
JDBC calls to ODBC calls and relies on an ODBC driver to communicate with the database.
This driver is included with the JDK. However this driver requires deployment and proper
configuration of an ODBC driver. The bridge is handy for testing, but it is not recommended
for production use. It is a cumbersome solution for both Internet and Intranet because it
needs both the drivers to be installed on the users machine. A block diagram of JDBC-ODBC
bridge is shown in Fig. 3.

100 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Database
Server (A)
Java
Database
Client

JDBC_
ODBC
bridge

Database
Server (B)
Database
Server (C)

Fig. 3: Access to a database by JDBC-ODBC bridge


Type 2. Native API Partly Java Driver
This type of drivers is partly written in Java and partly in the native code. This driver
category consists of drivers that communicate with databases servers in the servers native
protocol. For example, as shown in Fig. 4, an Oracle driver would use the SQL*Net protocol.
Similarly a DB2 driver would use an IBM database protocol. These drivers are implemented
in a combination of binary code and Java, and they must be installed on each client
machines. The only benefit is that its installation is easier than installing both the JDBCODBC bridge and an ODBC driver.

Java
Database
Client

Type2 JDBC
Driver (Java
& Binary
Code)

Database
Server
Vender Specific
protocol

Fig. 4: Access to a database by Native-API pure Java driver


Type 3. JDBC -Net pure Java Driver
The pure Java drivers communicate with a database access server using HTTP or SHTTP
protocol. This is an ideal solution for both Internet and Intranet. The database server then
translates the network protocol into a vendor specific database protocol. Pure Java drivers
that are served from the web server are the best solution for the applets. The Java drivers
are automatically installed on the users machine in a transparent manner. A block diagram
of type three drivers is shown in Fig. 5.

101 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Database
Server (A)
Database
Client

http

Vendor Specific

Database
access
Server

Protocols

Database
Server (B)
Database
Server (C)

Fig. 5: Access to a database by JDBC-Net pure Java driver


Type 4. Native-Protocol Pure Java Driver
It is a pure Java library that translates JDBC calls directly to a database-specific protocol.
The JDBC driver uses a database vender-specific protocol. This approach is efficient for
Intranet applications but suffers from the drawback that the vendors protocol may not be
supported by a firewall. Fig. 6 shows the type four driver.

Type4
JDBC
Driver
(PureJava)

Java
Database
Client

Vender Specific
protocol

Database
Server

Fig. 6: Access to a database by JDBC-Net pure Java driver

Steps to Connect to a DataBase from a Java Program


1. import java.sql.*;
2. Load the driver
Type1: Class.forName("sun.jdbc.odbc.driver.JdbcOdbcDriver");
Type4: Class.forName("oracle.jdbc.driver.OracleDriver");
3. Establish the connection
Type1:
Connection con = DriverManager.getConnection("jdbc:odbc:dsn",
"username","password");
102 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Type4:
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"username","password");
1521 : port no where oracle instance is running
orcl : SID (System Identification) for Express Edition :XE

4. Create the statement


Statement

- createStatement()

PreparedStatement - prepareStatement()
CallableStatement - prepareCall()
eg:
Statement st1 = con.createStatement();
PreparedStatement st2 = con.prepareStatement("select * from books");
CallableStatement st3 = con.prepareCall("{call ...}");
CallableStatement is used to call functions and procedures of PL/SQL
Statement vs PreparedStatement

If the same SQL command is executed multiple times in the program, then it is
suggested to use PreparedStatement
PreparedStatement is dynamic

5. Execute the statement


To execute the SQL statement the following methods are used

boolean execute()
- CREATE,DROP,ALTER,TRUNCATE (DDL)
int executeUpdate()
- INSERT,UPDATE,DELETE (DML)
ResultSet executeQuery() - SELECT (DQL)

Note: Any SQL command is executed by using above methods but to manage the return
type we need to use the respective methods
eg:
st1.executeQuery("select * from books");
st2.executeQuery();

103 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

6. Close the statement


eg:
st1.close();
st2.close();

7. Close the connection


con.close();
Type 1 driver : JDBC ODBC Bridge Driver
In order to use Type 1 driver to connect to Oracle we need to create DSN which refers to
the Oracle Data base driver.
Steps to create DSN in Control Panel
Open Control Panel -> System and Security -> Administrative Tools->
Data Sources (ODBC) -> Click on Add -> Select the driver "Microsoft ODBC for Oracle" and
click Finish
Data Source Name :java1
Username : scott
Server : orcl (for express edition : XE)
Click Ok
In Win7/Win8 (64-Bit)
Open C:\Windows\SysWOW64\odbcad32.exe file and continue the steps from "Click on
Add" from above steps
Example program to connect to Data base using Type 1 Driver
//JdbcType1Demo.java
import java.sql.*;
public class JdbcType1Demo {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:java1","scott","tiger");
System.out.println("Connected");
con.close();
}catch(Exception e)

104 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

{
System.out.println(e);
}
}
}

JDBC Type 4 driver example program


//JdbcType4Demo.java
import java.sql.*;
public class JdbcType4Demo {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
System.out.println("Connected");
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

/*
To use Type 4 for oracle, set the classpath to ojdbc14.jar as follows
Right Click on Project (MyProj1) ->Build Path->Configure Build Path ->Click on the tab
Libraries ->
Click on Add External jars -> Select the file ojdbc14.jar from your folder and click Open >Click Ok
*/
Statement interface Example
//JdbcStatementDemo
import java.sql.*;
public class JdbcStatementDemo {
public static void main(String[] args) throws SQLException{
Statement st = null;
Connection con = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");

105 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
st = con.createStatement();
/*st.execute("create table Student (rollno number(3),sname varchar(10),marks
number(3))");
System.out.println("Table Created");*/
/*st.executeUpdate("insert into student values (111,'xxx',200)");
st.executeUpdate("insert into student values (222,'yyy',400)");
st.executeUpdate("insert into student values (333,'zzz',300)");
System.out.println("Inserted");*/
/*int n = st.executeUpdate("update student set marks=500");
System.out.println(n+" records updated");*/
ResultSet rs = st.executeQuery("select * from student");
while(rs.next())
{
System.out.print(rs.getInt("rollno")+" ");
System.out.print(rs.getString("sname")+" ");
System.out.println(rs.getInt(3));// 3 indicates column no which is marks
}
}catch(Exception e)
{
System.out.println(e);
}
finally
{
st.close();
con.close();
}
}
}
PreparedStatement interface example program
//JdbcPreparedStatementDemo.java
import java.sql.*;
import java.util.*;
public class JdbcPreparedStatementDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Roll No");
int rollno = in.nextInt();
System.out.println("Enter Name");
String sname = in.next();
System.out.println("Enter Marks ");
int marks = in.nextInt();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");

106 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",


"scott","tiger");
/*PreparedStatement st = con.prepareStatement("insert into student values (?,?,?)");
st.setInt(1,rollno);
st.setString(2,sname);
st.setInt(3,marks);*/
PreparedStatement st =
con.prepareStatement("insert into student values("+rollno+",'"+sname+"',"+marks+")");
st.executeUpdate();
System.out.println("Inserted");
st.close();
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

CallableStatement interface
CallableStatement interface is used to call functions and procedures of pl/sql
Function vs procedure
A function can return only one value using return statement where as a procedure can
return multiple values using out parameters.
Creating a Function in PL/SQL
create or replace function f_get_price(pbno number )return number is
lprice number;
begin
select price into lprice from books where bno = pbno;
return lprice;
end;
/

107 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Creating a Procedure in PL/SQL


create or replace procedure getPrice(pbno IN number, pprice OUT number)
is
begin
select price into pprice from books where bno=pbno;
end;
/
The following program is used to call the above function in PL/SQL
//JdbcCallableStatementDemo1.java
//to call function
import java.sql.*;
public class JdbcCallableStatementDemo1 {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
CallableStatement st = con.prepareCall("{call ? := f_get_price(?)}");
st.registerOutParameter(1,Types.INTEGER);
st.setInt(2,111);
st.execute();
int price = st.getInt(1);
System.out.println("price ="+price);
st.close();
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

108 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

The following program is used to call the above procedure in PL/SQL


//JdbcCallableStatementDemo2.java
//to call procedure
import java.sql.*;
public class JdbcCallableStatementDemo2 {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
CallableStatement st = con.prepareCall("{call getPrice(?,?)}");
st.registerOutParameter(2,Types.INTEGER);
st.setInt(1,111);
st.execute();
int price = st.getInt(2);
System.out.println("price ="+price);
st.close();
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}

109 | P a g e Prime Hospital Lane, Behind Mythrivanam, Ameerpet, Hyderabad. Contact:9000780471

Você também pode gostar