You are on page 1of 185

Java Fundamentals JAVA CSREDDY

What do you mean by Software?

>> software is a development process which is going to convert our imaginaries or


dreams into reality by writing a set of programs or collection of programs.

>> To day in IT Sector we have three types of s/w applications, they are

1) System Software (Developed by using C & C++)

2) Application Software (Developed by using Database Products)

3) Internet Software (Developed by using .NET, JAVA)

>> To day in the IT Sector the developers or programmers can develop two types
of applications they are
1) Standalone Applications

2) Distributed Applications

Q) What do you mean by Standalone applications and Distributed Applications?

The applications which is going to run under the context of a local system hard
disk and whose results are not sharable across the globe, those are come under
standalone applications.

The applications which is going to run under the context of a server hard disk (we
are going to access them via client browser) and these results are sharable across the
globe, those are come under the category of Distributed applications.

Software Engineering:

Software engineering is the application of a systematic, disciplined,


quantifiable approach to the development, operation, and maintenance of software.

Q) What do you mean by Product and Project?

Product: The developed s/w application is common for all the clients are
known as products.

EG: MS-Office, Tally, Oracle …etc...

Project: The developed s/w application is not common for the clients and
it is different for the different clients based on their requirement are known as
project.

EG: Some of the Project based companies are TCS, WIPRO, and INFOSYS...Etc…

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Feasibility:

1.1. Economic Feasibility


1.2. Technical Feasibility
1.3. Time Feasibility

Normalization Use:

NORMALIZATION is used for the process of breaking up the data into several
tables so as to minimize the number of times we have to repeat the same data.

1) Help to eliminate duplicate records in the database tables.


2) Increase the Internal Consistency of the data.
3) And Decrease the Data Redundancy.

Q) Structured Programming & Object Oriented Programming?

Although Structured Programming has yielded excellent results when


applied to moderately complex programs, even it fails at some point, after a program
reaches a certain size. Using Structured Programming, the average programmer can
create and maintain programs that are up to 50,000 lines long.

To allow more complex programs to be written, a new approach to the job of


programming was needed. Towards this end, Object Oriented Programming was
invented. “Object Oriented Programming encourages you to decompose a
problem into its constituent parts. Each component becomes a self contained
object that contains its own instructions and data that relate to that object”.
In this way the complexity is reduced and the programmer can manage larger
programs.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Q) What do you mean by Static resources and Dynamic Resources?

At the beginning stages of computers we have client server architecture.


Where the main purpose of the server is to share the static resources to the client
requirements.
Static Resource: In this case when we send a request to the server machine, server
will identify the requested resource and send back to the client machine as a response.
Here server is generating the response without executing any application at server
machine so that this kind of response is called as static response.

Dynamic Response: As per the application requirements we need to get dynamic


response from server machine. To generate dynamic response server must execute
some applications at server machine, for this we should provide server side applications.

History of Java Language:

Java is a programming language developed at Sun Micro Systems in the year


1990 by a person called James Gosling and others. Whatever the trail version
which was released in the year 1990, whose name is “OAK” and it has taken 18
months to develop.

The software “OAK” is unable to meet industry standards or requirements.


Hence the Software OAK was revised in the year 1995. After revising the product
OAK, Sun Micro Systems released to the industry on the name of JAVA.

And JAVA is divided into 3 categories. They are J2SE, J2EE, and J2ME.

>J2SE (Java2 Standard Edition) is used for developing client side applications.

>J2EE (Java2 Enterprise Edition) is used for developing server side applications.

>J2ME (Java2 Mobile Edition) is used for developing Mobile/Wireless applications.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Features / Buzz Words of Java:

1) Simple
2) Platform Independent
3) Architectural Neutral
4) Portable
5) Multi Threaded
6) Networked
7) Distributed
8) High Performance
9) Interpreted
10) Robust
11) Dynamic
12) Secured
13) Object Oriented Programming Language

Simple:

1) Java is one of the simple programming languages why because java is totally
free from pointers. So 60% of the complexity is reduced.
2) Java Programming environment is free from pointers, i.e. the concept of
pointers cannot be used in java programming. Hence we get faster
development and faster execution of the java program. [ Byte code is so
faster than ordinary pointer code];
3) Java programming environment contains in built garbage collector for
collecting unused memory locations for improving the performance.
4) Java Programming environment can contain rich set of API [Application
Programming interface]. API it is a collection of packages. And package is a
collection of classes and interfaces and they interns contains collection of
predefined functions.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5) Java Programming environment contains user friendly syntaxes for
developing effective applications in java.

Platform Independent: [Operating systems totally 64 run java programs]

A Platform Independent language is one which runs on every operating system


without considering their vendors.

int - 2 bytes – DOS float – 4 bytes – DOS

4 bytes – UNIX 8 bytes – UNIX

1. The languages like c/c++ are treated as platform dependent since the data
types of c/c++ varying the memory space from one operating system to
another operating system.
2. The s/w of c/c++ is unable to convert one format of one operating system to
another format of other operating systems. [ DOS understands everything in
the format of MOZARTA (MZ) where as UNIX understands everything in
Embedded Linking Format (elf)]
3. The languages like java is treated as Platform independent since the data
types of java takes same memory space on all available operating systems.
4. The java s/w contains some special programs to convert from one format of
one operating system to other format of other operating system.
5. Finally the SLOGAN of Sun Micro Systems is “Writing once Run / Reuse
Anywhere” [WORA].

Architectural Neutral:

1. A language is said to be Architectural Neutral if and only if which runs on


available processors without considering their architectures and vendors.
2. The languages like c/c++ are treated as architecture dependent languages
since the s/w of c/c++ is unable to convert the factors of one processor to
other factors of other processor.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
3. The languages like java is treated as architecture neutral language since the
s/w of java contains some special programs to convert some factors of one
processor to some other factors of another processor.

Portable:

A portable language is one which will run on every operating system and every
processor without considering their vendors and architectures.

The languages like c/c++ are treated as non portable languages. The language java
is treated as portable language.

Portability=Plat Form Independent + Architectural Neutral

Multi Threading:

A flow of control is known as Thread.

 If a java program contains multiple flow of controls (Threads) then that java
program is known as Multi threading program.
 The purpose of thread is to execute the specific operation.
 The basic aim of multi threading is to achieve concurrent or simultaneous
execution.
 The real time implementation of multi threading is that server development.
 Multi Threading is a specialized form of multi tasking when we write any
program in java environment it contains 2 Threads. They are Fore Ground
Thread and Back Ground thread.
 Fore Ground thread is one which always executes user defined methods and
there is a possibility of creating multiple fore ground threads.
 A Back Ground thread is one which always monitors the status of fore ground
thread.

Q) How do you justify java is multi threaded language?

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
> Along with the regular java program there exists one of the back ground
program called Garbage Collector for monitoring the status of the regular java
program.

The thread which is created to execute regular java program is known as fore
ground thread and garbage collector is treated as back ground thread. Hence in
our java program 2 threads are running.

Networked:

It is a collection of interconnected autonomous/Non-autonomous


computers.

The basic aim of networking is that to share the data between multiple
machines either locally or globally.

According to industry standards we have 2 types of Networks.

1. Un Trusted Network
2. Trusted Network
Untrusted Network is one in which there exists collection of inter
connected Non- Autonomous computers. Using this network architecture we
can develop Intranet Applications by using J2SE.

Trusted Network is one in which there exists collection of interconnected


Autonomous computers. Using this network architecture we can develop Internet
Applications by using J2EE Technologies.

Distributed:

JAVA

Centralized Application Distributed Application

(Availability of Data is more)

J2SE (Single Server) Multi Server (J2EE)


urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
According to industry standards using java we can develop 2 types of
applications, they are 1) Centralized application

2) Distributed application

Centralized application is one which runs in single server always. Centralized


applications can be developed by J2SE. The limitation is that once the server is
down, clients are unable to communicate.

Distributed application is one which runs in multiple servers they can be developed
by using j2EE technologies. The advantage of Distributed application is that more
availability of data.

High- Performance:

Java is a High performance Language because it contains in built garbage collector


program for collecting unused memory locations.

The java programming environment is free from pointers

The magic of Byte Code will make the program execution faster.

Interpreted:

Java is one of the Interpreted programming languages. In the older


versions of java compilation phase will take less time and interpretation takes
more time, which is not recommended. In order to speed up the interpretation
process or phase Sun Micro systems has developed a program called JIT (Just in
Time) and introduced as a part of JVM. In the current versions of java the
interpretation phase is so faster than compilation phase.

Robust:

Java is a robust language because java programming environment can


effectively process Run Time errors of an application. Run time errors of java are
known as Exceptions. Hence java is strong in handling run time errors.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Secured:

It is one of the principles in IT to prevent the confidential Information from


Un Authorized users. Java API contains a separate package which provides security
i.e. Java Programmer need not to write their own security programs.

Dynamic:

Memory Allocation can be done in two ways and they are

1) Static Memory Allocation


2) Dynamic Memory Allocation

Static Memory Allocation is one in which memory will be allocated at compile


time.

Disadvantages:

1) Waste of Memory Space


2) Loss of Data
3) Overlapping of existing data with new data.

Java does not fallow static memory allocation due to above problems. But java
always follows Dynamic Memory Allocation only.

Dynamic Memory Allocation is one in which memory will be allocated at runtime.


In java to allocate memory space dynamically we use an operator called new
known as Dynamic Memory Allocation operator.

Q) If you want to write a meaning full program in any language we need to


fallow some basics what are they?

1) Programming Language

2) Translator

3) Storage Areas

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
4) Data Types

5) Tokens

6) Programming Constructs

7) Basic Structure of a Programming Language

Programming Languages are again categorized into 3 types.

a) Structured Oriented Programming Language :C


b) Object Oriented Programming Language : C++, JAVA, .NET etc...
c) Relational Model Programming Language : SQL and PL/SQL

Translator: Translator is nothing but a software program which can translate High
level language representation of source program into Machine level language
representations and Machine level language representations into human readable
format i.e. high level language representations.

Translators are again categorized into 3 types.

a) Compiler : Compile all lines at a time


b) Interpreter: Compile line by line
c) Assembler: Compile assembly level representations into machine level
language representations and vice versa. It is used a concept called
neumonics.

Storage Areas:

As part of enterprise applications requirement you need to store data in


some memory locations. These memory locations are called as Storage areas and
these are again categorized into 2 types. And they are as fallows

a) Temporary Storage Areas (TSA)


b) Permanent Storage Areas (PSA)

TSA: Examples: Buffers, Registers, Variables, Objects etc…


urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
PSA: If you want to store the data permanently we can use three different types
of Storage areas. They are given bellow.

1) File Systems 2) Databases 3) Data Warehouses

File Systems:

Databases:

Data Warehouses:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Data Types:

Data types are basically used to represent the input of the program in the
main memory of the computer by allocating sufficient memory space. In general in
any programming language we have 3 types of data types. They are

1) Fundamental Data Types or Primary Data Types


2) Derived Data Types
3) User/Programmer/Secondary Defined Data Types

Fundamental Data types:

Fundamental Data types allow us to represent a single value within the


variable but they are unable to represent multiple values of same type in a single
variable.

In java we have 8 fundamental Data Types which are organized in 4 groups or


categories.

1) Integer Category Data Types


2) Float Category Data Types
3) Character Category Data Types
4) Boolean category Data Types

Integer category data types:

These category data types are used for representing integer data. The
following table gives the types of integer category data types.

Range of any Data Type


urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
= (No. of bits available in the language which are understood by
computer) power No. of bits occupied by particular Data Type

Range of Byte Data Type= (2) power 8=1 to 256

 0 to 255
 0 to 255/2
 127.5 => 127.5
 -0.5 +0.5
 127 -128

Short Data Type= (2) power 16=1 to 65536 => 0 to 65535

+32767 => -32768

SNO Data Type Byte Size Range


1 byte 1 +127 to -128
2 short 2 +32767 to -32768
3 int 4 +x to –(x+1) i.e. (2) power 32 =x
4 long 8 +y to –(y+1) i.e. (2) power 64=y

Float category Data Type:

Float category Data Types are used for representing float values which are in the
form of scale, precision.

Ex: 500.789

Scale precision

The following table gives the types of float category data types.

SNO Data Type Size Range No. of Decimal


(bytes) places
1 float 4 +x to –(x+1) i. e. (2) power 32=x 8
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
2 double 8 +y to –(y+1) i.e. (2) power 64=y 16

Whenever we represent a real constant value using a float data type, the real
constant must be followed by a letter f otherwise; it will be treated as highest data
type in float category i.e. double.

10.75f is treated as float data type

10.75 is treated as double data type

Character Category Data Types:

A character is an identifier which is enclosed with in single quotes.

Ex: ‘a’,’b’,’1’ etc…

To represent character data in java we use a data type called “char”. This type
takes 2 bytes since java follows Unicode character set and it is available in 18
international languages.

UNICODE character set: It is one which contains all the characters which are
available in 18 international languages and it is followed by those programming
languages which are available in more than one international language.

NOTE:

ASCII is also a character set which is followed by those programming languages


which are available in one international language called English.

As per as English programmer is concerned, to represent a character we use one


byte and rest of one byte is wasted.

Boolean category Data Types:

Boolean category Data Type is used for representing logical values (true/false). To
represent true/false we use boolean data type. This data type takes 0 bytes why
because instead of storing the value in RAM it is stored in Flip Flops.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
And it is only one bit.

Note:

All the keywords in java must be written in small letters.

The default value of integer category variable is 0 i.e. Zero

The default value of float category variable is 0.0

The default value of character category variable is nothing

The default value of boolean category variable is false

Derived Data Types

Derived Data Types are those whose variables allow us to represent multiple
values of the same data type but they are unable to represent multiple values of
different type.

Example: arrays

User/Programmer/Secondary Defined Data Types

User/Programmer/Secondary Defined Data Types are those which are


developed by programmer. User/Programmer/Secondary Defined Data Types
allow us to represent multiple values of same type or different data types also.

Tokens:

A smallest individual unit in a passage of text is called as token. Even in our


computer programming languages also we need tokens. And these are as follows.

 Keywords
 Identifiers
 Constants
 Strings
 Special Symbols
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Operators

 Identifiers are the names of variables, methods, classes, packages and


interfaces.
 Identifiers must be composed of letters, numbers, the underscore _ and the
dollar sign $. Identifiers may only begin with a letter, the underscore or a
dollar sign.
 It's a good idea to give your variables mnemonic names that are closely
related to the values they hold.
 The main restriction on the names you can give your variables is that they
cannot contain any white space. You cannot begin a variable name with a
number.
 All variable names are case-sensitive. MyVariable is not the same as
myVariable.
 There is no limit to the length of a Java variable name.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Note: Remaining like operators and special symbols I hope you all aware about
that.
Programming Constructs:

Programming Constructs are again categorized into 3 types and they are

 Sequence statements Example: if, if else etc…


 Selection statements Example: switch
 Iterative Statements and again these are divided into two types.
 Entry Control Loop Example: while and for loop
 Exit Control Loop Example: do while loop

And in fallowing sessions we are going to understand the Basic Structure of


Java Programming language.

Comments in java:
Comments of any programming language improve readability/ Understandability /
Clarity. Java contains 3 types of comments;

1) Multiple Comment (Borrowed from C)


Syntax:
/*…..
….
…. */
2) Single Line Comment (Borrowed from C++)
Syntax:
// Comment….
3) Java Document Comment (Available in Java Only)
Syntax:
/**
….
…..
…..

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
*/

Variables in Java:

Whenever we pass any values to the java program, those values must be
presented interms of variables. Hence variables are treated as Building Blocks of
programming language.

A variable is an identifier whose value can be changed during execution of


the program.

Declaration of a Variable:

It is nothing but allocating sufficient amount of memory space for the variables.
Before using any variables in java, they must be declared.

Syntax:

data type v1, v2,…,vn;

data type represents either fundamental data type/ derived/ user defined data
type.

v1, v2,.. , vn represents java valid variable names.

Eg: int x; float f1, f2; boolean b; Here we are getting default values for the
variables.

Declaration cum Initialization:

It is nothing but allocating memory space for the variables and placing our
own values without placing default values.

Syntax:

data type v1=valu1,v2=val2,…,vn=valn;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
val1,val2,…,valn represents corresponding values for v1,v2,…vn.

Eg: int a=10,b=20;

Constants in java:

A constant is an identifier whose value can not be changed during execution of the
program. In order to make anything as constant in Java we use a keyword called
‘final’. Final keyword is placing an important role in 3 places. They are

1) At Variable Level
2) At Method Level
3) At Class Level

At Variable Level:

If we don’t want to change the value of the variable then that variable must be
made as final.

Syntax:

final data type v1=val1, v2=val2,…,vn=valn;

Ex: final float f1=3.147f;

f1=f1+2; // Invalid statement here we are getting compilation error.

Hence final variables values cannot be modified/changed.

At Method Level:

Each and every operation in java can be performed with respect to method.
If we don’t want to change the definition of the method, then that method must
be made as final.

Syntax:

final return type method_Name(list of arguments if any)

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{ //block of statement(s);

Ex:

final float simpleInterest (float p, float t, float r)

{ float res= (p*t*r)/100;

return (res);

Hence final methods cannot be overridden/ redefined.

At Class Level:
If we don’t want to give the features of base class to the derived class, then the base
class must be made as final
Syntax:
final class <ClassName>
{
//Body of the class
}
Final classes cannot be inherited by derived classes i.e. final classes will not participate
in Inheritance process.
Object oriented Programming Concepts:

1) Class

2) Object

3) Data Abstraction or Data Hiding

4) Data Encapsulation

5) Inheritance

6) Polymorpisham

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
7) Dynamic Binding

8) Message Passing

Classes:
1) The purpose of class is to develop user defined data types.
2) Each and every java program must be developed by using the concept called
classes.

A class is a way of binding the data members and associated methods in a single
unit.

a) The data members of the class are also known as properties or attributes where as
methods of the class are also known as behaviors or accessories.
b) In object oriented programming we have 2 types of methods. They are 1) Member
Methods 2) Non-Member Methods
c) A Member Method is one which is available within the scope of the class and they
can access private data of the class.
d) A Non_Member Method is one which does not come under the scope of the class
and they cannot access private data of the class.
e) In java programming environment member methods are allowed, but there is no
concept of Non-Member methods. Hence java provides 100% security.

Syntax:

class <ClassName>

{ variable declaration; // Heap Memory

methods definition; // Stack Memory

 class is a keyword used for developing user defined data types.


 <ClassName> is a java valid variable name treated as name of the class. Each and
every class name is treated as secondary or user defined data type.
 Class name is used for creating objects.
 Whenever we create a class there is no memory space for data members and
methods of a class and memory space will be coming when we create an object.
 The definition of a particular class will exist only one time.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Each and every operation in java must be performed with respect to methods.
Each and every method of java must be defined with in class and such methods
are known as member methods.

Objects:
 Whenever we create a class there is no memory space for data members and
methods of a class and memory space will be coming when we create an object.
 Definitions:
 Instance of a class is known as object.
 Instance is nothing but allocating sufficient memory space for data members and
methods of a class.
 Class variable is known as an object.
 Grouped item is known as an object.
 (If a variable contains multiple values of same type or different type or both then
that item is known as grouped item)
 Value form of a class is known as an object.
 Blue print of a class is known as an object.
 Real world entities are known as an object.

Creation of Object:

In order to create an object in java programming environment we must follow


Dynamic Memory allocation, to allocate the memory space dynamically we use an
operator called “new”.
The new operator internally performs the following operations.
1) It allocates sufficient amount of memory space for data members and methods of
a class.
2) It takes an address of created memory space and placed into L.H.S variable i.e.
Object name.
Syntax1:
<ClassName> objectname=new <ClassName ()>;
Student s=new Student (); // Assume that Student is a Class

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Syntax2:
<ClassName> objectname; // represents object declaration and whose default
value is null.
objectname=new <ClassName(); // represents object referencing and whose
default value is not null.
Types of Data members/Variables in Java:
In java programming environment every program must be written with respect to
classes. In Java the class can contain 2 types of data members, they are
1) Instance or Non Static Variables
2) Static Data Members
SNO Instance Data Members Static Data Members
1 Instance Data Members are those Static Data Members are those whose
whose memory space is created memory is created only once when the class
each and every time when an is loaded in main memory irrespective of
object is created. number of objects created.
2 Programmatically instance variables Programmatically static variables declaration
declaration should not be preceded must be preceded by a keyword called
by a key word ‘static’ “static”
3 Syntax: Syntax:
Data type v1,v2,….,vn; Static data type v1,v2,..,vn;
4 Instance Data Members are Static Data Members must be accessed with
accessed with respect to object respect to class name.
name. Classname.staticmembername;
Obj.instancemembername;
5 The value of instance data member The value of static data member is always
is not sharable sharable
6 Instance Data Members are also Static Data Members are also known as class
known as object level data level data members since they depends on
members since they depends on class and independent from object.
object and independent from class. Ex:
Ex: int stno; static String ename;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Note: The classes are loaded into main memory with the help of Class Loader Sub
System (Which is a part of JVM).

Types of Methods in Java:


In Java the class can contain 2 types of methods. They are 1)Instance / Non static
Methods 2) Static Methods

SNO Instance Methods Static Methods


1 Instance Methods are those which Static Members are those which are
are recommended to perform recommended to perform one time
repeated operations such as operations such as opening the file either in
reading data from the file, reading read/Write mode, Obtaining connection from
the data from database etc... data base etc…
2 Programmatically instance methods Programmatically static methods definition
definition should not be preceded must be preceded by a keyword called
by a key word ‘static’ “static”
3 Syntax: Syntax:
return type method_name(List static return type method_name(List of
of arguments if any) arguments if any)
{ {
Block of statement(s); Block of statement(s);
} }
4 Instance methods must be Static methods must be accessed with
accessed with respect to object respect to class name.
name. Classname.staticMethodName();
Obj.instancemethodName();
5 The result of instance methods is The result of static methods is always
not sharable sharable
6 Instance Methods are also known Static Methods are also known as class level

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
as object level methods since they methods since they depends on class and
depend on object and independent independent from object.
from class.

Example:
System.out.println ();
The above statement is used for displaying the data on the console Line By Line
System.out.print();
The above statement is used for displaying the data on the console in the same line.
println () and print () methods are the 2 predefined instance methods present in
one of the predefined class called PrintStream. To access print() and println() methods
we need an object of PrintStream class.
An object of PrintStream class called “out” is created as a static data member in
another predefined class System. Hence print(), println() methods must be accessed by
us in the java programming as follows.
System.out.println ();
System.out.println ();
Hungarian Notation:
This is the naming convention followed by Sun Microsystems for development of Library
/ API of JAVA.
Rule for Class/ Interface:
If a class name contains either one or more than one word then all the words first letters
must be capital.
Ex: system Normal Notation System Hungarian Notation
printstream PrintStream
numberformatexception NumberFormatException
arrayindexoutofboundsexception ArrayIndexOutOfBoundsException
Rule for Method:
If a method name contains either one or more than one word, then first word first letter
is small and rest of the subsequent words first letters must be capital.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Normal Notation Hungarian Notation
println (); println ();
actionperformed(); actionPerformed();
adjustmentvaluechanged (); adjustmentvaluechanged();

Rule for Data Members:


If we use any data members from the predefined classes /interfaces then those data
members must be written in capital letters. If the data member contains more than one
word then those words must be separated by underscore ‘_’
Normal Notation Hungarian Notation
pi PI
maxpriority MAX_PRIORITY
verticalscrollbaronly VERTICAL_SCROLLBAR_ONLY

Note: Hungarian Notation is mandatory for predefined classes/ interfaces,


methods and data members. And this notation is optional for user defined ones.
But it is recommended to follow Hungarian Notation even for user defined
Classes/ Interfaces, Methods, Data Members
Program:
Write a java program will illustrates the concept of instance methods and static
methods?
class Demo
{ void f3()
{
System.out.println("F3 is instance method");
}
void f1()
{
f3(); // rule-2
Demo.f2(); //rule-4
System.out.println ("F1 is instance method");
}
static void f2()
{
System.out.println("F2 is static method");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
public static void main(String args[])
{
System.out.println ("Main begining");
Demo d=new Demo();
d.f1 (); //rule-3
f2 (); // or Demo.f2 (); //rule-1
System.out.println ("Main method ending");
}}
Rule-1:
One static method can call another static method directly provided that both methods
belong to same class.
Rule-2:
One instance method can call another instance method directly provided both the
methods belong to same class.
Rule-3:
One static method can call another instance method with respect to object whether they
belong to same class / different class.
Rule-4:
One instance method can call another static method with respect to class name whether
they belong to same class /different class.
Note:
1) According to industry standards it is highly recommended to write a separate class
which contains business logic methods and this class is known as Business Logic
Class. Where as we write separate class which contains execution logic method
(main) and this class is known as execution Logic Class.
2) Business logic is one which gives solution to the client requirement / problem.
3) Execution logic is one which will give solution for calling business logic methods.
Passing Dynamic Data to Java Program:
In order to get the dynamic data to a java program we have 2 approaches.
1) Reading the Data From keyboard
2) Reading the Data From Command Prompt I.e. command line arguments
Example:
class Command
{ public static void main(String args[])
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{ System.out.println("No of Values="+args.length);
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z=x+y;
System.out.println(z);
}}
Conversion of String Data into Fundamental Data:
When we pass the data from command prompt to java program which is by
default treated as String Data. On String data we cannot perform any numerical
operations. Hence we must convert String Data into Fundamental or numerical data with
the help of Wrapper Classes. The following table gives fundamental datatype, its
corresponding Wrapper class name and conversion method from String into fundamental
data.
SNO Data Wrapper Class Conversion Method from String Data to
Types Fundamental Data
1 byte Byte public static byte parseByte(String)
2 short Short public static short parseShort(String)
3 int Integer public static int parseInt(String)
4 long Long public static long parseLong(String)
5 float Float public static float parseFloat(String)
6 double Double public static double parseDouble(String)
7 char Character public static char parsechar(String)
8 boolean Boolean public static boolean parseBoolean(String)

class Command
{ public static void main(String args[])
{ System.out.println("No of Values="+args.length);
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
float n1=Float.parseFloat(args[2]);
float n2=Float.parseFloat(args[3]);

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int z=x+y;
float n3=n1+n2;
System.out.println(z);
System.out.println(n3);
}
}
// Display all command-line arguments.
class CommandLine
{ public static void main(String args[])
{ System.out.println("Length of the String array is:"+args.length);
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Sample Program:
class Book {
String id;
String title;
String author;
void getChaptersList() {
id="Adv1";
title="Servlets";
author="Srinivasa Reddy";
System.out.println("Getting the chapters list");
System.out.println("ID:"+id);
System.out.println("Title:"+title);
System.out.println("Author:"+author);
System.out.println("-------------------------");
}
public static void main(String[] args) {
Book book1 = new Book();
book1.getChaptersList();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Book book2 = new Book();
book2.getChaptersList();
}
}

import java.io.*;
class Emp
{
public static void main(String args[])throws Exception
{
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
InputStreamReader is=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(is);
System.out.println("Employee Number:");
int eno=Integer.parseInt(br.readLine());
System.out.println("Employee Name:");
String ename=br.readLine();
System.out.println("Employee Salary:");
float sal=Float.parseFloat(br.readLine());
System.out.println("Employee Details:");
System.out.println("------------------");
System.out.println("Employee Number:"+eno);
System.out.println("Employee Name:"+ename);
System.out.println("Employee Salary:"+sal);
}
}

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Sample:

import java.io.*;

class Bank
{
public static void main(String args[]) throws IOException
{ int i,j;
String[] ename;
ename=new String[30];
String[] bname;
bname=new String[30];
String[] type;
type=new String[30];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(i=0;i<=2;i++)
{ System.out.println("Enter the name:");
ename[i]=br.readLine();
System.out.println("Enter the bank name:");
bname[i]=br.readLine();
System.out.println("Enter the accnt type:");
type[i]=br.readLine();
}
System.out.println("name bank actype");
for(j=0;j<=2;j++)
{
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(ename[j]+" "+bname[j]+" "+type[j]);
}
}
}

Sample:
class Initialization {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
Object o;
public static void main(String[] args) {
Initialization app = new Initialization();
app.run();
}
void run() {
System.out.println("boolean: " + bo);
System.out.println("byte: " + by);
System.out.println("char: " + c);
System.out.println("short: " + s);
System.out.println("int: " + i);
System.out.println("long: " + l);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("Object: " + o);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}

// -----------------------------------------------------------------------------
// MathLibraryExample.java
// -----------------------------------------------------------------------------
/**
* -----------------------------------------------------------------------------
* Used to provide an example that exercises most of the routines in
* java.lang.Math.
* @version 1.0
* @author Srinivasa Reddy Challa
* -----------------------------------------------------------------------------
*/
public class MathLibraryExample {
private static int i = 7;
private static int j = -9;
private static double x = 72.3;
private static double y = 0.34;
/**
* Helper utility used to print a String to STDOUT.
* @param s String that will be printed to STDOUT.
*/
private static void prt(String s) {
System.out.println(s);
}
private static void prt() {
System.out.println();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
/**
* Helper utility used to print all variables used through out all
* example Math methods.
*/

private static void printVariables() {


prt("PRINT VARIABLES");
prt("===========================================");
prt(" (int) i = " + i);
prt(" (int) j = " + j);
prt(" (double) x = " + x);
prt(" (double) y = " + y);
prt();
}
/**
* The Math library defines several useful constants.
*/
private static void printMathConstants() {
prt("MATH CONSTANTS");
prt("===========================================");
prt(" Pi is " + Math.PI);
prt(" e is " + Math.E);
prt();
}
/**
* The absolute value of a number is equal to the number if the number is
* positive or zero and equal to the negative of the number if the number
* is negative.
*/
private static void doAbsoluteValues() {
prt("ABSOLUTE VALUE");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
prt("===========================================");
prt(" |" + i + "| is " + Math.abs(i));
prt(" |" + j + "| is " + Math.abs(j));
prt(" |" + x + "| is " + Math.abs(x));
prt(" |" + y + "| is " + Math.abs(y));
prt(); }

/**
* Round off a floating point number to the nearest integer with round().
* <p>
* The "ceiling" of a number is the smallest integer greater than or equal
* to the number. Every integer is its own ceiling.
* <p>
* The "floor" of a number is the largest integer less than or equal to the
* number. Every integer is its own floor.
*/
private static void doTruncateRounding() {
prt("TRUNCATING AND ROUNDING FUNCTIONS");
prt("===========================================");
prt(" " + x + " is approximately " + Math.round(x));
prt(" " + y + " is approximately " + Math.round(y));
prt();
prt(" The ceiling of " + i + " is " + Math.ceil(i));
prt(" The ceiling of " + j + " is " + Math.ceil(j));
prt(" The ceiling of " + x + " is " + Math.ceil(x));
prt(" The ceiling of " + y + " is " + Math.ceil(y));
prt();
prt(" The floor of " + i + " is " + Math.floor(i));
prt(" The floor of " + j + " is " + Math.floor(j));
prt(" The floor of " + x + " is " + Math.floor(x));
prt(" The floor of " + y + " is " + Math.floor(y));
prt();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}

/**
* Comparison operators. min() returns the smaller of the two arguments
* (numbers) you pass it.
* <p>
* max() returns the the larger of the two arguments (numbers) you pass it.
*/
private static void doComparisonOperators() {
prt("COMPARISON OPERATORS");
prt("===========================================");
prt(" min(" + i + ", " + j + ") is " + Math.min(i,j));
prt(" min(" + x + ", " + y + ") is " + Math.min(x,y));
prt(" min(" + i + ", " + x + ") is " + Math.min(i,x));
prt(" min(" + y + ", " + j + ") is " + Math.min(y,j));
prt();
prt(" max(" + i + ", " + j + ") is " + Math.max(i,j));
prt(" max(" + x + ", " + y + ") is " + Math.max(x,y));
prt(" max(" + i + ", " + x + ") is " + Math.max(i,x));
prt(" max(" + y + ", " + j + ") is " + Math.max(y,j));
prt();
}
/**
* Trigonometric Methods. All arguments are given in radians.
*/
private static void doTrigonometricMethods() {
prt("TRIGONOMETRIC METHODS");
prt("===========================================");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// Convert a 45 degree angle to radians
double angle = 45.0 * 2.0 * Math.PI/360.0;
prt(" cos(" + angle + ") is " + Math.cos(angle));
prt(" sin(" + angle + ") is " + Math.sin(angle));

// Inverse Trigonometric methods. All values are returned as radians


double value = 0.707;
prt(" acos(" + value + ") is " + Math.acos(value));
prt(" asin(" + value + ") is " + Math.asin(value));
prt(" atan(" + value + ") is " + Math.atan(value));
prt();
}
/**
* Exponential and Logarithmic Methods.
*/
private static void doExponentialLogarithmicMethods() {
prt("EXPONENTIAL AND LOGARITHMIC METHODS");
prt("===========================================");
// exp(a) returns e (2.71828...) raised to the power of a.
prt(" exp(1.0) is " + Math.exp(1.0));
prt(" exp(10.0) is " + Math.exp(10.0));
prt(" exp(0.0) is " + Math.exp(0.0));
prt();
// log(a) returns the natural logarithm (base e) of a.
prt(" log(1.0) is " + Math.log(1.0));
prt(" log(10.0) is " + Math.log(10.0));
prt(" log(Math.E) is " + Math.log(Math.E));
prt();
}

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

/**
* Using Power Method. pow(x, y) returns the x raised to the yth power.
*/
private static void doPower() {
prt("POWER METHOD");
prt("===========================================");
prt(" pow(2.0, 2.0) is " + Math.pow(2.0,2.0));
prt(" pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
prt(" pow(8, -1) is " + Math.pow(8,-1));
prt();
}
/**
* Using Power Method. qrt(x) returns the square root of x.
*/
private static void doSquareRoot() {
prt("SQUARE ROOT METHOD");
prt("===========================================");
for (i=0; i < 10; i++) {
prt(" The square root of " + i + " is " + Math.sqrt(i));
}
prt();
}
/**
* Random Numbers. Java provides a Random method that returns a
* pseudo-random number between 0.0 and 1.0.
*/
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
private static void doRandomNumbers() {
prt("RANDOM NUMBERS");
prt("===========================================");
prt(" Random number: " + Math.random());
prt(" Random number: " + Math.random());
prt(); }
public static void main(String[] args) {
prt();
printVariables();
printMathConstants();
doAbsoluteValues();
doTruncateRounding();
doComparisonOperators();
doTrigonometricMethods();
doExponentialLogarithmicMethods();
doPower();
doSquareRoot();
doRandomNumbers();
}
}
Constructors in Java:
A constructor is a special member method which will be called by the JVM
automatically whenever an object is created for placing our own values instead of
placing default values.
Advantages:
1) It eliminates in placing default values
2) It eliminates the calling of ordinary methods explicitly; the purpose of the
constructors is that to initialize an object.
Rules / Properties / Characteristics of Constructors
1) Constructor will be called automatically whenever an object is created.
2) The name of the constructor must be similar to name of the class.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
3) Constructor should not return any value, even void also. [ if we write any return
type which is by default treated as ordinary method ]
4) Constructors should not be static since they will be called each and every time as
and when an object is created.
5) Constructors will not be inherited.

Types of Constructors:
In Java we have 2 types of constructors. They are
a) Default / Parameter Less/ No Argument Constructor
b) Parameterized Constructor
Note:
Defining default constructor is optional. If we are not defining the default constructor
then JVM will call its own constructor called system defined constructor and it places
default values depending upon data type. If we define the default constructor of the
class, then JVM will call the user defined constructor for placing our own values.
Note:
Each and every class contains the default constructor.
class Test
{ int a,b;
Test()
{ a=10;
b=20;
System.out.println("I am from Dconstructor");
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
}
class Con_Demo1
{
public static void main(String args[])
{
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Test t1=new Test();
}
}
Q) Write a sample program to get values into the constructor at runtime? One
is by using BufferedReader Class, DataInputStream Class? (Get Empno, Ename,
Job, and Salary and print it by using other function or method?

Parameterized Constructor:
Parameterized Constructors are used for creating multiple objects of same class
with different values.
Parameterized Constructor is one which always takes parameters.
class name
{ ---
ClassName(list of arguments or formal parameters)
{ // Block of Statements;
}
}
Program:
class Test
{ int a,b;
Test(int x,int y)
{ a=x;
b=y;
System.out.println("I am from Parameterized constructor");
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
}
class Con_Demo2
{ public static void main(String args[])
{
Test t1=new Test(1,2);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Test t2=new Test(10,20);
Test t3=new Test(100,200);
}
}
Note Point 1) Whenever we create an object using parameterized constructor defining
parameterized constructor is mandatory.
Note Point 2) Whenever we create multiple objects with both default and
parameterized constructors, it is mandatory for the java programmer to define both
parameterized and default constructors. Otherwise, we get compile time errors.
Overloaded Constructor:
Every Overloaded Constructor is a parameterized constructor and it is mandatory
to define.
A constructor is said to be overloaded if constructor name is same but its
signature is different.
Signature represents
a) Number of Parameters
b) Type of Parameters // At least one thing must be differentiated
c) Order of Parameters
Object Parameterized Constructor or Copy Constructor
It is one which takes object as a parameter.
Note: Object parameterized constructor is used for copying the content of one object to
another object. And both the objects must belong to same type.
class Test {
int a,b;
Test(int x,int y) { a=x; b=y;
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
Test(Test t) { a=t.a; b=t.b;
System.out.println("Value of a="+a);
System.out.println("Value os b="+b);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
class Con_Demo3
{ public static void main(String args[])
{ Test t1=new Test(10,20);
Test t2=new Test(t1);
} }
this keyword Usage:
“this” is a keyword / implicit object created by JVM for 2 purposes. They are
1) It points to current class object
2) Whenever formal parameters and data members of the class are similar, there is a
possibility of ambiguity. In order to differentiate between formal parameters and
Data Members of the class, the data members of the class must be proceeded by a
keyword “this”
this.currentclassdatamember;
class Sample
{ int a,b;
Sample(int a, int b)
{
this.a=a;
this.b=b;
}
void disp()
{
System.out.println("Value of a="+a);
System.out.println("Value of b="+b);
}
}
class This1
{
public static void main(String args[])
{
Sample s1=new Sample(10,20);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
s1.disp();
Sample s2=new Sample(2,15);
s2.disp();
}
}

this(),this(…):
In order to call the current class constructors we must use the following functions.
this():
It is used for calling current class default constructor from current class parameterized
constructors.
this(..,..):
It is used for calling current class parameterized constructors from other category
constructors of same class.
Note:
Whenever we use either this() or this(...,…) in the current class constructors, they must
be always used as first statement.
Sample:
class Sample
{int a,b;
Sample()
{ System.out.println(" I Am From Deafault Constructor");
a=1; b=2;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
}
Sample(int x)
{ this(10,20);
System.out.println(" I am from SPCons");
a=b=x;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
Sample(int a,int b)
{ this();
System.out.println(" I am from DPConstructor");
this.a=a;
this.b=b;
System.out.println(" Value of a="+a);
System.out.println(" Value of b="+b);
}
}
class This2
{ public static void main(String args[])
{
Sample s1=new Sample (100);
}
}

Inheritance:
Inheritance is a mechanism of getting the features from one class to another class.
The class which is giving the data members and methods is known as
Base/Parent/Super Class. The class which is taking data members is known as derived.
Derived Class: Derived Class is one which contains some of the features of its own plus
some of the features from Base Class. Features of a class are nothing but Data Members
and Methods. The process of inheritance is also known as Sub Classing/Reusability
/Derivation/Extendibility.
Advantages of Inheritance:
 Application Development time is less.
 Redundancy of the code is reduced. Hence we get consistent result plus less
execution time.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Application Memory Space is reduced. Hence we get effective performance and
reduced memory space.
Inheritance Types:
Based on getting the features from one class to another class java contains 5 reusable
techniques / Inheritance Types.
They are: Single Inheritance , Multi Level, Hierarchical, Multiple, Hybrid Inheritance.

Single Inheritance:
It is one in which there exists single base class and single derived class.
Multi Level Inheritance:
It is one in which there exists single base class, single derived class and ‘n’ number of
intermediate base classes. Intermediate base class is one in one context it acts as base
class and in another context the same class acts as derived class.
C1 (Base Class) C2 (DC &BC)  C3 (DC &BC) C4 Derived Class.
IBC IBC
Hierarchical Inheritance:
It is one in which there exists single base class and ‘n’ number of Derived Classes.

C1 is a Base Class For that We are having C2, C3, C4 etc are derived Classes.

Multiple Inheritance:
It is one in which there exists Multiple Base Classes and Single Derived Class.
Java does not support multiple Inheritance through the concept of classes but it can be
supported by Java through the concept of interfaces.

Hybrid Inheritance: Combination of any available Inheritance types. In the combination,


if one of the combinations is Multiple Inheritance then that entire Hybrid Inheritance is
not supported by Java through classes but it can be supported by java through
Interfaces Concept.

Syntax for inheriting the features from base class to derived class.
class <ClassName> extends <Super Class Name>
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
//Variable Declaration;
// Methods definition;
}
extends is a keyword which is used for inheriting the features of Base Class
into derived class plus it improves the functionality of Derived Class.

 One derived class can extend only one base class


 Whenever we develop any inheritance application it is always recommended to
create an object of bottom most derived class since it contains all its super class
features.
 If we don’t want to inherit the some of the features of the base class into derived
class then those base class features must be made as private. Hence private
features of the base class will not be inherited into derived class.
 If we don’t want to inherit entire features of base class into the derived class then
the base class must be made as final. Already you know that final classes cannot
be re used/ extended.
 Whenever we create object of Bottom Most Derived Class, first we get the memory
space for base class members and later we get the memory space for derived
class member.
 For each and every class in java there exists a predefined implicit super class
called java.lang.Object and it provides Garbage Collector for collecting unused
memory locations.
Write a program for single inheritance:

class bc
{ int a;
void disp1(){ System.out.println("Display Base Class");}
}
class dc extends bc
{ int b;
void disp2() { System.out.println("Display Of Derived class");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
a=10; b=20;
System.out.println("Value of a="+a);
System.out.println("Value of b="+b); }
}

class idemo1
{ public static void main(String args[]) {
dc d=new dc();
d.disp1();
d.disp2();
}
}
Multi Level Demo:
class Admin

{ int stfatt,stdatt; double sal;


void getDetails(int att1,int att2)
{ stfatt=att1; stdatt=att2; }
protected void putAtt()
{
System.out.println(" Student Attendence : "+stdatt+" "+stfatt); }
}
class FrontOffice extends Admin
{ protected void giveSal()
{ putAtt();
sal=25000; }
}
class Accountant extends FrontOffice
{ void printSal()
{ giveSal();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("\nStaff Salary : "+sal); }
}
class MultiLevelDemo
{ public static void main(String args[])
{ Accountant a=new Accountant();
a.getDetails(25,28);
a.printSal();
} }
Hierarchical Demo:
class Eng{ int dur; double fees;
public Eng() { dur=4; fees=20000.00; }
protected void disp() { System.out.println("\nThe Duration is : "+dur);
System.out.println("The Fees is : "+fees);
}
}
class EEE extends Eng { String s1,s2,s3;
public EEE(String s1,String s2,String s3)
{ this.s1=s1; this.s2=s2; this.s3=s3; }
public void display() { disp();
System.out.println("The Subjects are");
System.out.println("Subject 1 :"+s1);
System.out.println("Subject 2 :"+s2);
System.out.println("Subject 3 :"+s3); }
}
class CSIT extends Eng
{ String s1,s2,s3;
public CSIT(String s1,String s2,String s3)
{ this.s1=s1; this.s2=s2; this.s3=s3; }
public void display() { disp();
System.out.println("The Subjects are ");
System.out.println("Subject 1 :"+s1);
System.out.println("Subject 2 :"+s2);
System.out.println("Subject 3 :"+s3); }

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
class HeirarchialDemo
{ public static void main(String args[]) {
EEE e=new EEE("Electronics","Maths","Physics");
CSIT c=new CSIT("Computers","Power Systems","Maths");
e.display();
c.display();
}}
Super Keyword:
In order to differentiate the base class features and derived class features we use a
keyword ‘super’. The keyword ‘super’ is placing an important role in 3 places. They
are
 At Variable Level
 At Method Level
 At Constructor Level

Super At Variable Level:


Whenever we inherit the base class members into derived class there is a
possibility that base class members are similar to derived class members.
In order to differentiate the base class members from derived class members in
the context of derived class, the base class members must be preceded by ‘super’
keyword.
super.baseclassmembername;
Program: /* super at variable level */
class bc { int a; }
class dc extends bc { int a,c;
void set(int x,int y) {
super.a=x;
a=y; }
void sum() { c=super.a+a; }
void disp() {
System.out.println("Value of a from bc:"+super.a);
System.out.println("Value of a from dc:"+a);
System.out.println("Value of a from c:"+c);
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
class idemo2
{ public static void main(String args[]) {
int x=Integer.parseInt(args [0]);
int y=Integer.parseInt(args [1]);
dc d=new dc();
d.set(x,y);
d.sum();
d.disp(); } }
Super At Method Level:
Whenever we inherit the base class methods into derived class, there is a
possibility that base class methods are similar to derived class methods. In order to
differentiate the base class methods from derived class methods in the context of
derived class, base class methods must be preceded by ‘super’ keyword.
super.baseclassmethodname;
Program:
/* super at method level */
class bc
{
void disp()
{
System.out.println("Display of Base Class");
}
}
class dc extends bc
{
void disp()
{
super.disp();
System.out.println("Display of Derived Class");
}
}
class idemo3
{
public static void main(String args[])

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
dc d=new dc();
d.disp();
}
}
Note: In the above program if we remove ‘super’ keyword then the current disp() will
be called by itself recursively and finally we get an error at runtime. Known as
java.lang.StackOverFlowError

Method Overriding:
Method Overriding=Method Heading is same but method body is different.
(or)
Method over riding is a process of redefining the original method in various
derived classes by inheriting the original method from base class.

Program: /* Example for Method overriding */


class bc
{ private int a,b,c;
void sum() { a=10; b=20;
c=a+b;
System.out.println("Sum:"+c);
}
}
class dc extends bc
{ float f1,f2,f3;
void sum(){ super.sum();
f1=10.75f;
f2=10.25f;
f3=f1+f2;
System.out.println("Float sum="+f3);
}
}
class idemo6
{ public static void main(String args[]) { dc d=new dc();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
d.sum();
}
}
How do you call the original method from overridden method?
ANS: super.originalmethodname();
The above statement must be written in the context of derived class overridden
method.

Super at Constructor Level:


In order to call the super class constructor from derived class constructors we
must use the following functions.
super():
It is used for calling super class default constructor from derived class
constructors.
super(…):
It is used for calling super class parameterized constructor from derived
class constructors.

Rule:
Whenever we use either super(), super(..) in the derived class constructors,
they must be used as first statement.
Note: Important Points:
 Whenever we want to call base class default constructor from derived class
constructors we have to use super() in the context of derived class constructor.
 Writing super() in the context of derived class constructor is optional.
/* Super at Constructor Level */
class c1 { int a,b;
c1() { System.out.println("c1 deafault constructor");
a=10; b=20;
System.out.println("Value of a:"+a);
System.out.println("Value of b:"+b); }
}
class c2 extends c1 { int c,d;
c2() { super();
System.out.println("c2 deafault constructor");

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
c=30; d=40;
System.out.println("Value of C:"+c);
System.out.println("Value of d:"+d); }
}
class idemo4 { public static void main(String args[])
{ c2 o2=new c2();
}
}

Note: Important Points:


 Whenever we want to call base class parameterized constructor from derived class
constructors we must use super (…) in the context of derived class constructors.
 Writing super (…) in the context of derived class is mandatory.

class c1
{ int a,b;
c1(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("C1 Par Constructor");
System.out.println("Value of a:"+a);
System.out.println("Value of b:"+b);
}
}
class c2 extends c1
{ int c,d;
c2()
{ super(10,20);
System.out.println("C2 Defalut Constructor");
c=30;
d=40;
System.out.println("Value of c:"+c);
System.out.println("Value of d:"+d);

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
}
class idemo5
{ public static void main(String args[])
{ c2 o2=new c2();
}
}

Polymorphism:
Polymorphism is one of the oops principle. “It is a process of representing one
form in multiple / may forms”.
The principle of polymorphism is implemented in java programmatically by using
the concept of method overriding. In object oriented programming we have 2 types
of polymorphisms. They are
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
It is one in which the method binds with an object at compile time and normally
space is created for the methods at compile time only.
 The disadvantage of static polymorphism is that “Poor Utilization of Memory
Space”. To avoid this limitation we must use runtime polymorphism.
Runtime Polymorphism:
It is one in which method binds with an object at runtime and memory space for
the method will be allocated at runtime. The advantage of runtime polymorphism is that
effective utilization of memory space.
In real time applications when we are developing multiple applications with the
similar type of logic, it is always recommended to write with the concept of
polymorphism.

Dynamic Binding:
 Dynamic binding always says that “Don’t create an object of derived class
but create an object of the base class”.
 The basic aim of dynamic binding is that to execute polymorphism applications.
 The purpose of dynamic binding is that to increase the performance of an
application by reducing the amount of memory space.
Definition:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Dynamic Binding is a mechanism of binding an appropriate version of derived class
which is inherited from base class with base class object.
Note:
While we are executing polymorphism application with dynamic binding concept,
internally 2 points will be considered
by int a,b,c; JVM
1) What type of Object
void sum() 2) What type of address object
{ contains
Eg: a=10;
Let us b=20; consider the following entries which
will execute the program which was
c=a+b;
developed in the bellow diagram.
Sop(“Int Sum==”+c);
}
Consider the following Diagram:

C1 Class
char c1,c2,c3;

void sum()

c1=’A’;

c2=’B’;

c3=c1+c2;

Class C3

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Class C2 Sop(“Int Sum==”+c3);

float f1,f2,f3; }

void sum()

f1=10;

f2=20;

f3=f1+f2;

Sop(“Float Sum=”+f3);

1) C1 o1;
2) o1=new C1();
3) o1.sum();
4) o1=new C2();
5) o1.sum();
6) o1=new C3();
7) o1.sum();

In the statements (2), (4), (6) the object o1 contains an address of classes C1, C2,
C3. Hence the object o1 is known as Polymorphic Object.

The sum() is only one and it was implemented for performing various sums. Hence
sum() is known as polymorphic method.

In statements (3), (5), (7) o1.sum() is one but it gives different sum’s. Hence
o1.sum() is called polymorphic statement.

Note:

It is always recommended for the java programmer to develop an


application with polymorphism along with method overriding and execute
with the help of Dynamic Binding.

Types of Relationships in Java:

In order to use the features of one class into another class java contains 3
types of Relationships. They are
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) Is- a Relationship: It is one in which the features of one class are inherited into
another class by using inheritance with extends keyword.
class C1
{ …

}
class C2 extends C1
{


}
2) Has a relationship: It is one in which the object of one class is created as a data
member in another class.

class C1
{ …

}
class C2 { …

C1 o1=new C1(); //Has a Relationship
}

3) Uses a Relationship:

It is one in which a method of one class is using an object of another class.


class C1
{ …

}
class C2 { …

void disp()
{ …

C1 o1=new C1(); //Uses a Relationship


}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Factory Method:

A Factory method is one whose return type must be similar to name of the class where it
belongs to.

The purpose of Factory Method is that to create an object of the class without
using new operator.

Rules for Writing Factory Method:

1) The return type of Factory Method must be similar to name of the class where it
belongs to.
2) Every Factory Method in java must be static
3) Every Factory Method is recommended to make it to belong to public.

Abstract Classes:

Each and every program in java must be developed with respect to classes. Java
contains 2 types of classes. They are 1) Concrete Classes 2) Abstract Classes

 A concrete class is one which contains fully defined methods.


 Defined methods of java are also known as concrete/ implemented methods.
 Once the class is concrete we can create an object of that class directly.

An Abstract class is one which contains some defined methods plus some undefined
methods. Undefined methods of java are known as abstract or un implemented
methods. Once the class is abstract, whose class object cannot be created / instantiated
directly but it can be instantiated indirectly.

Abstract Method: A method is said to be an abstract if which does not contain method
body / definition but it contains only prototype/declaration.

In order to make undefined method as abstract method the declaration


of the method must be preceded by a keyword ‘abstract’.

Syntax:

abstract return type methodName(list of parameters if any);

Ex: abstract void sum ();

Note: abstract methods always make us to understand what a method can do?

But we cannot get How a method can be done?


urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 abstract methods are always meant for general purpose or common purpose.
 Once the class contains abstract method(s) then that class is known as abstract
class.
 To make the class as abstract we use a keyword ‘abstract’ before the class
definition.

Syntax:

abstract class <ClassName>

{ …..

abstract return type methodName(list of parameters if any);

……

Eg: abstract class Operation

abstract void sum();

Since the class operation is an abstract class whose object cannot be created directly but
it can be created indirectly.

Operation op=new Operation(); // In Valid

In java programming abstract classes are always reusable by any number of


subclasses.

An object of abstract class=An Object of its Sub Class

Or

=An Object of that class which extends an abstract class.

Note: Abstract classes of java make use of polymorphism along with method
overriding and dynamic binding.

Program: /* Abstract Class Example */

abstract class operation{ abstract void sum(); }


class isum extends operation{ int a,b,c;
void sum() { a=100; b=200;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
c=a+b;
System.out.println("int sum="+c);
}
}
class fsum extends operation { float a,b,c;
void sum() { a=100.25f; b=200.75f;
c=a+b;
System.out.println("Float Sum="+c);
}
}
class abdemo { public static void main(String args[]) {
//operation op=new operation(); invalid
operation op;
op=new isum();
op.sum();
op=new fsum();
op.sum();
}
}

Note: Abstract classes are not ‘final’

 Abstract classes are always reusable since they contain common purpose
methods.

Abstract Base Class and Abstract Derived Class:

Abstract Base Class: An abstract base class is one which contains logical
representation of abstract methods which are inherited from abstract base class.

With respect to abstract base class and abstract derived class we cannot create an
object directly but we can create indirectly.

 If the derived class inherits ‘n’ number of abstract methods from abstract base
class and if the derived class is not defining at least one abstract method then the
current derived class is known as abstract and whose definition must be made
abstract by using ‘abstract’ keyword.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 If the derived class defines all n –number of abstract methods then the current
derived class is known as concrete derived class.
 Both abstract base class and abstract derived class are always re usable by
derived classes.

Program:

abstract class c1 {
abstract void f1();
abstract void f2();
}
abstract class c2 extends c1 {
void f1() {
System.out.println("F1 Defined in c2");
}
}
class c3 extends c2 {
void f2() {
System.out.println("F2 Defined in C3");
}
void f1() {
super.f1();
System.out.println("F1 Defined in c3");
}
void f3() {
System.out.println("F3 defined in c3");
}
}

class abdemo1 {
public static void main(String args[]) {
System.out.println("With Respect to C3");
c3 o3 = new c3();
o3.f1();
o3.f2();
o3.f3();
System.out.println("With Respect to C2");
// c2 o2=new c2(); invalid
c2 o2;
o2 = new c3();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
o2.f1();
o2.f2();
// o2.f3(); in valid
System.out.println("With Respect to C1");
// c1 o1=new c1(); invalid
c1 o1;
o1 = new c3();
o1.f1();
// o1.f2();invalid
// o1.f3(); invalid
}
}
Note: We can make a concrete class as abstract if require. For
that we need to place an abstract keyword in front of class
definition.

Null Body methods are those which contain method definition but
there is no block of statements. Hence in java null body methods
are always overridden in derived classes.

Interfaces:
The concept of interfaces can be developed by using a keyword ‘interface’.
The concept of interface supports multiple inheritance.
The scope of interfaces is more than scope of abstract classes.
Definition: An interface is a collection of general purpose methods and general purpose
data members (or) is a collection of public static final data members and public abstract
methods (or) it is a construct which contains purely abstract methods and common
purpose data members;

Syntax:
interface <interface name>
{

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
variable declaration cum intialization;
methods declaration;
}
 interface is a keyword which is used for developing user defined data types.
 An Object of interface cannot be created directly, but it can be created indirectly.
 All the variables in the interface must be initialized since they are meant for
common purpose. Hence all the variables of interface are by default belongs to
public static final xxx data members. Hence xxx represents data type, variable
name and variable value.
 Whatever the methods we are using in the interface are undefined methods and to
make them as abstract, java programmer need not to use a keyword abstract
explicitly.
 Since the methods of interface can be accessed by everybody, explicitly we need
not write a keyword ‘public’.
 Therefore all the methods of interface are default belongs to public abstract
methods.
 All the features of interface are by default treated as Universal General Purpose
Reusable features.
 Note: It is always recommended to keep all common purpose methods in
interfaces only but not in abstract classes.
Eg:
interface i1
{ int a=10; // public static final int a=10;
int b=20; // public static final int b=20;
void f1(); // public abstract void f1();
void f2(); // public abstract void f2();
}
Note:
 Interfaces definition should not contain main();
 Interfaces should not contain constructors
 Interfaces are by default abstract only
 Interfaces are not final since they are re usable by any number of subclasses.

Inheriting the features of interface(s) to class:

[abstract] class <ClassName> implements <intf1>,<intf2>...<intfn>


{
variable declaration;
methods definition/declaration;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}
 <ClassName> represents name of the derived class, <intf1>, <intf2> …,<intfn>
represents list of interfaces.
 ‘implements’ is a keyword used for inheriting the features either from one or
more than one interface into the derived class plus it improves the functionality of
derived class.
 If the derived class inherits n number of abstract methods from interface(s) and if
the derived class is not defining at least one abstract method then the current
derived class must be made as abstract by ‘abstract’ keyword.
 If the derived class defines all the abstract methods then the derived
class is known as concrete class.
 One class can ‘extends’ one class at a time. But one class can implements
multiple interfaces.
Example:
interface i2 {
void f1();
}
interface i3 {
void f2();
}
class C11 implements i2, i3 {
public void f1() {
System.out.println("F1 Defined in C11 Class");
}

public void f2() {


System.out.println("F2 Defined in C11 Class");
}
}
public class InterDemo {
public static void main(String[] args) {
// i2 o2=new i2(); invalid
i2 o2;
o2 = new C11();
o2.f1();
// o2.f2(); in valid
i3 o3 = new C11();
// o3.f1(); invalid
o3.f2();
}
}
Interface Inheritance:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
It is a process of getting the features from either one or more than one interface to
another interface.
Syntax:
interface <intf1> extends <intf2>,<intf3>,…,<intfn>
{
Variable declaration cum initialization;
Methods declaration;
}
One class can extends only one class at a time where as one interface can extends
either one or more than one interface.
Syntax for Inheriting features from base class, various Interfaces to the
derived class:

[abstract] class <classname2> extends <classname1> implements


<intf1>,<intf2>..
{
variable declaration;
methods definition;
}
In the above syntax <classname1> is a base class, <classname2> is a derived class
respectively.
When we use both implements & extends keywords in a single java program, we must
use always extends and later we must use implements keyword.

Program:
interface i1 {
void f1();
}
interface i2 extends i1 {
void f2();
}
abstract class c1 {
void f3() {
// Null Body
}
}
abstract class c2 extends c1 implements i2 {

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void f1() {
System.out.println("F1 Defined in C2");
}
void f3() {
System.out.println("F3 Redefined in C2");
}
}
class c3 extends c2 {
public void f2() {
System.out.println("F2 Defined in C3");
}
public void f1() {
System.out.println("F1 Redefined in C3");
}
void f3() {
System.out.println("F3 redefined in in C3");
}
void f4() {
System.out.println("F4 Special in c3");
}
}
class inter2 {
public static void main(String args[]) {
System.out.println("With Respect to C3");
c3 o3 = new c3();
o3.f1();
o3.f2();
o3.f3();
o3.f4();
System.out.println("With Respect to C2");
c2 o2 = new c3();
o2.f1();
o2.f2();
o2.f3();
// o2.f4(); invalid
System.out.println(" with respect to C1");
c1 o1 = new c3();
// o1.f1(); invalid
// o1.f2(); invalid
o1.f3();
// o1.f4(); invalid
System.out.println(" W r to I2");
i2 io2 = new c3();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
io2.f1();
io2.f2();
// io2.f3(); invalid
// io2.f4(); invalid
System.out.println("W r To I1");
i1 io1 = new c3();
io1.f1();
// io1.f2(); invalid
// io1.f3();
// io1.f4();
}
}
Packages:
A package is a collection of classes, interfaces and sub packages. A sub package is again
contains collection of classes, interfaces and sub sub packages.
 Whenever the class/interface is common for much number of java programmers,
those classes & interfaces are recommended to keep into the package.
 Advantages:
 Application Development Time is less
 Redundancy of code is reduced. Hence we get consistent result and faster
execution.
 Every application takes less amount memory space. Hence we get high
performance.
Types of packages in Java:
In java programming we have 2 types of packages, they are 1) Predefined Packages
2) User / Custom defined packages.
Predefined Packages: Predefined Packages are those which are developed by Sun
Micro Systems and supplied as part of JDK to deal with Universal Requirements.
All the Predefined Packages of java are compressed in a single file called “rt.jar” , the
file rt.jar is located in JDK/JRE/LIB folder.
User Defined Packages: User Defined Packages are those which are developed by java
programmer and they are supplied as a part of their project to deal with common
specific requirements.
Types of Predefined Packages:
As a part of J2SE we have 8 essential packages. They are
java.lang.*: This package is used for achieving language functionalities such as
 Displaying Data on to the console
 Getting the command line arguments
 Obtaining Garbage Collector
 Conversion of data from String into fundamental and fundamental into String.
 Dealing with runtime errors.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Developing multi threading applications etc..
java.awt.*: This package is used for developing front end GUI / Windows applications.
This package contains various classes and interfaces which allows us to create various
GUI components.
Eg: Button b1=new Button(“save”);
Awt Stands for Abstract Windowing Tool Kit.
java.awt.event.*: event is a sub package of awt package. The event package contains
various classes and interfaces which provides life/behavior/functionality to the GUI
components.
Hence to develop a full pledged front end application we must deal with java.awt.* and
java.awt.event.* packages.
java.io.*: This package is used for dealing with file operations in file programming.
Some of the file operations are
 Opening a file either in read/write mode.
 Modifying data from the file
 Deleting data from the file
 Inserting data into the file etc...
java.applet.*: This package is used for developing distributed applications. This
package contains only one class known as applet.
Applet: An applet is a java program which runs in the context of browser / world wide
web.
Limitations of Applets:
 Applets bring virus from the server to the local machine.
 Applets are unable to provide enough security to prevent the confidential
information from unauthorized users.
java.net.*: This package is used for developing Client /Server applications or network
oriented applications the limitation of this package is that we are able to develop only
intranet applications but not internet applications.
java.text.*: This package is used for formatting of text, in other words it is used for
formatting Date and Time according to client requirements.
java.util.*: This package contains various classes and interfaces which improves the
performance of java applications. This package is also known as Collection Framework.
Collection Framework is a standardized mechanism of grouping of different type or
similar type of values into a single variable. This single variable is known as Collection
Framework variable.
User Defined Packages:
User Defined Packages are those which are developed by java programmer
and they are supplied as a part of their project to deal with common specific
requirements.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Whenever the class/interface is common for much number of java
programmers, those classes & interfaces are recommended to keep it in our package i.e.
User Defined Package.
Each and every class and interface of java must belong to a package. All the
predefined classes & interfaces are belonging to predefined packages. If we develop any
user defined class or interface and if they are not belong to any user defined package
then JVM will assume its own package called “NONAME” to keep the set of user defined
classes and interfaces.
Creating user defined package is nothing but creating it as directory / folder in
the current working machine.
Syntax for creating Userdefined Packages:
package packname;
> package is a keyword used for creating user defined packages;
package pack1.pack2.pack3…..packn;
Here pack2 and pack3 and packn are sub packages;
Name of the packages must be java valid identifiers names.
ex:
package p1;
package p1.p2;
Rule:
When we use any package statement in the java program it should be always
used as first executable statement in the java program.

Steps or Guidelines:
 Choose the appropriate package name and ensure the package statement must be
the first executable statement.
 Choose the ClassName or interface name and ensure whose modifier must be
public.
 The modifiers of the constructors of the class must be public.
 The modifiers of the methods of the class/interface must be public.
 Whichever class/interface we are writing in the package that name must be given
as filename with an extension of .java
Note:
At any point of time either we need to write the class or we need to
write the interface with in the package but not both of them at a time.
Syntax for compiling package classes and interfaces:
javac -d . ClassName/interfacename.java

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

-d is an option or switch which gives an indication to JVM saying that goto


ClassName/interface name.java, take the package name and create it as a directory
provided no errors present in ClassName/interface name.java and package name was
not created earlier.
> Which ever package is created as a directory that directory is treated as current
directory. Compile the java program and ensure .class file
> . Refers the current directory which represents copy the currently generated .class
files into the current directory. (Package name);
Eg:
>javac -d . Test.java ->
>javac -d . Itest.java ->
Tp consider this
Is a package
/
Test.class
Itest.class

Referencing package classes and interfaces:

1) Using import statement


2) Using fully qualified name approach

import statement: ‘import’ is a keyword used for importing either all the classes and
interfaces of a specific package or specific class or interface from the specific package.
import pname.*; importing all the classes and interfaces
import p1.p2.*;

Syntax 2: Importing a particular class or interface from a specific package


import p1.c1;
import p1.p2.I2;

Sample pgm:
package tp;
public class Test

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{ public Test()
{ System.out.println("Test constructor ");
}
public void display()
{ System.out.println("Test Disp");
}
}
Execution Logic Class:
import tp.Test;
class packdemo1
{
public static void main(String args [])
{ Test t1= new Test ();
t1.disp ();
}
Note: If any class contains main () then that class is not recommended to belong to
package since main () is defined according to individual requirement. If a class does not
contain any main () (treated as common class) then that class is recommended to place
in the package.

package mp;
public class Mul {
int n;
public Mul(int n) {
this.n = n;
}
public void table() {
for (int i = 1; i <= 10; i++) {
System.out.println (n + "*" + i + "=" + (n * i));
}
}
}
Execution Logic Class:
import mp.Mul;
public class packdemo2 {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
Mul m = new Mul(n);
m.table();
}
}
Example:
package ip;
public interface i1 {
void f1();
}
package cp;
public abstract class C1 {
public abstract void f2();
}
package cp;
import ip.i1;
public class C2 extends C1 implements i1 {
public void f1() {
System.out.println(" F1 Defined in C2 Class");
}
public void f2() {
System.out.println(" F2 Defined in C2 Class");
}
}

import ip.i1;
import cp.C1;
import cp.C2;
public class PackDemo4 {
public static void main(String[] args) {
System.out.println("With respect to C2 Class");
C2 o2 = new C2();
o2.f1();
o2.f2();
System.out.println("With respect to C1 Class");
C1 o1 = new C2();
// o1.f1(); in valid
o1.f2();
System.out.println("With respect to Interface ");
i1 io1 = new C2();
io1.f1();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// io1.f2(); in valid
}
}
Access Modifiers:
Access Modifiers are those which are applied before the class or interface. In java
Access Modifiers are of 3 types. They are
1) abstract
2) public
3) final
public abstract and public final can be possible.
abstract final (or) final abstract – Not Possible.
Access Specifiers:
In Java we have 4 types of Access Specifiers are there.
1) private
2) default (it’s not a keyword remember)
3) protected
4) public
Access Specifiers are always applied before the data members and methods.
Access Specifiers are always make us to understand how to access the data / methods
within the package (class-class, interface-interface, and interface-class) and across the
package (class-class, interface-interface, interface-class).
Access Specifier can be either private or protected or public. If we are not
writing any Access Specifier then JVM by default treats it as ‘default’ access Specifier.
[access Specifier] [static] [final] data type v1[=val1],v2[=val2],…, vn[=valn];
Eg: public static final float p1=3.147f; for the method also same style of syntax

String Handling:
Character: A character is an identifier which is enclosed with in single quotes
eg: 'a','$','10'
Characters are represented by a data type called char.
String:
A String is a sequence of characters enclosed with in double quotes;
Eg: "java"
In java we have two types of classes to deal with strings.
They are
1) java.lang.String class
2) java.lang.StringBuffer class

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Differences Between String and StringBuffer:

SNO String StringBuffer

1 The content of String object cannot be The content of StringBuffer can be


modified Modified

2 When we create an object of String class When we create an object


we get '0' bytes as an additional memory StringBuffer we get 16 additional
space characters memory space

3 String object is treated as immutable StringBuffer object is treated as


object Mutable object

java.lang.String class API:


Constructors:
1) String ();
This constructor is used for creating an object of String class with empty content
ex: String s=new String();
System.out.println(s); // nothing will be printed
2) String (String):
This constructor is used for creating an object of String class with some content.
String s="java";
String s1=new String(s);
System.out.println(s); //java
System.out.println (s1); //java

3) String (char []):


This constructor is used for converting array of characters into String
eg: char ch[]={'J','A','V','A'};
String s=new String (ch);
System.out.println(s); //JAVA
4) String (StringBuffer):
Used for converting StringBuffer object into String object i.e. mutable object into
immutable object.
Eg: StringBuffer sb=new StringBuffer ("java");
String s=new String (sb);
Instance Methods:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Instance methods of a String class can be accessed by object of String Class
public final int length ();To determine number of characters in the String Object.
Eg: 1) String s="java";
int no=s.length ();
Sop (no); //4
2) public final String trim();
This method is used for eliminating leading and trailing spaces.
String s=" JavaWorld ";
String s1=s.trim();
Sop (s1.length()); //9
3) public final String concat(String);
Concatenate to strings i.e. target String is concatenated with Source String
String s1="java";
String s2="program";
String s3=s1.concat(s2);
Sop(s3); // javaprogram
Note:
String s1="java";
String s2="prog";
String s3=s1+s2;
Sop(s3); //javaprog

4) public final String toLowerCase();


public final String toUpperCase();
Ex: String s1="JAVA";
String s2=s1.toLowerCase();
String s3=s2.toUpperCase();
Sop(s2); // java
Sop(s3); //JAVA
5) public final String substring(int);
This method is used for obtaining the part of the String by specifying the starting
position.
public final String substring(int ,int );
Obtaining the range of characters by specifying starting and ending position
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
String s2="Hello World";
String s3=s2.subString(6);
Sop(s3); // World
String s4=s2.substring(3,7);
Sop(s4); // lo wo
6) public final char[] tocharArray();
This method is used for converting String Object data into Array of characters
Eg: String s="java";
char ch[]=s.toCharArray();
7) public final boolean equals (String);
Ex; String s1="JAVA";
String s2="java";
boolean b=s1.equals (s2); // false

String s3="JAVA";
b=s1.equals (s3);
Sop(b); //true
8) public final boolean equalsIgnoreCase(String);
String s1="JAVA";
String s2="java";
boolean b=s1.equalsIgnoreCase (s2); // true

String Example Program:


public class Demo {
public static void main(String[] args) {
// String Class Constructors
String a = new String();
System.out.println(a); // nothing will be printed
String c = "JAVA";
String sb = new String(c);
System.out.println(sb);
char d[] = { 'J', 'A', 'V', 'A' };
String e = new String(d);
System.out.println(e);
StringBuffer br = new StringBuffer("Challa Srinivasa Reddy");
String f = new String(br);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(f);
// Instance Methods of a String Class
String s1 = " Java World ";
System.out.println(s1.length());
String s2 = s1.trim();
System.out.println(s2.length());
String s11 = "java";
String s22 = "program";
String s33 = s11.concat(s22);
System.out.println(s33);
String s111 = "java"; String s222 = "prog";
String s333 = s111 + s222;
System.out.println(s333);
System.out.println(s2.substring(7));
System.out.println(s2.substring(7, 10));
char ch[] = s333.toCharArray();
for (int i = 0; i < ch.length; i++)
System.out.println(ch[i]);
System.out.println(s333.toUpperCase());
System.out.println(s2.toLowerCase());
String S1 = "JAVA";
String S2 = "java"; String S3 = "JAVA";
boolean b = S1.equals(S2); boolean b1 = S1.equals(S3);
System.out.println(b);
System.out.println(b1);
boolean b11 = S1.equalsIgnoreCase(S2);
System.out.println(b11);
}
}
Sample Program:
class StringDemo1 {
public static void main(String args[]) {
System.out.println("welcome".length());
String s = new String("welcome");
System.out.println(s.length());
System.out.println(s.charAt(5));
String s21 = "computer";
System.out.println(s21.getBytes());
String s1 = "Hello";
String s2 = "hellow";
String s3 = "welcome";
String s4 = "Hello";
String s5 = "HELLOW";
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(s1 + "equals" + s2 + "--->" + s1.equals(s2));
System.out.println(s1 + "equals" + s3 + "--->" + s1.equals(s3));
System.out.println(s1 + "equals" + s4 + "--->" + s1.equals(s4));
System.out.println(s1 + "equals" + s5 + "--->" + s1.equals(s5));
System.out.println(s1 + "equalsIgnorecase" + s2 + "-->"
+ s1.equalsIgnoreCase(s2));
/*
* equals() method compares the character by character
inside a string object
*
* == operator compares two object references to see
whether they refer to the same instance or not
*/
String s11 = "Hello";
String s12 = new String(s11);
String s13 = s12;
System.out.println(s11 + "equals" + s12 + "->" +
s11.equals(s12));
System.out.println(s11 + "==" + s12 + "--->" + (s11 == s12));
System.out.println(s12 + "equals" + s13 + "--->" +
s12.equals(s13));
System.out.println(s12 + "==" + s13 + "--->" + (s12 == s13));
System.out.println(s1.indexOf('i')); // -1bcz i (not there)
System.out.println(s1.indexOf('l')); // 2 ‘l’ is 3 char in that
}
}

StringConstructors Alone:
class StringConstructors {
public static void main(String args[]) {
String s1 = new String(); // empty string
char chars[] = { 'h', 'e', 'l', 'l', 'o' };
String s2 = new String(chars); // s2="hello";
byte bytes[] = { 'w', 'o', 'r', 'l', 'd' };
String s3 = new String(bytes); // s3="world"
String s4 = new String(chars, 1, 3);
String s5 = new String(s2);
String s6 = s2;
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
}
}
Sample Programs and Some Additional Functions:
String a[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug","Sep", "Oct", "Nov", "Dec" };
for (int j = 0; j < a.length; j++)
{
for (int i = j + 1; i < a.length; i++) {

if (a[i].compareTo(a[j]) > 0) {
String t = a[j];
a[j] = a[i];
a[i] = t;
}
}
System.out.println(a[j]);
}

Sample:
class RegionMatchesDemo
{ public static void main(String args[])
{
String str="Good, good!";
boolean b1,b2,b3,b4;
b1=str.regionMatches(6,"Good",0,4);
b2=str.regionMatches(true,6,"Good",0,3);
b3=str.regionMatches(true,6,"Good",0,4);
b4=str.regionMatches(false,6,"Good",0,4);
System.out.println("b1="+b1);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("b2="+b2);
System.out.println("b3="+b3);
System.out.println("b4="+b4);
/* Some specilized forms
boolean startsWith(String str)
boolean endsWith(String str)
*/
String str1="welcome";
System.out.println(str1.startsWith("wel"));
System.out.println(str1.endsWith("come"));
// overloaded form
System.out.println("welcome".startsWith("come",3));
System.out.println("welcome".startsWith("come",4));
}
}

StringBuffer Class:
StringBuffer is a class which is used for handling String data.
Whenever we create an object of StringBuffer by default we get
16 additional characters memory space. The content of StringBuffer can be changed.
Hence StringBuffer object is known as Mutable object.

StringBuffer Class API:

Constructors:

StringBuffer();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

StringBuffer(StringBuffer);

StringBuffer(char []);

StringBuffer(String);

The above constructor is used for converting String object into StringBuffer object
I.e. converting immutable object into mutable object.
Eg: String s="java";
StringBuffer sb=new StringBuffer(s);
Sop(sb);
Instance Methods:

1) public final int length ();


2) public final int capacity();
This method is used for determining capacity of the StringBuffer(length+ 16
characters additional space)

Eg:
String s="java";
StringBuffer sb=new StringBuffer(s);
Sop(Length="+sb.length());
Sop(Capacity="+sb.capacity());
3) public final StringBuffer reverse();
This method is used for obtaining sentence reverse of StringBuffer content
Eg: StringBuffer sb=new StringBuffer("java");
StringBuffer sb1=sb.reverse();
Sop(sb1);// avaj

4) public final StringBuffer substring(int);

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5) public final StringBuffer substring(int,int); similar to String Class functions
6) public final String toString():
This method is used for converting StringBuffer object into String object.
Ex:
StringBuffer sb=new StringBuffer ("java");
String s=sb.toString();
Sop(s);
Sample Program:
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Jampani LTD");
System.out.println(sb);
sb.append(" Hyderabad");
System.out.println(sb);
sb.insert(8, "Pvt ");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.delete(17, 20);
System.out.println(sb);
sb.append(sb);
System.out.println(sb);
}
}
Program:
public class StringBufferApp {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer(" is ");
sb.append("Hot"); // concatenation
sb.append('!');
sb.insert(0, "Java");
sb.append('\n');
sb.append("This is ");
sb.append(true);
System.out.println(sb);
System.out.println(sb.charAt(6));
sb.setCharAt(21, 'T');
sb.append('\n');
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
sb.append("Java is #");
sb.append(1);
System.out.println(sb);
System.out.println("Converting StingBuffer Object to
String");
String s = sb.toString();
System.out.println(s);
}
}
Out put:
Java is Hot!
This is true
s
Java is Hot!
This is True
Java is #1
Converting StingBuffer Object to String
Java is Hot!
This is True
Java is #1

Program:

import java.io.BufferedReader;
import java.io.InputStreamReader;
class StringBuffer1 {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String str;
try {
System.out.print("Enter your name: ");
str = in.readLine();
str += " This is the example of SringBuffer class and it's
functions.";
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// Create a object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0, str.length());
// append()
strbuf.append("Hello");
strbuf.append("World");
// print HelloWorld
System.out.println(strbuf);
// insert()
strbuf.insert(5, "_Java ");
// print Hello_Java World
System.out.println(strbuf);
// reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf);
// print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf);
// print Hello_Java World
// setCharAt()
strbuf.setCharAt(5, ' ');
System.out.println(strbuf);
// print Hello Java World
// charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));
// print J
// substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3, 7));
// print lo J
// deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);
// print Helo java World
// capacity()
System.out.print("Capacity of StringBuffer object : ");
System.out.println(strbuf.capacity()); // print 83
// delete() and length()
strbuf.delete(6, strbuf.length());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(strbuf);
// no anything
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Out Put:
Enter your name: Challa Srinivasa Reddy
Challa Srinivasa Reddy This is the example of SringBuffer class
and it's functions.
HelloWorld
Hello_Java World
Reversed string : dlroW avaJ_olleH
Hello_Java World
Hello Java World
Character at 6th position : J
Substring from position 3 to 6 : lo J
Helo Java World
Capacity of StringBuffer object : 83
Helo J

Exception Handling:
Runtime Errors of java are known as Exceptions.
Definition: The process of converting system error messages into user friendly messages
is known as Exception Handling.
When we pass any invalid input to a java program, then there is a possibility
of generating runtime errors.
When exceptions happen in java program, automatically program execution
will be abnormally terminated and control comes out of the normal flow of the program.
Java contains distinct feature called Exception handling to build strong
applications in real time environment.
It is always recommended to the programmers to convert system error
messages into user friendly messages by using the feature called Exception Handling.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Types of Exceptions:
In Java we have 2 types of Exceptions. They are
1) Predefined / Built in Exceptions
2) User /Custom Defined Exceptions
Predefined Exceptions:
Predefined Exceptions are those which are developed by Sun Micro Systems
and supplied as a part of JDK to deal with Universal Problems. Some of the Universal
problems are Division by Zero, Invalid Bounds of the Array, Invalid Format of Number
etc…
User /Custom Defined Exceptions:
User Defined Exceptions are those which are developed by java programmer and
supplied as a part of their project to deal with common specific problems such as
negative ages, negative salaries, invalid number of password characters etc..
Types of Predefined Exceptions:
Predefined Exceptions are of 2 types. They are
a) Asynchronous Exceptions
b) Synchronous Exceptions
Asynchronous Exceptions: are those which deal with Hardware Problems such as
power failures, keyboard, mouse, and mother board failures, memory problems etc.
To handle all Asynchronous exceptions there exist a predefined super class
called java.lang.Error
Synchronous Exceptions: are those which deals with programmatic errors.
Synchronous Exceptions are divided into 2 types.
They are
1) Checked Exceptions 2) Un-Checked Exceptions

Checked Exceptions: are those which are sub classes of java.lang.Exception class.
They are related to secondary memory.
Eg: FileNotFoundException, ClassNotFoundException, IOException
Un-Checked Exceptions:
are those which are sub classes of java.lang.RuntimeException
They are related to primary memory RAM
EG: ArithematicException, NumberFormatException, ArrayIndexOutOfBoundsException
Exception Handling Hierarchy Chart:
You know already java.lang.Object is a Super Class for all the Java Predefined /
User Defined Classes.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

How Exception Occurs Internally:


When any exception happens in java program the following sequence of steps will be
performed internally.
Steps:
 User inputs relevant input to java program
 JVM processes the java program by making use of relevant input and it generates
relevant output.

1. User inputs irrelevant data to the java program.


2. JVM cannot process the java program with irrelevant input and it contacts JRE.
3. JRE is further contacting to java.lang.Throwable for obtaining the type of
exception.
4. java.lang.Throwable class decides the type of Exception and gives to JRE;
java.lang.Throwable is the Super class for all the exceptions in java.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
5. JRE is sending the type of exception to java Exception API
6. A) B) C) Java Exception API executes either java.lang.Error (A for Asynchronous),
or java.lang.Exception (B for checked) or java.lang.RuntimeException (C for
Unchecked) and obtains the specific exception.
7. Java Exception API gives an appropriate exception class to JRE
8. JRE gives appropriate Exception class to JVM
9. JVM creates an object of appropriate Exception Class
Eg: ArithematicException ae=new ArithematicException(“/by Zero”);
10. JVM generates the System Error Message on the console which is not
recommended.
11. As a java programmer it is highly recommended to convert system error
messages into user friendly messages by making use Exception Handling.
Handling the Exception:
To handle runtime errors/exceptions we use the following five keywords.
1) try
2) catch
3) finally
4) throws
5) throw
Syntax for handling Exceptions:
try { Block of Statement(s); Which cause problems at runtime
}catch(TypeofException obj1)
{ Block of statement(s); Which provides user friendly messages
} catch(TypeofException obj1)
{ Block of statement(s); Which provides user friendly messages
}…
finally { Block of Statements which will be executed compulsorily; }
Write a java program which illustrates the concept of try block, catch block and
finally block.
import java.io.*;
import java.lang.*;
import java.lang.RuntimeException.*;
class Exp1
{ public static void main(String args[])
{
try{ String s1=args[0];
String s2=args[1];
int x=Integer.parseInt(s1);

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int y=Integer.parseInt(s2);
int z=x/y;
System.out.println("Division="+z);
}catch(ArrayIndexOutOfBoundsException ab)
{ System.out.println("Pass Sufficient values from command prompt");
}catch(NumberFormatException nfe)
{ System.out.println("Pass Numerical Value");
}catch(ArithmeticException ae)
{ System.out.println("Dont enter zero for denominator");
}
finally
{
System.out.println("I am from finally");
}
}
}
Try block:
1) This is the block which contains block of statements which causes problems at
runtime.
2) When an exception occurs during the program execution in the try block, program
execution is abnormally terminated and control goes to an appropriate catch block
by skipping the rest of the statements.
3) After executing appropriate catch block control never goes to try block even we
use return statement in catch block.
4) Catch block must be followed immediately after try block, i.e. no intermediate
statements are allowed between try and catch blocks.
5) Each and every try block must contain at least one catch block but it is
recommended to write multiple catch’s to provide more user friendly messages.
6) One try block can contain another try block, i.e. nested try blocks can be possible.
Catch Block:
1) This is the block in which we write block of statements which provide user friendly
messages.
2) At any point of time only one catch block will execute out of n-number of catch
blocks.
3) Catch block will executes whenever an exception occurs in the try block.
4) In the catch block we declare an object of appropriate exception class and it will
internally referenced by the JVM whenever an exception taken place.
Finally Block:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) This is the block in which we write the block of statements which will relinquish
(releasing) the resources (Data Base, Files) which are obtained in try block.
2) Writing finally block is optional
3) Finally block will execute compulsorily.
Note:
1) When an exception occurs then a part of try block will execute, one appropriate
catch block and finally block will execute.
2) When no exception occurs then complete try block and finally block will execute
but no catch block will execute.
throws keyword:
throws is a keyword which gives an indication to the calling function to keep the called
function under try and catch blocks.
Whenever we develop any common method for group of programmers and if
the common method is having any problematic statements then we need to write the
type of exceptions as a part of method heading with a keyword throws.
Syntax of Throws Keyword:
return type methodname(list of formal parameters if any)throws Type of
Exception1,Type of Exception2, ...Type of Exception n
{
Block of Statement(s);
}

Note: List Exceptions Occurred in method body

Write a java program which illustrates the concept of throws keyword.


class Exp2
{
public void div(int x, int y)throws NumberFormatException,ArithmeticException
{ int z=x/y;
System.out.println("Division in Exp1:"+z);
}
}
class ExpThrows
{
public static void main(String args[])

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
Exp2 o1=new Exp2();
try
{ o1.div(x,y);
}
catch (NumberFormatException ne)
{ System.out.println ("Pass only Numeric values");
}
catch (ArithmeticException ae)
{ System.out.println ("Dont enter for denominator");
}
}
}
Finding the Details about un-known Exceptions:
When we write any java program there is a possibility of generating n number
of Runtime errors and those errors may not be known to java programmer. In order to
find the details about unknown exceptions we have 3 ways. They are
1) By using an object of java.lang.Exception
2) By using printStackTrace()
3) By using getMessage()

Using an object of java.lang.Exception:


Since Exception class is the super class for all exceptions in java, whose object will point
to any number of specific exceptions which are occurring in the java program. An object
of Exception class displays name of the exception and nature of the message.
Ex: try { ….
int x=Integer.parseInt(10x);

}catch(Exception e)
{ System.out.println(e); }
Message:
java.lang.NumberFormatException: For input string: "10x"

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Name of the Exception Nature of the Exception
Sample Program:
public class Exp1 {
public static void main(String[] args) {
try {
int x = Integer.parseInt("10x");

} catch (Exception e) {
System.out.println(e);
System.out.println(e.getMessage());
e.printStackTrace ();
}
}
}
Using getMessage ():
This is the method which is available in java.lang.Throwable class and it is further
inherited into java.lang.Exception and java.lang.Error classes.
Using this method we can display only nature of the message. The prototype
of the getMessage () is given bellow.
java.lang.Throwable public String getMessage();
Ex: try { …. int x=Integer.parseInt(10x);

}catch(Exception e)
{ System.out.println(e.getMessage()); }
Message: For input string: "10x"
Nature of the Exception
Using printStackTrace()
This is the method which is available in java.lang.Throwable class and it is further
inherited into java.lang.Exception and java.lang.Error classes.
Using this method we can find name of the exception, nature of the exception,
and the line number where the exception happens. The prototype of printStackTrace() is
given bellow.
java.lang.Throwable public void printStackTrace()
Ex:
try { …. int x=Integer.parseInt(10x);

}catch(Exception e)
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
{
System.out.println(e.printStackTrace()); // Invalid We cannot use like this
e.printStackTrace();
}
Message:
java.lang.NumberFormatException: For input string:"10x" at line No: 2
Name of the Exception Nature of the Exception Line No

throw keyword:
throw is a keyword which is used for throwing the exceptions which are occurring as a
part of method body. It can also be used to through the predefined exceptions by
changing the existing nature of the message.

Syntax1:

<ClassName> objname=new <ClassName(message);>


throw objname;

Class name here represents name of the class and it should be subclass of either
java.lang.Exception or java.lang.RuntimeException

Syntax2:
throw along with throws keyword

return type methodName (list of formal parameters if any)throws


<classname1>,<classname2>,...
{ if (testcond1)
{
<classname1> obj1=new <classname1 (msg);>
throw (obj1);
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
if(Tesdcond2)
{
<classname2> obj2=new <classname2 (msg);>
throw(obj2);
}
...
...
if(Tesdcondn)
{
<classname n> objn=new <classname n(msg);>
throw(objn);
}
}
<classname1>, <classname2>,… , <classnamen> represents list of Exception
Classes and they are subclasses of either java.lang.Exception or
java.lang.RuntimeException.

Write a java program which illustrates the concept of throw and throws
keywords?

class Ex3
{ public void div(int x,int y)throws NumberFormatException,ArithmeticException
{ if(y==0)
{
ArithmeticException ae=new ArithmeticException("Dont Enter Zero for Denominator");
throw(ae);
}
int z=x/y;
System.out.println("Division in Ex3:"+z);
}

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
}class Ex4
{ public static void main(String args[])
{ int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
Ex3 o3=new Ex3();
try { o3.div(x,y);
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
}
}
Write the differences between throw and throws keyword:

SNO throw throws

1 throw is a keyword used for throwing throws is a keyword which gives an


exceptions which are occurring in the indication to the calling function to keep
method body the called function under try and catch

2 throw is a keyword must be used as throws keyword must be used always as a


a part of method body only part of method heading only.

3 When we use throw keyword within When we use throws keyword as a part of
the method body, it is mandatory for method heading it is optional for the java
the java programmer to use throws programmer to use throw keyword as a
keyword as a part of method part of method body.
heading.
package UserDefinedException;
@SuppressWarnings("serial")
class InvalidAmountException extends Exception {
InvalidAmountException() {
super();
}
InvalidAmountException(String mesg) {
super(mesg);
}
}
class Bank { int accno, bal; String name;
void openAccount(int accno, int bal, String name)
throws InvalidAmountException {
if (bal < 1000)
throw new InvalidAmountException(

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
"Initial Balence should be more than 1000");
this.accno = accno;
this.bal = bal;
this.name = name;
}
void getBalence() {
System.out.println("Current Balence : " + bal);
}
void deposit(int amount) {
bal = bal + amount;
}
void withDraw(int amt) throws InvalidAmountException {
int d;
d = bal - amt;
if (d < 1000)
throw new InvalidAmountException("You should not withdraw if the remaining
balance is less than 1000");
bal = bal - amt;
}
}
public class BankTest {
public static void main(String args[]) {
Bank b = new Bank();
try {b.openAccount(101, 2000, "Srinivas");
b.getBalence();
b.deposit(500);
b.getBalence();
b.withDraw(1900);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
b.getBalence();
}
}
}
Collection Framework:

Collection frame work is the standardized mechanism of grouping either


similar or different type of values in a single variable. The single variable is known as
Collection Framework variable.

Q) Differences between collection framework and arrays?


Arrays:
1) Fixed size in memory
2) Arrays allows similar type of elements i.e. arrays of homogenous elements
3) Arrays are treated as static
Collection Framework:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) Dynamic Size in nature
2) Allows both similar type of elements and different type of elements
3) Treated as Dynamic
Aims &Goals:
1) Collection Framework provides effective performance to the java applications
2) Collection Framework provides Extendibility
3) Collection Framework provides Adaptability
4) Collection Framework is treated as algorithmic oriented i.e. Collection Framework
contains inbuilt sorting and searching and data structures techniques
In order to achieve the goals of Collection Framework we must use some of
predefined classes and interfaces which are present in java.util.* package.
We must import java.util.* package
Types of collection framework:
1) 1-D / Single Collection Framework
2) 2-D / Double Collection Framework

1-D / Single Collection Framework:


1-D / Single Collection Framework is one in which data is organizing either in the form
of row or in the form of column in a single variable but not in the form of (key, value)
pairs.
1-D / Single Collection Framework interfaces:
1) java.util.Collection
2) java.util.List
3) java.util.Set
4) java.util.SortedSet

java.util.Collection:
1) It is available on top of hierarchy of all the collection framework interfaces.
2) An Object of Collection interface allows us to add duplicates.
3) Collection interface object displays the data in random order.
4) Collection interface object allows us to retrieve the data only in forward direction but
not in back word direction.
java.util.List:
1) An Object of List interface allows us to add the value either at specific position or
at end.
2) An Object of List interface allows us to add duplicates.
3) An Object of List interface displays the data in sorted order.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
4) An Object of List interface allows us to remove the data either in forward
direction or in back word direction or in both.
5) It allows multiple null values to be added.
Java.util.Set:
1) Set interface object allows us to add the value only at the end.
2) Set interface object does not allow duplicates.
3) Set interface object allows display the data in random order.
4) Set interface object allows retrieving the data in forward direction.
5) It allows only single null value.
java.util.SortedSet:
1) SortedSet interface object allows us to add the value only at the end.
2) SortedSet interface object does not allow duplicates.
3) SortedSet interface object allows display the data in sorted order.
4) SortedSet interface object allows retrieving the data in forward direction.

Some regularly used Methods in java.util.Collection Interface:


public int size():
This method is used for counting number of values present in Collection Framework
Variable.
****
public boolean add(Object):
This method is used for adding an object to Collection Framework Variable. As long as
we call this method with respect to Collection and List interface objects, this method
always returns true because of both of these interfaces allow adding duplicates. When
we call this method with respect to Set and SortedSet interfaces object and if we try to
add duplicates, then this method returns false, since both Set & SortedSet donot allow
duplicates.

public Iterator iterator ():


This method is used for extracting the data from Collection Framework variable.
Eg: arraylistB.add ("beginner");
arraylistB.add ("java");
arraylistB.add ("tutorial");
arraylistB.add (".");
arraylistB.add ("com");
arraylistB.add ("java");
arraylistB.add ("site");
// Iterating through the ArrayList to display the Contents.
Iterator i1 = arraylistB.iterator ();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.print ("ArrayList arraylistB --> ");
while (i1.hasNext()) {
Object obj=i1.next();
System.out.print (obj + " , ");
}
Iterator Interface:
An object of Iterator Interface is used for extracting the
data from any Collection Framework Variable When we create an
object of Iterator which is by default pointing to just before
the first element and it extracts the data only in forward
direction.
Methods:
public boolean hasNext(); Is used for determining whether
we have next element or not. This method returns true when the
collection framework variable contains next element otherwise
this method returns false.
public Object next(); Is used for obtaining an element of
collection framework variable provided hasNext() method returns
true.

Some regularly used Methods in java.util.List:


public void add(int, Object):
This method is used for adding an object to the List at the
specific position or at the end also.

l.add(l.size(),new Integer(50));

public Object get(int):


This method is used for obtaining an element from List by
passing the valid position.

public Object remove(int):


public void remove(Object):
public void removeAll():

Methods 1 & 1 are used for removing an element based on either


position or content. Method 3 is used for removing all elements
from collection framework variable.

public ListIterator listIterator():


This method is used for extracting data of List in both
back ward and forward directions.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Eg:
ListIterator li1 = arraylistA.listIterator();
while (li1.hasNext()) {
Object obj=li1.next();
System.out.print(obj + " , ");
}
Forward Direction:
Now Backward Direction:

ListIterator li1 = arraylistA.listIterator();


while (li1.hasPrevious()) {
Object obj=li1.previous();
System.out.print(obj + " , ");
}
ListIterator Interface:

ListIterator Interface is the sub interface of Iterator. An


object of ListIterator Interface used for extracting data in
both forward and backward directions. By default an object of
ListIterator Interface is pointing just before first element.
Methods:
public boolean hasPrevious();
public Object previous();

Method 1 returns true provided Collection Framework


Variable is having previous element otherwise it returns false.
Method 2 is used for obtaining previous element provided
method 1 returns true.

Example Program for List Interface: Here we are having Concrete


Classes for List Interface, they are LinkedList and ArrayList
Classes.
import java.util.*;
public class ListDemo {
public static void main(String[] args) {
List a1 = new ArrayList();
a1.add("Srinu");
a1.add("Vasu");
a1.add("Reddy");
System.out.println("Return Value of add
method:"+a1.add("Challa"));
/*
* void add(int index, Object obj);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
*/
a1.add(4,"java");
a1.add(1,"java1");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1+"\n");
List l1 = new LinkedList();
l1.add("Srinu");
l1.add(a1);
l1.add("Vasu");
l1.add("Reddy");
l1.add(a1);
System.out.println(l1.add("Challa"));
/*
* boolean addAll(int index,Collection c);
*/
System.out.println("\n Return value of
addAll():"+l1.addAll(2,a1));
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
/*
* Object get(int index)
Returns the object stored at the specified index within the
invoking collection.
*/
System.out.println("\nValue form get():"+l1.get(5));
/*
* int indexOf(Object obj)
* int lastIndexOf(Object obj)
*/
System.out.println("\n Value form
indexOf():"+l1.indexOf(a1));
System.out.println("\n Value form
lastIndexOf():"+l1.lastIndexOf(a1));
/*
* Object remove(int index)

*/
l1.remove(2);
System.out.println(" Object removed from 2 position
Successfully:" + l1);
/*
* Object set(int index, Object obj);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

*/
l1.set(0, "List");
System.out.print("\n Value is placed in position :" +
l1);
/*
* List subList(int start, int end);
*/
List l2=l1.subList(2, 6);
System.out.println("\n Sub list Elements are:"+l2);
System.out.println("ListIterator -FD");
ListIterator litr=l1.listIterator(); //Retriving the data
while(litr.hasNext())
{
Object obj2=litr.next();
System.out.println(obj2);
}
System.out.println("List Iterator-BD");
while(litr.hasPrevious())
{
Object obj3=litr.previous();
System.out.println(obj3);
}
Object obj=l1.get(2);
System.out.println("Element ="+obj);
}
}

Next Program:
@looping-through-a-collection-object

import java.util.ArrayList;
import java.util.Iterator;
public class CollectionDemo {
/**
* Example of iterating through a Collection object
*/
public void iterateCollection() {
ArrayList<String> list = new ArrayList<String>();
list.add("Monday");
list.add("Tuesdag");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
list.add("Wednesday");
list.add("Thursday");
list.add("Friday");
list.add("Saturday");
list.add("Sunday");
Iterator<String> iterator = null;
// Example 1:
iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
// blank line
System.out.println();
// Example 2:
for (iterator = list.iterator(); iterator.hasNext();) {
String element = iterator.next();
System.out.println(element);
}
// blank line
System.out.println();
// Example 3:
for (String element : list) {
System.out.println(element);
}
}
public static void main(String[] args) {
new CollectionDemo().iterateCollection();
}
}

Program: LinkedList Demo


/* Linked List Collections Framework */
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
class LinkedListDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
LinkedList ll = new LinkedList();
System.out.println("Size=" + ll.size());
System.out.println("Content=" + ll);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
ll.add(new Integer(10));
ll.add(new Integer(20));
ll.add(new Integer(30));
System.out.println("Size=" + ll.size());
System.out.println("Content=" + ll);
ll.addFirst(new Integer(5));
ll.addLast(new Integer(40));
System.out.println("Size=" + ll.size());
System.out.println("Content=" + ll);
System.out.println("Iterator -FD");
Iterator itr = ll.iterator(); // Retriving the data
while (itr.hasNext()) {
Object obj1 = itr.next();
System.out.println(obj1);
}
System.out.println("ListIterator -FD");
ListIterator litr = ll.listIterator(); // Retriving the data
while (litr.hasNext()) {
Object obj2 = litr.next();
System.out.println(obj2);
}
System.out.println("List Iterator-BD");
while (litr.hasPrevious()) {
Object obj3 = litr.previous();
System.out.println(obj3);
}
Object obj = ll.get(2);
System.out.println("Element =" + obj);
}
}

import java.util.LinkedList;
import java.util.List;
//Converting Linked List to Array
public class LtoA {
public void convertLinkedListToArray() {
List<String> theList = new LinkedList<String>();
//List theList=new LinkedList();
theList.add("Apples");
theList.add("Bananas");
theList.add("Oranges");
theList.add("Grapes");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
String[] fruits = theList.toArray(new String[0]);
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
public static void main(String[] args) {
new LtoA().convertLinkedListToArray();
}
}

//@convert-a-list-arraylist-to-an-array
import java.util.*;
public class LAA {
public void ListToArray() {
List<String> carList = new ArrayList<String>();
carList.add("Dodge");
carList.add("Chevrolet");
carList.add("BMW");
carList.add("Toyota");
String[] carArray = carList.toArray(new String[0]);

for (String car : carArray)


{
System.out.println(car);

}
}

public static void main(String[] args) {


new LAA().ListToArray();
}
}
Some Advanced Methods of List and Collections Class Methods:
import java.util.*;
public class ListExample {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
List list = new ArrayList();
list.add("Bernadine");
list.add("Elizabeth");
list.add("Gene");
list.add("Elizabeth");
list.add("Clara");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(list);

/*
* get()
*/
System.out.println("2: " + list.get(2));
System.out.println("0: " + list.get(0));
LinkedList queue = new LinkedList();
queue.addFirst("Bernadine");
queue.addFirst("Elizabeth");
queue.addFirst("Gene");
queue.addFirst("Elizabeth");
queue.addFirst("Clara");
queue.addLast("Srinu");
queue.add(0,"Reddy");
System.out.println(queue);
System.out.println(queue.contains("Srinu"));
/*
* public Object removeFirst();
* public Object removeLast();
*/
queue.removeLast();
queue.removeFirst();
queue.removeLast();
System.out.println(queue);
/*
* getFirst() & getLast() methods will return an Object
* public Object getFirst();
* public Object getLast();
*/
System.out.println("getFirst():"+queue.getFirst());
System.out.println("getLast():"+queue.getLast());
/*
* toString() method converts Collection Object values into
String values
*/
System.out.println( queue.toString());

/*
* toArray() method converts Collection object into Object
array
*/

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("******Usage of toArray()
Function******");
System.out.println(queue.toArray());
Object[] o1=queue.toArray();
for(int i=0;i<o1.length;i++)
{
System.out.println(o1[i]);
}
System.out.println("By For Each Loop");
for(Object i:o1)
{
System.out.println(i);
}
System.out.println();
// Checking emptiness of an ArrayList
System.out.println("Is arraylist empty? "
+ queue.isEmpty());
System.out.println();
// Checking for Equality of ArrayLists
ArrayList arraylistC = new ArrayList(queue);
System.out.println("queue.equals(arraylistC)? "
+ queue.equals(arraylistC));
System.out.println();
/*
* Collections class methods
*/
System.out.println("Collections Class Methods Output\n");
// Sort an ArrayList
System.out.print("Sorted ArrayList --> ");
Collections.sort(queue);
System.out.print(queue);
System.out.println();
// Reversing an ArrayList
System.out.print("Reversed ArrayList --> ");
Collections.reverse(queue);
System.out.println(queue);
System.out.println();
System.out.println();
// Shuffling the elements of an ArrayList in Random Order
Collections.shuffle(queue, new Random());
System.out.print("ArrayList after shuffling its elements--
> ");
Iterator i1 = queue.iterator();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
while (i1.hasNext()) {
System.out.print(i1.next() + " , ");
}
System.out.println();
/*
* Example for copy() method in Collections Class
*/
LinkedList queue1 = new LinkedList();
queue1.add("srinu");
queue1.add("vasu");
queue1.add("venkat");
queue1.add("java");
System.out.println(queue1);
System.out.println("********Collections Class copy()
Output\n");
Collections.copy(queue1,queue);
System.out.println(queue1);
/*
* public static int binarySearch(List list,Object key);
*/
System.out.println("********Collections Class
binarySearch(List list,Object key) Output\n");
int i=Collections.binarySearch(queue, "Gene");
System.out.println(i);
/*
* public static void swap(List list, int i,int j);
*/
System.out.println("********Collections Class swap(List list,
int i,int j) Output\n");
System.out.println(queue);
Collections.swap(queue, 0,2) ;
System.out.println(queue);

/*
* public static void fill(List list, Object obj);
*/
Collections.fill(queue, "Srinu");
System.out.println("Out Put for fill()");
System.out.println(queue);
/*
* public static Object min(Collection coll);
* public static Object max(Collection coll);
*/
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("min and max functions");
System.out.println(Collections.min(queue1));
System.out.println(Collections.max(queue1));
System.out.println("End");
/*
* clear(); method
*/
queue.clear();
System.out.println(queue);
}
}

Methods in java.util.Set:
The Set Interface does not contain any special methods
except Collection Interface methods. Even though the methods are
same in both Set and Collection Interfaces their implementation
is different in different classes since Collection interface
allows duplicates and Set interface does not allow duplicates.

Methods in java.util.SortedSet:

public Object first();


public Object last();

import java.util.*;
public class CollectionsDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
List a1 = new ArrayList();
a1.add("Srinu");
a1.add("vasu");
a1.add("Reddy");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
List l1 = new LinkedList();
l1.add("Srinu");
l1.add("vasu");
l1.add("Reddy");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
Set s1 = new HashSet();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
s1.add("Srinu");
s1.add("vasu");
s1.add("Reddy");
System.out.println();
System.out.println(" Set Elements");
System.out.print("\t" + s1);
SortedSet s11 = new TreeSet();
s11.add("Srinu");
s11.add("Vasu");
s11.add("Reddy");
System.out.println();
System.out.println(" SortedSet Elements");
System.out.print("\t" + s11);
Map m1 = new HashMap();
m1.put("Srinu", "8");
m1.put("Vasu", "31");
m1.put("Reddy", "12");
m1.put("Challa", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
Map m2=new TreeMap();
m2.put("Srinu", "8");
m2.put("Vasu", "31");
m2.put("Reddy", "12");
m2.put("Challa", "14");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m2);
}
}

Case Study On 1-Dimensional Collections:


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
class Employee { int id; String name; String address;
Employee(int id, String name, String address) {
this.id = id;
this.name = name;
this.address = address;
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
void display() { System.out.println("Id:" + id);
System.out.println("Name:" + name);
System.out.println("Address" + address);
}
}
public class Cdemo {
public static void main(String args[]) throws Exception {
int a; String b, c; Employee a1;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
ArrayList<Employee> ar1 = new ArrayList<Employee>();
for (int i = 0; i < 5; i++) {
System.out.println("Enter id");
a = new Integer(br.readLine());
System.out.println("Enter Name");
b = br.readLine();
System.out.println("Enter Address");
c = br.readLine();
a1 = new Employee(a, b, c);
ar1.add(a1);
}
System.out.println("Enter Employee Id to be Search");
System.out.println("Enter employee id:");
int empid = new Integer(br.readLine());
for (int j = 0; j < ar1.size(); j++) {
Employee obj = ar1.get(j);
if (empid == obj.id) {
obj.display();
} else {
System.out.println("Not found");
}
}
} }
Collection Framework Classes:

Collection Framework Classes contain implementation for those


methods which are inherited from various collection framework
interfaces. The following table gives collection framework class
name and its hierarchy.

SNO Interfaces Class Name Relation Hierarchy


1 Collection AbstractCollection Implements Collection
2 List AbstractList Extends AbstractCollection
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Implements List
3 Set AbstractSet Extends AbstractCollection
Implements Set
SortedSet
4 AbstractSequential Extends AbstractList
List
5 LinkedList Extends AbstractSequential
List
6 ArrayList Extends AbstractSequential
List
7 HashSet Extends AbstractSet
8 TreeSet Extends AbstractSet
Implements NavigableSet( it
is extending
SortedSet)

Classes 1), 2), 3), 4) are abstract classes whose objects


are cannot be created directly and we never use them in real
time applications. Classes 5), 6), 7), 8) are concrete
classes and whose objects can be created directly and we use
them in real time.

LinkedList Class:
It is one of the bottom most concrete sub class of all
collection framework classes. An object of LinkedList allows us
to organize the data in the form of nodes. Node contains 2 parts
and whose structure you know already.
Data represents the type of value we are entering for the
LinkedList. Address part represents address of next node and for
the last node address part must be null which indicates end of
the LinkedList. So here explicitly memory is wasted for the
address. This is the drawback of LinkedList and one more is
retrieving is also takes time compared to ArrayList Class.
ArrayList Class:
It is one of the bottom most concrete sub class of all
collection framework classes. In ArrayList the data is organized
in the form of cells.
Creating ArrayList is nothing but creating an object of
ArrayList class.
Advantages:
1) Implicitly memory space is created for addresses for the
values of ArrayList in associative memory which leads to
less amount of memory space (Negligible).
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
2) Retrieving the data from ArrayList is taking negligible
amount of time, i.e. Retrieval time of ArrayList is quite
fast.
HashSet and TreeSet Classes:

SNO HashSet TreeSet


1 An object of HashSet does An Object of TreeSet does not
not allow duplicates allow duplicates
2 Hashing Mechanism is TreeSet follows binary trees
followed by HashSet to concept to organize its data
organize its data
3 We cannot determine in TreeSet object always displays
which order HashSet object the data in sorted order.
displays the data
4 The operations like The operations like insertion,
insertion, deletion and deletion, and modification
modification takes more takes less time.
amount of time.
5 Retrieval time of HashSet Retrieval time of TreeSet is
is more less

Collections Class:
Apart from above Collection Classes we have one more
Collection Framework Class is available for us to operate on
collection variables. We are having may predefined methods in
it.
Some Advanced Methods of List and Collections Class Methods:
Check at the above heading we are having the sample program
on Collections class methods.

/* HashSet Example & TreeSet Example */


import java.util.*;
class Hashdemo
{ public static void main(String args[])
{
HashSet hs=new HashSet();
//TreeSet ts=new TreeSet();
System.out.println("Size="+hs.size());
System.out.println("Content="+hs);
hs.add(new Integer(6));
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
hs.add(new Integer(10));
hs.add(new Integer(-5));
hs.add(new Integer(4));
System.out.println("Size="+hs.size());
System.out.println("Content="+hs);
System.out.println("Retriving the data");
Iterator itr=hs.iterator();
while(itr.hasNext())
{
Object obj=itr.next();
System.out.println(obj);
}
}
}
Example Program:

import java.util.*;
public class SetDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
int count[]={34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i=0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet=new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);

System.out.println("The First element of the set is: "+


(Integer)sortedSet.first());
System.out.println("The last element of the set is: "+
(Integer)sortedSet.last());
// Create the sorted set
SortedSet sortedset = new TreeSet();
// Add elements to the set
sortedset.add("b");
sortedset.add("c");
sortedset.add("a");
// Iterating over the elements in the set
Iterator it = sortedset.iterator();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
while (it.hasNext()) {
// Get element
Object element = it.next();
System.out.println(element.toString());
}

}
catch(Exception e){}
}
}

2-Dimensional Collection Framework:

2-Dimensional Collection Framework is one in which the data


is organized in the form of (key, value) pair. In (key, value)
pair the value of key must be always unique where as the value
may or may not be unique.
Both key and value must be objects.

2-Dimensional Collection Framework or Map interfaces:


Map interfaces are of 2 types. They are
1) java.util.Map ----- extends Collection

a) Map is the sub interface of collection. An object of Map


always allows us to add the data in the form of (key,
value).
b) An object of Map always displays the data in random order.
Methods:
public void put(Object, Object): This method is used for adding
an entry to Map interface object in the form of (key, value).
public Object get(Object kobj): This method is used for
obtaining the value by passing key value.
public void remove(int):
public void remove(Object kobj):
public void removeAll():

The above methods are used for removing an entry of Map either based on
position or based on content i.e. key.
The last method is used for removing all the entries of Map.

public Set KeySet ():

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
This method is used for obtaining Set of key values from the Map interface object and
pass these set of key values to get() for obtaining value of values.
Eg: Set s=m.keySet (); //s={10, 20, 30}
Iterator itr=s.iterator ();
while (itr.hasNext ())
{ Object kobj=itr.next ();
Object vobj=m.get(kobj);
System.out.println (vobj+”is the value of “+kobj);
}

2) java.util.SortedMap ----- extends Map

a) SortedMap is the sub interface of Map.


b) An object of SortedMap is also organizing the data in the form of (key, value).
c) SortedMap interface object always displays the data in Sorted order.
/*HashMap & TreeMap */
import java.util.*;
class HashMapdemo
{ public static void main(String args[])
{ HashMap hm=new HashMap();
//TreeMap tm=new TreeMap();
System.out.println("Size="+hm.size());
System.out.println("Content="+hm);
hm.put("pqr",new Integer(999));
hm.put("abc",new Integer(888));
hm.put("zzz",new Integer(777));
hm.put("aaa",new Integer(999));
System.out.println("Size="+hm.size());
System.out.println("Content="+hm);
Set s=hm.keySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{ Object obj1=itr.next();
Object obj2=hm.get(obj1);
System.out.println(obj1+"==>"+obj2);
}
}
}
2D-Collection Framework Classes or Map Classes:
2D-Collection Framework Classes contain definition for the
abstract methods which are inherited from various 2D-Collections
Framework interfaces.
The following table gives Map Class Name and their hierarchy:
SNO Classes Relation Hierarchy
1 AbstractMap Implements Map
2 AbstractSortedMap Extends AbstractMap
Implements SortedMap
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
3 HashMap Extends AbstractMap
4 TreeMap Extends AbstractSortedMap

Classes 1 and 2 are abstract classes whose objects cannot


be created directly and we never use them in real time
applications.
Classes 3 and 4 are concrete classes whose objects can be
created directly and we use them in real time applications.
HashMap and TreeMap Classes:

SNO HashMap TreeMap


1 HashMap interface objects TreeMap interface object does
does not allow duplicates not allow duplicates
2 Hashing Mechanism is TreeMap follows binary trees
followed by HashMap to concept to organize its data
organize its data in the in the form of (key, value)
form of (key, value)
3 We cannot determine in TreeMap object always displays
which order HashMap object the data in sorted order.
displays the data
4 The operations like The operations like insertion,
insertion, deletion and deletion, and modification
modification takes more takes less time.
amount of time.
5 Retrieval time of HashMap Retrieval time of TreeMap is
is more less

Real World Example:

Student Class:
package CollectionCaseStudy;
public class Student {
private String rollNo;
private String name;
private String address;
private String phone;
private String email;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

public Student(String rollNo, String name, String address, String phone,


String email) {
this.rollNo = rollNo;
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}

@Override
public String toString() {
return "Student [rollNo=" + rollNo + ", name=" + name + ",
address="
+ address + ", phone=" + phone + ", email=" + email +
"]";
}
}

StudentManager Class:
package CollectionCaseStudy;
import java.util.Iterator;
import java.util.List;
public class StudentManager {
public void printStudentDetails(List<Student> studentList) {
Iterator<Student> iterator = studentList.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println("Student Roll No :" + student.getRollNo());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("Student Name :" + student.getName());
System.out.println("Student Address :" + student.getAddress());
System.out.println("Student Email :" + student.getEmail());
System.out.println("Student Mobile No :" + student.getPhone());
System.out.println("******************************************");
System.out.println("By Using Student Object with the help of toString()");
System.out.println(student);
System.out.println("******************************************");
}
}
}

MainClass:
package CollectionCaseStudy;
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
Student s1 = new Student("1", "Srinivas", "Flat No 123", "9603585810",
"urtrainer.java@gmail.com");
Student s2 = new Student("2", "Srinivasa Reddy", "Flat No 123/6A",
"9603585810", "urtrainer.java@gmail.com");
Student s3 = new Student("3", "Vasu", "Flat No 124/6B", "9603585810",
"urtrainer.java@gmail.com");
Student s4 = new Student("4", "Challa", "Flat No 125/6C", "9603585810",
"urtrainer.java@gmail.com");
Student s5 = new Student("5", "Csreddy", "Flat No 111/6E",
"9603585810", "urtrainer.java@gmail.com");
List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
new StudentManager().printStudentDetails(studentList);
}
}
Sample Program on Object Hash Code Values:
class Employee {
int id;
String name;
String add;
Employee(int id, String name, String add)
{ this.id = id;
this.name = name;
this.add = add;
}
Employee()
{ id = 112;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
name = "vasu";
add = "hyd";
}
}
public class Sample123 {
public static void main(String[] args) {
Employee o1 = new Employee(111, "srinu", "audipudi");
Employee o2 = new Employee(111, "srinu", "audipudi");
System.out.println(o1.hashCode());
System.out.println(o2.hashCode());
Employee t1 = new Employee();
Employee t2 = new Employee();
System.out.println(t1.getClass());
int a = t1.hashCode();
int b = t2.hashCode();
System.out.println("t1 object hash code: " + a);
System.out.println("t2 object hash code: " + b);
if (t1.equals(t2))
System.out.println("t1 and t2 refers the same");
else
System.out.println("t1 and t2 does not refer the same");
Employee t3, t4;
t3 = t1;
t4 = t1;
if (t3.equals(t4))
System.out.println("t3 and t4 refers the same");
else
System.out.println("t3 and t4 does not refer the same");

}
}

Other java.util.* package Classes:


This package is used to import all the utility classes in our program.

Utility Classes:

Calendar Date StringTokenizer Random

Stack Dictionary ->HashTable ->Properties

Calendar: This is used to set and get properties of Calendar. It is an abstract class.

Static Calendar getInstance () method is used to get the instance of the Calendar class.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Methods: void set(int, int);

int get(int);

Static final variables:

JANUARY -> 0 FEBRUARY -> 1 ….. DECEMBER -> 11

SUNDAY -> 1 MONDAY -> 2 ….. SATUARDAY -> 7

MONTH, YEAR, DAY_OF_WEEK, WEEK_OF_YEAR

package utilpgms;
import java.util.Calendar;
class CalenderDemo {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
System.out.println("Current Month : " + cal.get(Calendar.MONTH));
System.out.println("Current Day : " + cal.get(Calendar.DAY_OF_WEEK));
cal.set(Calendar.MONTH, Calendar.AUGUST);
cal.set(Calendar.DAY_OF_WEEK, 1);
//cal.set(Calendar.MONTH, 7);
System.out.println("Modified Month : " + cal.get(Calendar.MONTH));
System.out.println("Modfied Day : " + cal.get(Calendar.DAY_OF_WEEK));
System.out.println("Week of the Year : "
+ cal.get(Calendar.WEEK_OF_YEAR));
System.out.println("Year : " + cal.get(Calendar.YEAR));
}
}
DATE: This is used to know the date and time properties in date class, SUNDAY
-> 0..... SATUARDAY ->6, JANUVARY - 1.... DECEMBER – 12

Constructors: Date ();

Date (long);

Methods : int getDate();

int getDay();

int getYear();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int getMonth();

int getHours();

int getMinutes();

int getSeconds();

void setDate(int);

void setDay(int);

void setYear(int);

void setMonth(int);

void setHours(int);

void setMinutes(int);

void setSeconds(int);

Note: All the above methods are depricated.

Depricated API:

API which is available in the older version, but not including the newer version is
called a Depricated API.

They may remove completely for the next 4 or 5 years.

If we want to know, the depricated methods in our program, then we can compile
the program with the keyword

javac -deprecation filename.java

If we don’t want to get any warning then we should compile with the keyword

javac -nowarn filename.java

package utilpgms;
import java.util.Date;
public class DateDemo {
@SuppressWarnings("deprecation")
public static void main(String args[]) {
Date d = new Date();
System.out.println(d);
System.out.println(d.getDay());
System.out.println(d.getHours());
System.out.println(d.getDate());
System.out.println(d.getMinutes());
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(d.getSeconds());
System.out.println(d.getYear() + 1900);
d.setDate(4);
System.out.println(d.getDate());
}
}

Random Class: It is a class of util package which is used to generate random


numbers dynamically at the runtime. But the class can be applicable only on integral and
floating type.

Constructors: Random ();

Methods: XXX nextXXX(); XXX nextXXX(XXX);

XXX replace with any integral data types.

package utilpgms;
import java.util.Random;
public class RandomDemo {
public static void main(String args[]) {
Random r = new Random();
int ri = r.nextInt();
System.out.println("Int : " + ri);
ri = r.nextInt(100);
System.out.println("Limit Int : " + ri);
double rd = r.nextDouble();
System.out.println("Double : " + rd);
}
} Whatever the random value we are getting it may be a negative number or
positive number. If you want to get only positive number then you must use
Math.abs() method.
If you want to generate random number you have one more possibility that
is using Math. random () function and its return type is double data type.
Depending upon your requirement you go with your alternate option.

String Tokenizer :

This class is used to divide the given string into different tokens and that tokens
will be stored into a enumeration type. It will be divide the given string but we can’t
make any modifications on the given string.

Constructors: StringTokenizer(String, String);

Methods : int CountTokens();

boolean hasMoreTokens();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
boolean hasMoreElements();

String nextToken();

Different Possibilities of Splitting a String:

import java.util.StringTokenizer;
public class SplitString {
public static void main(String[] args) {
String str = "My name is Srinivas Reddy Challa";
String[] count = str.split(" ");
System.out.println("Number of Words:" + count.length);
String[] count1 = str.split("\\s+");
System.out.println("Number of Words:" + count1.length);
String str1 = "My name is Srinivas Reddy Challa";
StringTokenizer mytokens = new StringTokenizer(str1);
System.out.println("******************");
System.out.println("Number of Tokens:" + mytokens.countTokens());
System.out.println("******************");
while (mytokens.hasMoreElements())
System.out.println(mytokens.nextToken());
String str2 = "My, name, is, Srinivas Reddy ,Challa";
StringTokenizer mytokens1 = new StringTokenizer(str2, ",");
System.out.println("******************");
System.out.println("Number of Tokens:" + mytokens1.countTokens());
System.out.println("******************");
while (mytokens1.hasMoreTokens())
System.out.println(mytokens1.nextToken());
System.out.println("******************");
}
}
Stack: A Stack is one of the ordered list of elements, where it follows the order LIFO or
FILO. This class is used to perform all the stack operation and it is containing all built in
methods for that operations.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

package utilpgms;
import java.util.Stack;
class StackDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]) {
Stack st = new Stack();
st.push("A");
st.push("B");
st.push("C");
st.push("D");
st.push("E");
st.push(new Integer(10));
System.out.println("Stack Peek value : " + st.peek());
System.out.println(st.search("D"));
System.out.println(st.empty());
for (int i = 0; i <= 5; i++)
System.out.println (st.pop());
System.out.println(st.search(new Integer(10)));
System.out.println(st.empty());
}
}
Out Put:
Stack Peek value : 10 3 false 10 E D C B A
-1
true
Dictionary: Dictionary is an abstract class that represents a key/value storage
repository and operates much like Map.
Hashtable : Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Constructors:
Hashtable( )
Hashtable(Object key,Object value);
Methods: Object get(Object key);
Object put(Object key, Object value);
Object remove(Object key);
Enumeration keys( ) Returns an enumeration of the keys contained in the hash table.
Enumeration elements( )
Returns an enumeration of the values or elements contained in the hash table.
boolean hasMoreElements();
Properties : It is similar to Hashtable. This is a specially implemented to store the
key/value pair which are in the form of Strings.
Constructor: Properties ()
Methods: void setProperty(String,String);
String getProperty(String);
void list(PrintStream);
Program
package utilpgms;
import java.util.Properties;
class PropertiesDemo {
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("C", "Kanitkar");
p.setProperty("edition", "4th");
p.setProperty("Price", "150");
System.out.println("Author is :" + p.getProperty("C"));
System.out.println("Edition is :" + p.getProperty("edition"));
System.out.println("Price is :" + p.getProperty("Price"));
}
}
package utilpgms;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public void queueExample() {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Queue queue = new LinkedList();
// Using the add method to add items.
// Should anything go wrong an exception will be thrown.
queue.add("item1");
queue.add("item2");
// Using the offer method to add items.
// Should anything go wrong it will just return false
queue.offer("Item3");
queue.offer("Item4");
// Removing the first item from the queue.
// If the queue is empty a java.util.NoSuchElementException will be
//thrown.
System.out.println("remove: " + queue.remove());
// Checking what item is first in line without removing it
// If the queue is empty a java.util.NoSuchElementException will be
// thrown.
System.out.println("element: " + queue.element());
// Removing the first item from the queue.
// If the queue is empty the method just returns false.
System.out.println("poll: " + queue.poll());
// Checking what item is first in line without removing it
// If the queue is empty a null value will be returned.
System.out.println("peek: " + queue.peek());
}
public static void main(String[] args) {
new QueueDemo().queueExample();
}
}

Queue is a one more interface in 1- D Collection Framework.

Input and Output Streams in Java:

 A stream represents a sequence of data.


 I/O stands for input and output streams.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Streams are used to read data from a source location or write data into a
destination location.
 Here source can be a keyboard, a file, a disk. Destination can be file, disk, and
console.
 Streams support different kinds of data streams, simple byte stream, primitive
data stream, character stream and object stream.

A Stream is a flow of data between primary memory and secondary


memory.

Operations on the File:

On files we can perform two operations. They are Read and Write Operations.

Whenever we want to transfer the temporary data from primary memory to


secondary memory chose the filename, open the file in write mode and perform write
operations.

During the write operation if the selected file is read only file then we cannot
perform any write operation. Hence, we get an exception known as java.io.IOException.

During the write operation if there is no sufficient secondary memory space then
we get an exception known as java.io.IOException

In order to read the data from file which is residing in secondary memory into
primary memory, choose the filename open it into read mode and perform read
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
operation. During read operation, if the specified file is not found, then we get an
exception called java.io.FileNotFoundException.

If we try to read the data from corrupted file we get an exception known as
java.io.IOException, you already aware that java.io.IOException is the super class for
java.io.FileNotFoundException.

Types of Streams:

Based on transferring the data between primary memory and secondary memory we
have 2 types of streams. They are 1) Byte Streams 2) Character Streams.

Byte Streams: Byte Streams are those which will transfer 1 byte of data between
primary memory and secondary memory. Byte Streams contain various classes and
interfaces which are used for opening the file in read mode and write mode and
performing various other operations. Byte Streams are internally implemented in lower
level applications such as flow of data across various electronic circuits, flow of data
across mother board circuits.

InputStream:

 This is one of the super class for all Byte Stream classes which are related to read
operation.
 Any object of InputStream class called ‘in’ created in System class as a static data
member(System.in)
 InputStream class is one of the abstract whose object cannot be created directly,
but we can create indirectly and it is meant for opening a file in read mode.

Instance Methods:
public int available(): This method is used for determining the size of the file.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public int read(); This method is used for reading the data from the file until end of file
is taking place. In java end of file is indicated by -1.
public void close(): This method is used for closing the file which was opened in read
mode.
OutputStream:
 This is one of the Super Class for all Byte Stream classes related to write
operation.
 This is one of the abstract class whose object can be created indirectly and it is
meant for opening a file in write mode.
 public int available():
 public void close():
 public void write(int):
This method is used for writing the integer category data which was opened in
write mode.
DataInputStream Class: DataInputStream class is one of the bottom most concrete sub
class of all ByteStream classes. DataInputStream class is used for 2 purposes. They are
1) Reading the data from keyboard 2) Reading the data from other machine which
is located in another machine.
Constructor: DataInputStream(InputStream)
DataInputStream dis=new DataInputStream(System.in);
package Sample;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class DataRead {
public static void main(String args[]) {
try { DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter First number:");
String s1 = dis.readLine();
System.out.println("Enter Second number:");
String s2 = dis.readLine();
int x = Integer.parseInt(s1);
int y = Integer.parseInt(s2);
int z = x + y;
System.out.println("Sum:" + z);
} catch (FileNotFoundException e) {
System.out.println("Problem in Reading");
} catch (IOException e) {
System.out.println("Problem in reading corrupted file");
}
}
}

FileInputStream Class:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
FileInputStream Class is also one of the bottom most sub class of all Byte Stream
Classes. This class is used for opening a file in read mode.

FileInputStream(String) throws FileNotFoundException the parameter String represents


name of the file which is going to open in read mode.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Srinivasa Reddy Challa
*
*/
public class FileInputStream1 {
/**
* @param args
*/
public static void main(String[] args) {
StringBuffer content = null;
InputStream fileStream = null;
int ch;
String fname = "C://data.txt";
try { fileStream = new FileInputStream(fname);
content = new StringBuffer();
while ((ch = fileStream.read()) != -1) {
content.append((char) ch);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println(content);
try {
fileStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

BufferedInputStream Class:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
* @author Srinivasa Reddy Challa
*
*/
public class FileBufferTest {
/**
* @param args
*/
public static void main(String[] args) {
FileInputStream fileInput = null;
BufferedInputStream bufferInput = null;
try {
fileInput = new FileInputStream("C:/data.txt");
bufferInput = new BufferedInputStream(fileInput);
byte[] contents = new byte[1024];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bufferInput.read(contents)) != -1) {
strFileContents = new String(contents, 0, bytesRead);
System.out
.println("The Content of the file read using
BufferedInputStream is:\n"
+ strFileContents);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
bufferInput.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
OutputStream Classes:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

/**
* @author Srinivasa Reddy Challa
*
*/
public class FileOutputTest {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
FileOutputStream fileOutput = null;
scanner = new Scanner(System.in);
System.out.println("Enter Name");
String name = scanner.next();
try {
// fileOutput = new FileOutputStream("C:/newFile.txt");
fileOutput = new FileOutputStream("C:/newFile.txt", true);
byte buffer[] = new byte[100];
buffer = name.getBytes();
fileOutput.write(buffer);
System.out
.println("Employee Details Successfully Written
to the file");

} catch (FileNotFoundException fileOut) {


fileOut.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
fileOutput.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

}
}
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

/**
* @author training
*
*/
public class FileBufferOutputTest {
/**
* @param args
*/
public static void main(String[] args) {
FileOutputStream fileOutput = null;
BufferedOutputStream bufferOutput = null;
Scanner scanner = null;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
scanner = new Scanner(System.in);
System.out.println("Enter Employee Id");
int empId = scanner.nextInt();
System.out.println("Enter Employee Name");
String empName = scanner.next();
String finalValue = "Welcome" + empName + " , Your Employee Id
is "
+ empId;
try {
fileOutput = new FileOutputStream("C:/newFile.txt", true);
bufferOutput = new BufferedOutputStream(fileOutput);
bufferOutput.write(finalValue.getBytes());
System.out.println("Data is Written into the file");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
bufferOutput.flush();
bufferOutput.close();
fileOutput.close();
} catch (IOException io) {
io.printStackTrace();
}
}

}
}
import java.io.*;

public class RandomIOApp {

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

RandomAccessFile file = new RandomAccessFile("test.txt", "rw");

file.writeBoolean(true); file.writeInt(123456);

file.writeChar('j'); file.writeDouble(1234.56);

// Use seek() to move to a specific file location

file.seek(1); System.out.println(file.readInt());

System.out.println(file.readChar()); System.out.println(file.readDouble());

file.seek(0); System.out.println(file.readBoolean()); file.close();

}}

Character Streams:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Character Streams are those which are transferring 2 bytes at a time between primary
and secondary memory. Character Streams also contain various classes and interfaces
out of which some of them are used for opening a file in read mode and some of them
are used in to open a file in write mode. Character Streams are used in higher level
applications such as internet applications.

Reader Classes:

package CharacterStreams;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderDemo {
public static void main(String[] args) {
FileReader fileReader = null;
try {
fileReader = new FileReader("C:/data.txt");
int chars;
while ((chars = fileReader.read()) != -1) {
System.out.println((char) chars);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}}
package CharacterStreams;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileReverseReading {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufReader = null;
StringBuffer sbuf = new StringBuffer();
File file = new File("c:/data.txt");
try {
fileReader = new FileReader(file);
bufReader = new BufferedReader(fileReader);
int len = (int) file.length();
char[] c = new char[len];
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
bufReader.read(c, 0, len);
// Reversing the String
char[] cnew = new char[len];
for (int i = 0, j = len - 1; i < len; i++, j--) {
cnew[i] = c[j];
sbuf.append(cnew[i]);
}
System.out.println("The Reversed File Contents is \n"
+ sbuf.toString());
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {fileReader.close();
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}

package CharacterStreams;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderDemo {
public static void main(String[] args) {
FileReader fileReader = null;
BufferedReader bufReader = null;
try {fileReader = new FileReader("c:/data.txt");
bufReader = new BufferedReader(fileReader);
String line = null;
System.out.println("The Data which is taken from the file to the
buffer is");
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException fileNotFound) {
fileNotFound.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {fileReader.close();
bufReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}}}
Writer Classes:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
FileWriter Class:

package CharacterStreams;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
FileWriter fileWriter = null;
String data = "The information to be written to the file ";
try {fileWriter = new FileWriter("C:/info1.txt");
fileWriter.write(data);
System.out.println("The information is written to the file");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
BufferedWriter Class:
package CharacterStreams;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {fileWriter = new FileWriter("C:/info1.txt");
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello");
bufferedWriter.newLine();
bufferedWriter.write("Welcome");
System.out.println("Information is Written to the file");

} catch (IOException ioe) {


ioe.printStackTrace();
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}}
package CharacterStreams;
import java.io.BufferedWriter;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class BufferedWriterEmaiReg {
public static void main(String[] args) {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
Scanner scanner = null;
scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.next();
System.out.println("Enter your mail id");
String email = scanner.next();
String finalValue = "Welcome" + name+ ", Thank you for registering your
email id:" + email;
try {fileWriter = new FileWriter("c:/newFile.txt");
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(finalValue);
System.out.println("Information is written to the file");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {bufferedWriter.close();
fileWriter.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}

Serialization:

When we use normal streams to transfer the data between primary memory and
secondary memory, there is a possibility of performing various read and write operations
which leads to poor performance of an application.

In order to improve the performance of normal streams we must use serialization.


In other words the concept of serialization reduces number of read and write operations.

Definition: The process of saving the state of the object permanently in


secondary memory is known as Serialization.

In order to develop any serialization and deserialization applications we must


develop 3 categories of programs. They are 1) Sub Class Program 2) Serialization
Process Program 3) Deserialization Process Program

Developing Serialization Sub Class Program:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
 Choose the appropriate package for keeping Serializable sub class and ensure the
package statement must be first statement in java program.
 Choose the appropriate class and whose object participating in serialization
process.
 Whichever class we are selecting in step 2 that class must implement a predefined
interface called java.io.Serializable – This interface is known as Marked/ Tagged
interface (Marked interface is one which does not contain any abstract methods).
 Choose the set of data members which depend on the class.
 For each and every data member we must define set of set methods.
 For each and every data member we must define set of get methods.

/* Pgm for serialize subclass for student */

package Serialization;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Student implements Serializable {
int stno; String name; float marks;
public void setStno(int stno) {
this.stno = stno;
}
public void setName(String name) {
this.name = name;
}
public void setMarks(float marks) {
this.marks = marks;
}
public int getStno() {
return stno;
}
public String getName() {
return name;
}
public float getMarks() {
return marks;}}
Developing Serialization Process program:
package Serialization;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
class Spgm {
public static void main(String args[]) {
try { Student so = new Student(); //Step-1
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter Student Number:");
String sno = dis.readLine();
int stno = Integer.parseInt(sno);
System.out.println("Enter Student Name:");
String name = dis.readLine();
System.out.println("Enter Student Marks:");
String mark = dis.readLine();
Float marks = Float.parseFloat(mark);
// calling of setmethods Step -2
so.setStno(stno);
so.setName(name);
so.setMarks(marks);
// Choose the file name Step-3
System.out.println("Enter file name to write student data");
String fname = dis.readLine();
FileOutputStream fos = new FileOutputStream(fname);
ObjectOutputStream oos = new ObjectOutputStream(fos); //Step-4
oos.writeObject(so); //Step-5
System.out.println("Student data saved successfully");
fos.close(); //Step-6
oos.close();
} catch (IOException ioe) {
System.out.println("Problem in creating file in write mode");
}
}
}
Deserialization:
The ability to restore a record of a file from secondary memory to primary
memory is known as deserialization.

Deserialization Process Program:

package Serialization;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
class Dspgm {
public static void main(String args[]) {
try {Student so = new Student(); // 1)
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter file name to read Student data:");
String fname = dis.readLine();
FileInputStream fis = new FileInputStream(fname); // 2)
ObjectInputStream ois = new ObjectInputStream(fis); // 3)
Object obj = ois.readObject();
so = (Student) obj; // 4)
System.out.println("Student Number:" + so.getStno()); // 4)
System.out.println("Student Name:" + so.getName());
System.out.println("Student Marks:" + so.getMarks());
fis.close();
ois.close();
} catch (FileNotFoundException ie) {
System.out.println(" Problem in reading the file");
} catch (IOException ie) {
System.out.println("problem in reading the file");
} catch (Exception e) {
System.out.println(e);
}
}
}
Example2:
package Serialization;
import java.io.Serializable;
public class Employee implements Serializable {
long empId;
String empName;
transient long empSalary;
Employee(long empId, String empName, long empSalary) {
this.empId = empId;
this.empName = empName;
this.empSalary = empSalary;
}
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName
+ ", empSalary=" + empSalary + "]";
}

}
package Serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* @author Srinivasa Reddy
*
*/
public class SerializationDemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
Employee emp = new Employee(135234, "SrinivasaReddy", 125000);
System.out.println("Employee Before Serialization" + emp);
FileOutputStream fileOut = new FileOutputStream("c:/data.txt");
// Serialization
ObjectOutputStream oos = new ObjectOutputStream(fileOut);
oos.writeObject(emp);
oos.flush();
oos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {Employee emp;
FileInputStream fileIn = new FileInputStream("C:/data.txt");
// Deserialization
ObjectInputStream ois = new ObjectInputStream(fileIn);
emp = (Employee) ois.readObject();
ois.close();
System.out.println("Employee After Deserialization" + emp);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
}
}
}

A stream is a sequence of data. A program uses an input stream to read data


from a source, one item at a time:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Reading information into a program.

A program uses an output stream to write data to a destination, one item at


time:

Writing information from a program.

Sample Programs for practice:


1) Write a program for finding the Factorial of a given number?
public class Factorial {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
static int fact(int number) { int f = 1;
for (int i = 1; i <= number; i++)
f = f * i;
return f;
}
public static void main(String[] args) {
int result = fact(5);
System.out.println("Factorial of 5=" + result);
} }
2) Write a program for finding the Fibbanoic Series?
public class Fibbanoic {
public static void main(String[] args) {
int n = 10, i, f0 = 1, f1 = 1, f2 = 0;
for (i = 1; i <= n; i++) {
f2 = f0 + f1;
f0 = f1;
f1 = f2;
f2 = f0;
System.out.println(f2);
}}}
3) Write a program for finding the given number is Armstrong or not?
public class ArmStrong {
public static void main(String[] args) {
int n = 153, c = 0, a, d; d = n;
while (n > 0) { a = n % 10;
n = n / 10;
c = c + (a * a * a);
} if (d == c)
System.out.println("ArmStrong Number");
else
System.out.println("Not an ArmStrong Number");
}}
4) Write a program for checking the given number is Palindrome or not?
public class Palindrome {
public static void main(String[] args) {
int a = 242; int n = a, b = a, rev = 0;
while (n > 0) { a = n % 10;
rev = rev * 10 + a;
n = n / 10;
}
if (rev == b)
System.out.println("It is a palindrome");
else
System.out.println("It is not a palindrome");
}
}
5) Is it possible to Overload Main function or not? Yes it is possible
public class OverloadMain {
public static void main(int a) {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println(a);
}
public static void main(String a) {
System.out.println("Hello " + a);
}
public static void main(String[] args) {
System.out.println("main() method invoked");
main(10);
main("Srinivasa Reddy");
}
}
6) Is it possible to run a java program without using main?
Ans: Its not possible upto jdk 1.6 version
public class Withoutmain {
static {
System.out.println("Static Block is Executed");
System.exit(0);
}
public static void main(String[] args) {

}
}
Note: Now it is possible to write and execute a java program without using
main function also. After jdk 1.7 it is possible
public class Withoutmain {
static {
System.out.println("Static Block is Executed");
System.exit(0);
}
}

7) What do you mean by cloning?

The Object cloning is a way to create exact copy of an object. For


this purpose clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class
whose object clone we want to create. If you don’t implement Cloneable
interface then clone() method will throw CloneNotSupportedException.

8) Write a program for clone() method in Object class and discuss about its
use?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
package CloneExample;
class Student implements Cloneable {
int rollno;
String name;
Student(int rollno, String name) {
this.rollno = rollno;
this.name = name;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String args[]) {
try {
Student s1 = new Student(101, "Srinivasa Reddy");
Student s2 = (Student) s1.clone();
System.out.println(s1.rollno + " " + s1.name);
System.out.println(s2.rollno + " " + s2.name);
} catch (CloneNotSupportedException c) {
c.printStackTrace();
}

}
}
/*
* We want to use the data of one object into another object we are having
two
* possibilities 1) By using copy constructor 2) using clone() method of
object
* class and it return object. What is its importance: Ans If you create
another
* object by using new keyword and assign the values of another object to
this
* one it will require a lot of processing on this object.So to save extra
* processing task we use clone() method and it is very easy to upply.
*/
9) Aggregation Program:
package AggregationExample;
public class Address {
String city, state, country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
}

package AggregationExample;
public class Emp {
int id;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
String name;
Address address;
public Emp(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
void display() {
System.out.println(id + " " + name);
System.out.println(address.city + " " + address.state + " "
+ address.country);
}
public static void main(String[] args) {
Address address1 = new Address("gzb", "UP", "india");
Address address2 = new Address("gno", "UP", "india");
Emp e = new Emp(111, "varun", address1);
Emp e2 = new Emp(112, "arun", address2);
e.display();
e2.display();
}
}
CaseStudy-1:
import java.io.BufferedReader;
import java.io.InputStreamReader;
interface Inter {
public void input() throws Exception;
public void display();
}
abstract class Sample1 implements Inter {
int i, j;
String[] ename = new String[30];
String[] bname = new String[30];
String[] type = new String[30];
public void input() throws Exception {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the name:");
ename[i] = br.readLine();
System.out.println("Enter the bank name:");
bname[i] = br.readLine();
System.out.println("Enter the accnt type:");
type[i] = br.readLine();
}
}
}

class Sample2 extends Sample1 implements Inter {


urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void display() {
System.out.println("name \t bank \t actype");
System.out.println("-----------------------------------");
for (int j = 0; j <= 2; j++) {
System.out.println(ename[j] + "\t" + bname[j] + "\t" + type[j]);
}
System.out.println("-----------------------------------");
}
}
public class CaseStudy11 {
public static void main(String args[]) throws Exception {
Sample2 ob1 = new Sample2();
ob1.input();
ob1.display();
Inter i1;
i1 = new Sample2();
i1.input();
i1.display();
Sample1 s1;
s1 = new Sample2();
s1.input();
s1.display();
}
}

CaseStudy-2:
package Case2;
interface Inter {
public void input()throws Exception;
public void display();
}
package Case2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
abstract class Sample1 implements Inter {
int i, j;
String[] ename = new String[30];
String[] bname = new String[30];
String[] type = new String[30];
public void input() throws Exception {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for (int i = 0; i <= 2; i++) {
System.out.println("Enter the name:");
ename[i] = br.readLine();
System.out.println("Enter the bank name:");
bname[i] = br.readLine();
System.out.println("Enter the accnt type:");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
type[i] = br.readLine();
}
}
}
class Sample2 extends Sample1 implements Inter {
public void display() {
System.out.println("name \t bank \t actype");
System.out.println("-----------------------------------");
for (int j = 0; j <= 2; j++) {
System.out.println(ename[j] + "\t" + bname[j] + "\t" +
type[j]);
}
System.out.println("-----------------------------------");
}
}
package Case2;
public class Case22 {
public static void main(String args[])throws Exception
{
/* Sample2 ob1=new Sample2();
ob1.input();
ob1.display(); */
/* Inter i1;
i1=new Sample2();
i1.input();
i1.display(); */
Sample1 s1;
s1=new Sample2();
s1.input();
s1.display();
}
}
Case Study-3:
public interface Inter1 {
public void input() throws Exception;
public void display();
public void area();

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Square implements Inter1 {
float base;
float height;
double area1;
@Override
public void input() throws Exception {
// TODO Auto-generated method stub
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Base Value:");
base=Float.parseFloat(br.readLine());
System.out.println("Enter the Height Value:");
height=Float.parseFloat(br.readLine());
}
@Override
public void area() {
// TODO Auto-generated method stub
area1=base*height;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Base Value is="+base);
System.out.println("Height Value is="+height);
System.out.println("Square Area is="+area1);
}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Traingle implements Inter1 {
float base;
float height;
double area1;
@Override
public void input() throws Exception {
// TODO Auto-generated method stub
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the Base Value:");
base=Float.parseFloat(br.readLine());
System.out.println("Enter the Height Value:");
height=Float.parseFloat(br.readLine());
}
@Override
public void area() {
// TODO Auto-generated method stub
area1=base*height/2;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Base Value is="+base);
System.out.println("Height Value is="+height);
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("Traingle Area is="+area1);
}
}
class DemoArea{
public static void main(String args[])throws Exception
{
// Area of Traingle
Inter1 i1;
i1=new Traingle();
i1.input();
i1.area();
i1.display();
// Area of Square or Rectangle
i1=new Square();
i1.input();
i1.area();
i1.display();
}
}
Case Study-4:
package sample;
import java.io.IOException;
public interface IEmployee {
public abstract void input() throws IOException;
public abstract void updateSalary();
public abstract void dispalyDetails();
public static final double HRA = 0.02;
public static final double DA = 0.01;
}
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PermanentEmployee implements IEmployee {
String ename[] = new String[5];
String ejob[] = new String[5];
double esal[] = new double[5];
String emno[] = new String[5];
String eloc[] = new String[5];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public void input() throws IOException {
System.out.println("**********************************");
System.out.println(" Enter Employee Details ");
System.out.println("**********************************");

for (int i = 0; i < 5; i++) {


System.out.println("Enter Employee Name:");
ename[i] = br.readLine();
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
System.out.println("Enter Employee Job:");
ejob[i] = br.readLine();
System.out.println("Enter Employee Salary:");
esal[i] = Double.parseDouble(br.readLine());
System.out.println("Enter Employee Mobile Number:");
emno[i] = br.readLine();
System.out.println("Enter Employee Location:");
eloc[i] = br.readLine();
}
}
public void updateSalary() {
for (int i = 0; i < 5; i++) {
esal[i] = Math.round(esal[i] + (esal[i] * HRA) + (esal[i] * DA));
}
}
public void dispalyDetails() {
for (int i = 0; i < 5; i++) {
System.out.println("**********************************");
System.out.println(" Employee Details Are ");
System.out.println("**********************************");
System.out.println("Employee Name:" + ename[i]);
System.out.println("Employee Job:" + ejob[i]);
System.out.println("Employee Salary:" + esal[i]);
System.out.println("Employee Mobile:" + emno[i]);
System.out.println("Employee Location:" + eloc[i]);
System.out.println("**********************************");
System.out.println("**********************************");
System.out.println();
System.out.println();
}
}
}
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ContractEmployee implements IEmployee {
String ename[] = new String[5];
String ejob[] = new String[5];
double esal[] = new double[5];
String emno[] = new String[5];
String eloc[] = new String[5];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public void input() throws IOException {
System.out.println("**********************************");
System.out.println(" Enter Contract Employee Details ");
System.out.println("**********************************");
for (int i = 0; i < 5; i++) {
System.out.println("Enter Contract Employee Name:");

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
ename[i] = br.readLine();
System.out.println("Enter Contract Employee Job:");
ejob[i] = br.readLine();
System.out.println("Enter Contract Employee Salary:");
esal[i] = Double.parseDouble(br.readLine());
System.out.println("Enter Contract Employee Mobile Number:");
emno[i] = br.readLine();
System.out.println("Enter Contract Employee Location:");
eloc[i] = br.readLine();
}
}
public void updateSalary() {
for (int i = 0; i < 5; i++) {
esal[i] = esal[i] + (esal[i] * HRA) + (esal[i] * DA);
if (esal[i] < 10000) {
esal[i] = Math.round(esal[i] + 1000);
} else {
esal[i] = Math.round(esal[i] + 500);
}
}
}
public void dispalyDetails() {
for (int i = 0; i < 5; i++) {
System.out.println("**********************************");
System.out.println(" Contract Employee Details Are ");
System.out.println("**********************************");
System.out.println("Employee Name :" + ename[i]);
System.out.println("Employee Job :" + ejob[i]);
System.out.println("Employee Salary :" + esal[i]);
System.out.println("Employee Mobile :" + emno[i]);
System.out.println("Employee Location:" + eloc[i]);
System.out.println("**********************************");
System.out.println("**********************************");
System.out.println();
System.out.println();
}
}
}
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HourlyEmployee implements IEmployee {
String ename[] = new String[5];
String ejob[] = new String[5];
double esal[] = new double[5];
String emno[] = new String[5];
String eloc[] = new String[5];
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void input() throws IOException {
System.out.println("**********************************");
System.out.println(" Enter Hourly Employee Details ");
System.out.println("**********************************");
for (int i = 0; i < 5; i++) {
System.out.println("Enter Hourly Employee Name:");
ename[i] = br.readLine();
System.out.println("Enter Hourly Employee Job:");
ejob[i] = br.readLine();
System.out.println("Enter Hourly Employee Salary:");
esal[i] = Double.parseDouble(br.readLine());
System.out.println("Enter Hourly Employee Mobile Number:");
emno[i] = br.readLine();
System.out.println("Enter Hourly Employee Location:");
eloc[i] = br.readLine();
}
}
public void updateSalary() {
for (int i = 0; i < 5; i++) {
esal[i] = esal[i] + (esal[i] * HRA) + (esal[i] * DA);
if (esal[i] > 8500) {
esal[i] = Math.round(esal[i] + 1000);
} else {
esal[i] = Math.round(esal[i] + 500);
}
}
}
public void dispalyDetails() {
for (int i = 0; i < 5; i++) {
System.out.println("**********************************");
System.out.println(" Hourly Employee Details Are ");
System.out.println("**********************************");
System.out.println("Employee Name :" + ename[i]);
System.out.println("Employee Job :" + ejob[i]);
System.out.println("Employee Salary :" + esal[i]);
System.out.println("Employee Mobile :" + emno[i]);
System.out.println("Employee Location:" + eloc[i]);
System.out.println("**********************************");
System.out.println("**********************************");
System.out.println();
System.out.println();
}
}
}

package sample;
public class EmployeeDemo {
public static void main(String[] args) {

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
IEmployee i1;
i1 = new PermanentEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();

i1 = new ContractEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();

i1 = new HourlyEmployee();
try {
i1.input();
} catch (Exception e) {
System.out.println(e.getMessage());
}
i1.updateSalary();
i1.dispalyDetails();

}
}

CaseStudy-5:

package Case1;
public interface Inter1 {
public void input()throws Exception;
public void display();
public void insert();
public void update()throws Exception;
public void delete()throws Exception;
}

package Case1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
class Sample1 implements Inter1 {
int eno;
String ename;
String job;
String dept;
int dno;
float sal;
Connection con;
PreparedStatement pst;
String sql;
BufferedReader br;
public void input() throws Exception {
System.out.println("Enter Employee Number:");
eno = Integer.parseInt(br.readLine());
System.out.println("Enter Employee Name:");
ename = br.readLine();
System.out.println("Enter Employee Job:");
job = br.readLine();
System.out.println("Enter Employee Dept:");
dept = br.readLine();
System.out.println("Enter Dept Number:");
dno = Integer.parseInt(br.readLine());
System.out.println("Enter Employee Salary:");
sal = Float.parseFloat(br.readLine());
}
public void display() {
try {
pst = con.prepareStatement("select *from empdemo");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
for (int i = 1; i <= count; i++) {
System.out.print(rsmd.getColumnName(i) + " \t ");
}
System.out.println("\n--------------------------------");
while (rs.next()) {
for (int i = 1; i <= count; i++) {
System.out.print(rs.getString(i) + " \t ");
}
System.out.println("\n-------------------------------");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in display()");
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
e.printStackTrace();
}
}
Sample1() throws IOException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mydsn", "training",
"training");
System.out.println("Connection successful");
br = new BufferedReader(new InputStreamReader(System.in));
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in Constructor()");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Exception in Constructor()");
e.printStackTrace();
}
}
public void insert() {
try {
pst = con.prepareStatement("insert into empdemo values(?,?,?,?,?,?)");
pst.setInt(1, eno);
pst.setString(2, ename);
pst.setString(3, job);
pst.setString(4, dept);
pst.setInt(5, dno);
pst.setFloat(6, sal);
pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in insert()");
e.printStackTrace();
}
}

public void delete() throws Exception {


try {
System.out.println("Enter Employee Number to Delete:");
eno = Integer.parseInt(br.readLine());
pst = con.prepareStatement("delete from empdemo where eno=?");
pst.setInt(1, eno);
pst.executeUpdate();
} catch (SQLException e) {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
// TODO Auto-generated catch block
System.out.println("Exception in delete()");
e.printStackTrace();
}
}
public void update() throws Exception {
try {
System.out.println("Enter Employee Number to Update:");
eno = Integer.parseInt(br.readLine());
System.out.println("Enter Employee Name:");
ename = br.readLine();
System.out.println("Enter Employee Job:");
job = br.readLine();
System.out.println("Enter Employee Salary:");
sal = Float.parseFloat(br.readLine());
pst = con.prepareStatement("update empdemo set ename=?,job=?,sal=? where
eno=?");
pst.setInt(4, eno);
pst.setString(1, ename);
pst.setString(2, job);
pst.setFloat(3, sal);
pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Exception in update()");
e.printStackTrace();
}
}
}
class Sample {
public static void main(String[] args) throws Exception {
Inter1 i1 = new Sample1();
i1.input();
i1.insert();
i1.display();
i1.delete();
i1.update();
i1.display();
}
}
Above program is related to JDBC

/*
* Example For Constructor
* Is it possible to declare a constructor as private ?
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
* YES YOU CAN
*/
public class Sample {
int a,b;
/*
* Constructor as private
*/
private Sample(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("Private Constructor\n A value:"+a+"\nB value:"+b);
}
public static void main(String args[])
{
System.out.println("Welcome");
/*
* Instatiating the Objects
*/
new Sample(10,20);
new Sample1(30,40);
}
}
class Sample1 {
int a,b;
//private Sample1(int a,int b)
//protected Sample1(int a,int b)
//public Sample1(int a,int b)
Sample1(int a,int b)
{
this.a=a;
this.b=b;
System.out.println("------ Constructor\n A value:"+a+"\nB value:"+b);
}
}
Check the different possibilities for above program..
class Text
{public static void main(String [] args)
{ int x= 0; int y= 0;
for (int z = 0; z < 5; z++)
{ if (( ++x > 2 ) || (++y > 2))
{ x++; }
}
System.out.println(x + " " + y);
}}
// Answer
// 8 2
Some Important Questions:
public class AA {
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String[] args) {
int i = 9;
switch (i) {
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}
Output: default
Zero

public class c123 {


private c123() {
System.out.println("Hellow");
}
public static void main(String args[]) {
c123 o1 = new c123();
c213 o2 = new c213();
}
}
class c213 {
private c213() {
System.out.println("Hello123");
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
The constructor c213() is not visible

at c123.main(c123.java:8)

interface interface_1 {
void f1();
}
class Class_1 implements interface_1 {
public void f1() {
System.out.println("From F1 funtion in Class_1 Class");
}
}
public class Demo1 {
public static void main(String args[]) {
Class_1 o11 = new Class_1();

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
o11.f1();
}
}

Output:
From F1 funtion in Class_1 Class
interface interface_1 {
void f1();
}
class Class_1 implements interface_1 {
void f1() {
System.out.println("From F1 funtion in Class_1 Class");
}
}
public class Demo1 {
public static void main(String args[]) {
Class_1 o11 = new Class_1();
o11.f1();
}
}

Exception in thread "main" java.lang.Error: Unresolved compilation


problem:
Cannot reduce the visibility of the inherited method from interface_1

at Class_1.f1(Demo1.java:6)
at Demo1.main(Demo1.java:14)
What is the output of the program?

abstract class MineBase {


abstract void amethod();
static int i;
}
class Mine1 extends MineBase {
void am() { int[] ar = new int[5];
for (i = 0; i < ar.length; i++)
System.out.println(ar[i]);
}
}
public class Mine {
public static void main(String argv[]) {
Mine1 ob1 = new Mine1();
ob1.am();
int[] ar = new int[5];
System.out.println("in main");
for (int i = 0; i < ar.length; i++)
System.out.println(ar[i]);
}}
public class Pass {
static int j = 20;

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public static void main(String argv[]) {
int i = 10;
Pass p = new Pass();
p.amethod(i);
System.out.println(i);
System.out.println(j);
}
public void amethod(int x) {
x = x * 2;
j = j * 2;
}
}
Output:
10
40

private class Base {


Base() {
int i = 100;
System.out.println(i);
}
}
public class Pri extends Base {
static int i = 200;
public static void main(String argv[]) {
Pri p = new Pri();
System.out.println(i);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
Illegal modifier for the class Base; only public, abstract & final
are permitted
at Base.<init>(Pri.java:1)
at Pri.<init>(Pri.java:8)
at Pri.main(Pri.java:12)

Output for bellow program is:


Exception in thread "main" java.lang.Error: Unresolved compilation
problem:
Type mismatch: cannot convert from double to int

at Pri1.main(Pri1.java:15)

class Base1 {
Base1() {

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
int i = 100;
System.out.println(i);
}
}
public class Pri1 extends Base1 {
static int i = 200;
public static void main(String argv[]) {
Pri1 p = new Pri1();
System.out.println(i);
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
What is the output for this program?
public class Q {
public static void main(String argv[]) {
int anar[] = new int[5];
System.out.println(anar[0]);
}
}
Output: 0
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class demo {
public static void main(String[] args) {
int arr[] = new int[5];
int arr1[] = { 10, 20, 30, 40, 50 };
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try { for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
System.out.println("Enter the Value :");
arr[i] = Integer.parseInt(br.readLine());
} for (int j = 0; j < arr.length; j++)
System.out.println("New Array" + arr[j]);
for (int temp : arr)
System.out.println("Using for each loop:" + arr[temp]);
} catch (Exception e) { System.out.println(e.getMessage()); }
}} Usage for For Each Loop Example:
Write a sample program for counting number of vowels and consonants?

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class Vowel {
public static void main(String[] args) {
String st = args[0];
int j = 0, k = 0;
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) == 'a' || st.charAt(i) == 'e'
|| st.charAt(i) == 'i' || st.charAt(i) == 'o'
|| st.charAt(i) == 'u') {
j++;
} else
k++;
}
System.out.println("No of vowels " + j);
System.out.println("No of consonants " + k);

}
}
MultiThreading:
A flow of control is known as Thread.
 If a Java program contains multiple flow of controls then that java program is
known as Multithreaded program.
 The basic aim of Multithreading is to achieve concurrent/simultaneous execution.
 The real time implementation of multithreading is to develop real-time servers.
 Ex: Tomcat, Web logic, Web sphere
 The languages like C/C++ are treated as Single threaded modeling languages
since they contain single flow of control using those languages we can achieve
only sequential execution.
 The languages like Java, .Net are treated as Multithreaded modeling languages
since there is a possibility of creating multiple flow of controls.
 Multithreading is one of the specialized form of multi tasking of operating systems.
 In Java Runtime Environment, if we write any Java Program it is by default
contains 2 types of Threads. They are
1) Fore Ground / Child Thread
2) Back Ground/ Parent Thread
 Fore Ground Thread is one which is always executing User-Defined Operations/
Functions.
 Back Ground Thread is one which is always monitoring the execution status of fore
ground thread.
 By default there exists one fore ground thread and one back ground thread.
Programmatically we can create multiple flow of controls which are nothing but
foreground threads.
 In Information Technology we are writing 2 types of applications.
1) Process Based Applications (PBA)
2) Thread Based Applications (TBA)

States of Thread:
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
When we write any Multi Threading applications there is a possibility of
having Multiple threads and these all threads will undergo various states of a thread.
Thread Contains 5 states. They are 1) new state
2) ready state
3) running state
4) waiting state
5) halted state

State chart diagram:

new state: A new state is one in which the thread is about to enter into main
memory of the computer
ready: A ready state is one which memory space is allocated for the thread and it is
waiting for the cpu first time
running: A running state is one in which the thread is under the control of cpu or the
thread is under execution. Java environment multiple threads are executing
concurrently by fallowing Round Robin Algorithm of Operating system.
waiting: A state is said to be waiting state if it satisfies any of the fallowing
> Making the thread to sleep for a period of time
> suspending the concurrently executing thread
> joining multiple threads as a single unit
> making the thread to wait for some period of time
Halted:
This state is said to be halted if the thread is reached or finished its execution.
Note:
as long as thread is said to be present in new and halted states their execution states
is false, as long as thread is present in ready, running and waiting states whose
execution status is true.
Number of ways to create a Thread:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
In java we have 2 ways to create a thread . they are
1) by using java.lang.Thread class
2) by using java.lang.Runnable interface
By using java.lang.Thread class:
an object of Thread can be created in 3 ways. they are
1) Directly with new operator
Thread t1=new Thread(); // new state
2) Using Factory Method
Thread t2=Thread.currentThread(); // Factory Method
3) Using an object of sub class of Thread class
class th extends Thread
{
//
}
th t1=new th();
Here t1 is an object of the class which in turns an object of Thread class.
Thread class API:
Data Members:
public static final int MIN_PRIORITY(=1)
public static final int NORM_PRIORITY(=5)
public static final int MAX_PRIORITY(=10)
The above said data members are used for setting the priority to the Threads.
Hence they are known as thread Priority Modifiers.
constructors:
1) Thread():
This is used for creating an object of Thread Class without giving name of the
Thread. Ex: Thread t1=new Thread();
2) Thread(String):
This constructor is used for creating an object of Thread class by giving name of
the Thread. Ex: Thread t1=new Thread("java");
3) Thread(Runnable):
This constructor is used for converting Runnable Interface Object into Thread Class
Object. Runnable interface contains only run(), to enter into run() we must make
use of start() and other methods of Thread Class.
Ex: Runnable r=new th(); Thread t1=new Thread(r);
4) Thread(Runnable, String):
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
This constructor is similar to previous one in functionality but with this constructor we
can give name of the Thread.
Ex: Runnable r=new th();
Thread t1=new Thread(r,"java");
Instance methods:
1) public final void setName(String);
2) public void String getName();
The above methods are used for setting and getting the name to /from the
Thread.
3) public final void setPriority(int);
4) public final int getPriority();
The above methods are used for setting and getting the priority to /from the
Thread.
5) public final void start();
This method is used for bringing the Thread from new state to ready state.
In other words starting the Thread execution when we start the Thread it internally
calls run() of Thread class.
6) public void run();
In this method we must define the logic of the Thread always. In Thread
class, this method is defined with null body. To define our own logic of the Thread,
run() of Thread class must be overridden in derived class by inheriting from Thread
Class.
7) public final boolean isAlive();
This method is used for determining execution status of the Thread. This
method returns true when the Thread is in ready, running and waiting status. This
method returns false when the Thread is in new and halted states.
8) public final void suspend();
This method is used for suspending the currently executing Thread. If the
Thread is suspended, it stops the current execution and it will be entered into waiting
state from running state.
9) public final void resume();
This method is used for bringing the suspended Thread from waiting state to
ready state. When the Thread is resumed it starts executing where it left off
previously.
10) public final void join()throws InterruptedException;
This method is used for joining various fore ground Threads as a single unit.

Static methods:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
1) public static final Thread currentThread();
Thread t1=Thread.currentThread();
This method is used for obtaining name of the Threads which are by default
running in Java Environment.
2) public static final void sleep(long)throws InterruptedException;
Thread.sleep(10000);
Here parameter long represents amount of time to be represented interms
of milliseconds (1sec=1000 Millisecond).
This method is used for sending the Thread from running state to waiting
state for a period of time or making the Thread to sleep for some period of time.
Once the sleeping time is completed automatically Thread will be entered to ready
state from waiting state.
Note: If one Thread is sleeping at some address if any other Thread trying to sleep
at the same address then existing Thread will generate InterruptedException.
Sample Program:
public class ThreadDemo {
public static void main(String args[])
{
Thread t1=Thread.currentThread();
System.out.println("Name of the Thread:"+t1);
t1.setName("java");
System.out.println("Name after modified:"+t1);
System.out.println("Status of the Thread1:"+t1.isAlive());
Thread t2=new Thread();
System.out.println("Status of the Thread2:"+t2.isAlive());
System.out.println("Default Name of the Thread2:"+t2.getName());
System.out.println("MIN PRIORITY:"+Thread.MIN_PRIORITY);
System.out.println("MAX PRIORITY:"+Thread.MAX_PRIORITY);
System.out.println("NORM PRIORITY:"+Thread.NORM_PRIORITY);
}
}
Output:
Name of the Thread:Thread[main,5,main]
Name after modified:Thread[java,5,main]
Status of the Thread1:true
Status of the Thread2:false
Default Name of the Thread2:Thread-0
MIN PRIORITY:1
MAX PRIORITY:10
NORM PRIORITY:5

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

When Threads are in execution the data will be in the above said way.
 Each thread has its private run-time stack for storing variables and data.
 If two threads execute the same method, each will have its own copy of the stack
to store the method local variables.
 The objects instance variables are (Class variables) shared across all the threads,
they are not thread safe.

Stacks
class ThreadEx1 extends Thread {
int i = 0;
ThreadEx1(String name) {
this.setName(name);
}
public void run() {
for (i = 0; i < 5; i++) {
System.out.println("Printing From"+ Thread.currentThread().getName()
+ "The value of i ::"+ i);
try { Thread.sleep(300);
} catch (InterruptedException ex) {
ex.printStackTrace();
}}}}

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class ThreadExMain {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.currentThread();
System.out.println("The current Thread is" + t.getName());
System.out.println("The Current Thread Priority is" + t.getPriority());
t.setName("myThread");
t.setPriority(6);
System.out.println("The current Thread is" + t.getName());
System.out.println("The Current Thread Priority is" + t.getPriority());
ThreadEx1 ex1 = new ThreadEx1("First");
ThreadEx1 ex2 = new ThreadEx1("Second");
System.out.println("The Thread Priority of ex1 is" + ex1.getPriority());
System.out.println("The Thread Priority of ex2 is" + ex2.getPriority());
ex1.start();
ex2.start();
for (int i = 0; i < 5; i++) {
System.out.println("Printing From:"
+ Thread.currentThread().getName() + "::" + i);
Thread.sleep(100);
}
}
}
Output:

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Example For Join Method:


import java.io.BufferedReader;
import java.io.InputStreamReader;
class Th extends Thread {
public void run() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:");
System.out.println(i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class Th1 extends Thread {
public void run() {
try {
for (int i = 10; i > 0; i--) {
System.out.println("Thread Th1:");
System.out.println(i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
class Th2 extends Thread {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Base Value:");
float base = Float.parseFloat(br.readLine());
System.out.println("Enter the Height Value:");
float height = Float.parseFloat(br.readLine());
double area = 0.5 * base * height;
System.out.println("Area is:" + area);
} catch (Exception e) {
System.out.println(e);
}
}
}
public class ThreadDemo1 {
public static void main(String args[]) throws Exception
{ Th t1 = new Th();
Th1 t2 = new Th1();
Th2 t3 = new Th2();
System.out.println("Status of t1 before start:" + t1.isAlive());
t1.start();
t2.start();
t1.join();
t2.join();
t3.start();
System.out.println("Status of t1 After start:" + t1.isAlive());
}
}
Using java.lang.Runnable:
Runnable is one of the predefined interface used for developing Multithreading
applications.
An object of Runnable interface cannot be created directly but it can be created directly.
Runnable interface contains only one method.
Runnable interface API:
To develop a Multithreading program using Runnable interface we need to choose
our class and it must implement Runnable interface and we must over ride run().
class ThreadRunnableExample implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Printing From "+ Thread.currentThread().getName() + "
, the value of i :"+ i);
try { Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}}}

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public class ThreadRunnableEx {
public static void main(String[] args) throws InterruptedException {
ThreadRunnableExample r1 = new ThreadRunnableExample();
ThreadRunnableExample r2 = new ThreadRunnableExample();
Thread t1 = new Thread(r1, "First");
Thread t2 = new Thread(r2, "Second");
t1.start();
t2.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "::" + i);
Thread.sleep(100);
}
}
}
Example2:
class ThreadSample implements Runnable {
public Thread t;
public ThreadSample(String nm) {
t = new Thread(this, nm);
t.setName(nm);
}
public void run() {
System.out.println(t.getName());
if (t.getName().equals("First"))
Method1();
if (t.getName().equals("Second"))
Method2();
if (t.getName().equals("Third"))
Method3();
}
public void Method1() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void Method2() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(4000);
}
} catch (Exception e) {
System.out.println(e);
}
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
public void Method3() {
try {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread Th:" + t.getName() + " " + i);
Thread.sleep(5000);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
public class ThreadEx {
public static void main(String[] args) {
ThreadSample T = new ThreadSample("First");
ThreadSample T1 = new ThreadSample("Second");
ThreadSample T2 = new ThreadSample("Third");
T.t.start();
T1.t.start();
T2.t.start();
try {T.t.join();
T1.t.join();
T2.t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}System.out.println("Ok");
}
}

Why Runnable is better?


 If we inherit the Thread class for creating threads we cannot extend any other
class. Since Java does not support multiple inheritance
 By implementing the Runnable interface we can make the thread class extend
other classes.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

Observe The following Program without Join:


class JoinEx implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Printing From "+ Thread.currentThread().getName() + "
, the value of i :"+ i);
try {Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}}}}
public class JoinExMain {
public static void main(String[] args) throws InterruptedException {
JoinEx r1 = new JoinEx();
JoinEx r2 = new JoinEx();
Thread t1 = new Thread(r1, "First");
Thread t2 = new Thread(r2, "Second");
t1.start();
t2.start();
System.out.println("Main Thread Ends Here");
}}Output:
Main Thread Ends Here
Printing From Second , the value of i :0
Printing From First , the value of i :0
Printing From Second , the value of i :1
Printing From First , the value of i :1
Printing From Second , the value of i :2
Printing From First , the value of i :2
Printing From Second , the value of i :3
Printing From First , the value of i :3
Printing From First , the value of i :4
Printing From Second , the value of i :4
Printing From Second , the value of i :5
Printing From First , the value of i :5
Printing From Second , the value of i :6
Printing From First , the value of i :6
Printing From First , the value of i :7
Printing From Second , the value of i :7
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Printing From Second , the value of i :8
Printing From First , the value of i :8
Printing From First , the value of i :9
Printing From Second , the value of i :9

Observe The following Program with Join:


class JoinEx implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Printing From "+ Thread.currentThread().getName() + "
, the value of i :"+ i);
try {Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}}}}
public class JoinExMain {
public static void main(String[] args) throws InterruptedException {
JoinEx r1 = new JoinEx();
JoinEx r2 = new JoinEx();
Thread t1 = new Thread(r1, "First");
Thread t2 = new Thread(r2, "Second");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main Thread Ends Here");}} Output:
Printing From Second , the value of i :0
Printing From First , the value of i :0
Printing From Second , the value of i :1
Printing From First , the value of i :1
Printing From Second , the value of i :2
Printing From First , the value of i :2
Printing From Second , the value of i :3
Printing From First , the value of i :3
Printing From Second , the value of i :4
Printing From First , the value of i :4
Printing From First , the value of i :5
Printing From Second , the value of i :5
Printing From Second , the value of i :6
Printing From First , the value of i :6
Printing From Second , the value of i :7
Printing From First , the value of i :7
Printing From Second , the value of i :8
Printing From First , the value of i :8
Printing From Second , the value of i :9
Printing From First , the value of i :9
Main Thread Ends Here

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
What is Synchronization:

Synchronization is a mechanisam of allowing only one Thread at a time among ‘N’


number of Threads into that area which is sharable to perform read and write
operations.
If any thing is sharable by multiple Threads then there is a possibility of getting
inconsistent result. In order to get consistent result the sharable thing must be made as
Synchronized by using “Synchronized” keyword.
In Synchronization process Locking and Un Locking process is continued as long as
all the Threads are executing.
Synchronization Techniques:
In Java we have 2 types of Synchronization techniques. They are
1) Synchronized Methods
2) Synchronized Blocks
Synchronized Methods: Synchronized Methods are of 2 types. They are
1) Synchronized Instance Methods
2) Synchronized Static Methods
Synchronized Instance Method: If an ordinary instance method is sharable by
multiple Threads, then there is a possibility of generating inconsistent result. To avoid
this in consistent result, ordinary instance method definition must be made as
Synchronized.
When an ordinary instance method is Synchronized, then the corresponding class
Object will be Locked.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Syntax:
synchronized return_type methodName(List of Parameters if any)
{
Block of stmt(s);
}
Eg: class Account
{ int bal=0;
synchronized void deposit(int amt)
{ bal=bal+amt;
System.out.println(“Current Balance=”+amt);
}
} When one of the Thread is executing deposit(), the account class Object is Locked and
if any other Threads are trying to access deposit() then they made wait by the JVM until
the current Thread completes its execution.
Synchronized static method:
If an ordinary static method is sharable by multiple Threads, then there is a
possibility of generating inconsistent result. To avoid this in consistent result, ordinary
static method definition must be made as Synchronized.
When an ordinary static method is made as synchronized then the corresponding
class will be locked.
Syntax:
synchronized static return_type methodName(List of Parameters if any)
{
Block of stmt(s);
}
Eg: class Account
{ static int bal=0;
Synchronized static void deposit(static int amt)
{ bal=bal+amt;
System.out.println(“Current Balance=”+amt);
}
} if one Thread is executing deposit() then the corresponding class will be locked and at
the same time if any other Threads are trying to access then those Threads must be
made wait until current Thread completes its execution.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
Synchronized Blocks:
When we inherit non Synchronized Methods from Base Class or Base Interface into
the derived class, with in the derived class we cannot change the prototype of Base
Class/ Interface methods i.e. Non- Synchronized Methods cannot be made as
Synchronized Methods with in the derived class. Hence, we must use Synchronized
blocks.
Synchronized blocks is an alternative arrangement for Synchronized Methods for
achieving Synchronization technique. Synchronized blocks must be always written with
in the non- Synchronized Method.
synchronized(Object of Current Class)
{
Block of statement(s);
}
Sample Program for Synchronized Method:
class Account {
int bal = 0;
synchronized void deposit(int amt)
// void deposit(int amt)
{
bal = bal + amt;
System.out.println("Current Balance=" + bal);
}
int getBal() {
return bal;
}
}
class Customer extends Thread {
Account ac;
public Customer(Account ac) {
// TODO Auto-generated constructor stub
this.ac = ac;
}
public void run() {
ac.deposit(1000);
}
}
public class SyncDemo1 {
public static void main(String[] args) {
Account ac = new Account();
Customer cu[] = new Customer[5];
for (int i = 0; i < 5; i++) {
cu[i] = new Customer(ac);
}
for (int i = 0; i < 5; i++) {
cu[i].start();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY
try {
for (int i = 0; i < 5; i++) {
cu[i].join();
}
} catch (InterruptedException ie) {
System.out.println("Problem in Thread execution");
}
System.out.println("Total Bal=" + ac.getBal());
}
}
Example Program for Synchronized Blocks:
class Account1 { int bal = 0;
void deposit(int amt) {
synchronized (this) {
bal = bal + amt;
System.out.println("Current Balance=" + bal);
}
}
int getBal() {
return bal;
}
}
class Customer1 extends Thread {
Account1 ac;
public Customer1(Account1 ac) {
// TODO Auto-generated constructor stub
this.ac = ac;
}
public void run() {
ac.deposit(1000);
}
}
public class SyncDemo2 {
public static void main(String[] args) {
Account1 ac = new Account1();
Customer1 cu[] = new Customer1[5];
for (int i = 0; i < 5; i++) {
cu[i] = new Customer1(ac);
}
for (int i = 0; i < 5; i++) {
cu[i].start();
}
try { for (int i = 0; i < 5; i++) {
cu[i].join();
}
} catch (InterruptedException ie) {
System.out.println("Problem in Thread execution");
}
System.out.println("Total Bal=" + ac.getBal());
}}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

The process of exchanging the data between Multiple Threads is known as Inter
Thread Communication (or) An output of one Thread is given as an input to some other
Thread. And the output of some other Thread is given as input to some other thread,
then this type of communication is known as Inter Thread Communication.
In order to develop inter thread communication applications we must use some
predefined methods which are present in java.lang.Object

wait(): Is used for making the Thread to wait witout specifying any amount of time.
After that Thread will be entered from waiting stae to ready state.
notify():Is used for bringing the Thread from waiting state to ready state one Thread at
a time.
notifyAll(): Is used for bringing multiple Threads from waiting state to ready state.

urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

class Main
{ int i=1;
synchronized void zig()
{ if(i==1){
System.out.println("Zig");
i=2;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){}
}
}
synchronized void zag()
{ if(i==2)
{ System.out.println("Zag");
i=3;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){}
}
}
synchronized void zoom()
{ if (i==3)
{System.out.println("Zoom");
i=1;
notifyAll();
}
else
{ try{
wait();}
catch(InterruptedException e){

}
}
}
}
class P implements Runnable
{ Main M;
Thread t;
P(Main M)
{ this.M=M;
t=new Thread(this,"P");
t.start();
}
urtrainer.java@gmail.com
Java Fundamentals JAVA CSREDDY

public void run()


{ while(true)
{ M.zig();
}
}
}
class Q implements Runnable
{ Main M;
Thread t;
Q(Main M)
{ this.M=M;
t=new Thread(this,"Q");
t.start();
}
public void run()
{ while(true)
{ M.zag();
}
}
}
class R implements Runnable
{ Main M;
Thread t;
R(Main m)
{ M=m;
t=new Thread(this,"R");
t.start();
}
public void run()
{ while(true)
{
M.zoom();
}
}
}
public class Sample {
@SuppressWarnings("unused")
public static void main(String[] args) {
Main M=new Main();
P p=new P(M);
Q q=new Q(M);
R r=new R(M);
}
}

urtrainer.java@gmail.com

You might also like