Documents Null-Core+Java+Notes Madhu
Documents Null-Core+Java+Notes Madhu
Documents Null-Core+Java+Notes Madhu
Java Introduction :
package com.madhu.basics;
} }
As per the sun micro system standard the java language is divided into three types.
J2SE:-
Standalone applications:-
1) Standalone applications are the java applications which don’t need the client
server architecture.
2) The standalone applications applicable for the only one desktop hence it is called
J2EE:-
Web-applications:-
1) Web applications are the java applications which needs client and server concept.
2) Web applications must need the internet connections to access the application.
J2ME:-
By using j2me we are able to develop the applications that applications only run on
mobile devices.
Java Features :
1. Simple:-
Java technology has eliminated all the difficult and confusion oriented concepts
like pointers, multiple inheritance in the java language.
The c,cpp syntaxes easy to understand and easy to write. Java maintains C and CPP
syntax mainly hence java is simple language.
Java tech takes less time to compile and execute the program.
2. Object Oriented:-
Java is object oriented technology because to represent total data in the form of
object.
By using object reference we are calling all the methods, variables which is present
in that class.
The total java language is dependent on object only hence we can say java is a object
oriented technology.
3. Platform Independent :-
Compile the Java program on one OS (operating system) that compiled file can execute
in any OS(operating system) is called Platform Independent Nature. The java is
platform independent language. The java applications allows its applications
compilation one operating system that compiled (.class) files can be executed in any
operating system.
4. Architectural Neutral:-
Java tech applications compiled in one Architecture (hardware----RAM, Hard Disk) and
that Compiled program runs on any hardware architecture(hardware) is called
Architectural Neutral.
5. Portable:-
In Java tech the applications are compiled and executed in any OS(operating system)
and any Architecture(hardware) hence we can say java is a portable language.
6. Robust:-
1 Exception Handling
2 Memory Allocation
a. JAVA is having very good predefined Exception Handling mechanism whenever we are
getting exception we are having meaning full information.
b. JAVA is having very good memory management system that is Dynamic Memory (at
runtime the memory is allocated) Allocation which allocates and deallocates memory
for objects at runtime.
7. Secure:-
To provide implicit security Java provide one component inside JVM called Security
Manager.
To provide explicit security for the Java applications we are having very good
predefined library in the form of java.Security.package.
Web security for web applications we are having JAAS(Java Authentication and
Authorization Services) for distributed applications.
8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the memory
is allocated) and dynamic loading to perform the operations.
9. Distributed:-
10. Multithreaded: -
If any tech allows executing single thread at a time such type of technologies is
called single threaded technology.
If any technology allows creating and executing more than one thread called as
Multithreaded technology called JAVA.
11. Interpretive:-
Download the software from internet based on your operating system. The software is
different from 32-bit operating and 64-bit operating system.
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
for 32-bit operating system please click on Windows x86 :- 32- bit operating system
for 64-bit operating system please click on Windows x64 :- 64-bit operating system
After installing the software the java folder is available in the following location
To check whether the java is installed in your system or not go to the command
prompt. To open the command prompt
Whenever we are getting above information at that moment the java is installed but
the java is not working properly.
C:/>javac
1) Operating system will pickup javac command search it in the internal operating
system calls. The javac not available in the internal command list .
2) Then operating system goes to environmental variables and check is there any path
is sets or not. up to now we are not setting any path. So operating system don’t know
anything about javac command Because of this reason we are getting error message.
Hence we have to environmental variables. The main aim of the setting environmental
variable is to make available the fallowing commands javac,java,javap (softwares) to
the operating system.
Now the java is working good in your system. open the command prompt to check once
Class Test
1. variables
2. methods
3. constructors
4. instance blocks
5. static blocks
Static :- To provide direct access permission to the jvm declare main is static(with
out creation of object able to access main method)
String[] args :- used to take command line arguments(the arguments passed from
command prompt)
Ex:-
Class Test
{ int a=10;
System.out.println(“java tokens”);
Print():-
Print is used to print the statement into the console and the control is available in
the same line.
Ex:-
System.out.print(“Techfort”);
Println():-
In the println statement Print is used to print the statement into the console and ln
represent go to the new line now the control is available in the next line.
Ex:-
System.out.println(“Techfort”);
Output:- Techfort
Identifiers:-
Any name in the java program like variable name,class name, method name, interface
name is called identifier.
Ex:-
class Test
void add()
int a=12;
int b=13;
1. All Java classes, Abstract classes and Interface names should start with uppercase
letter ,if any class contain more than one word every innerword also start with
capital letters.
Ex:- String
StringBuffer
2. All java methods should start with lower case letters and if the method contains
more than one word every innerword should start with capital letters.
Ex :- post()
toString()
toUpperCase()
3. All java variables should start with lowercase letter and inner words start with
uppercase letter.
Ex:- pageContent
bodyContent
Ex:- MIN_PRIORITY
MAX_PRIORITY
NORM_PRIORITY
5. All java packages should start with lower case letters only.
Ex:- java.awt
Java.io
Java Comments :-
To provide the description about the program we have to use java comments.
By using single line comments we are providing description about our program within a
single line.
This comment is used to provide description about our program in more than one line.
Syntax:- /*…………….line-1
……………..line-2
*/
3) Documentation Comments:-
This comment is used to provide description about our program in more than one page.
In general we are using document comment to prepare API kind of documents but it is
not suggestable.
Syntax:- /*…………….line-1
*……………..line-2
line-3
*/
Control statements :-
Conditional statements
Iteration statements
If syntax:-
if (condition)
Statements;
The curly brasses are optional whenever we are taking single statements.
The curly brasses are mandatory whenever we are taking multiple statement.
Ex:-
class Test
{
int a=10;
if (a>5)
If-else syntax:-
if (condition)
else
The curly brasses are optional whenever we are taking single statements.
The curly brasses are mandatory whenever we are taking multiple statements.
Ex:-
class Test
int a=10;
int b=20;
if (a<b)
else
System.out.println("hi madhu");
Switch statement:-
2) Curly brasses are mandatory if we are not taking we are getting compilation error.
3) Inside the switch It is possible to declare any number of cases but is possible to
declare only one default.
a. Byte
b. Short
c. Int
d. Char
5) Float and double and long is not allowed for a switch argument because these are
having more number of possibilities (float and double is having infinity number of
possibilities) hence inside the switch statement it is not possible to provide float
and double and long as a argument.
Iteration Statements:-
If we want to execute group of statements repeatedly or more number of times then we
should go for iteration statements.
1) for
2) while
3) do-while
for syntax:-
Body;
Body;
The curly brasses are optional whenever we are taking single statement.
The curly brasses are mandatory whenever we are taking more than one statements.
Ex:-
class Test
for(int i=0;i<5;i++)
{
System.out.println(“Techfort software services pvt ltd”);
Do-While:-
1) If we want to execute the loop body at least one time them we should go for do-
while statement.
2) In the do-while first body will be executed then only condition will be checked.
3) In the do-while the while must be ends with semicolon otherwise we are getting
compilation error.
4) do is taking the body and while is taking the condition and the condition must be
Boolean condition.
Syntax:-do
//body of loop
} while(condition);
Ex :-
class Test
int i=0;
do
System.out.println("Kodanda Ramu");
i++;
}while (i<10);
}
Transfer statements:- by using transfer statements we are able to transfer the flow
of execution from one position to another position .
1. break
2. continue
3. return
4. try
break:- we are able to use the break statement only two places if we are using any
other place the compiler will raise compilation error.
class Test
if (i==5)
break;
System.out.println(i);
Continue:- (skip the current iteration continue the rest of the iterations normally)
class Test
{
public static void main(String[] args)
if (i==5)
continue;
System.out.println(i);
Data Types:-
1) Data types are used to represent the type of the variable and type of the
expression.
2) Data types are used to specify the how much memory is allocated for variables.
Variables :- used to store the values. While declaring variable we must specify the
type of the variable by using data types concept.
Local variables
Instance variables
Static variables
Local variables : The variables which are declare inside a method & inside a block &
inside a constructor is called local variables
The scope of local variables are inside a method or inside a constructor or inside a
block.
Ex:-
class Test
int b=20;
System.out.println(a+b);
Instance variables:-
The variables which are declare inside a class and outside of the methods is called
instance variables.
We are able to access instance variables only inside the class any number of methods.
Ex:-
class Test
int a=10;
int b=20;
void add()
System.out.println(a+b);
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
3. Static variables:-
The instance variables which are declared as a static modifier such type of variables
are called static variables.
We are able to access static variables within the class any number of methods.
class Test
System.out.println(a+b);
void add()
System.out.printl(a+b);
a. Directly possible.
Ex:-
class Test
{
//1-way(directly possible)
System.out.println(a);
System.out.println(Test.a);
System.out.println(t.a);
1. Instance variable for the each and every object one separate copy is maintained.
2. Static variable for all objects same copy is maintained. One Object change the
value another object is affected.
Ex:-
class Test
int a=10;
System.out.println(t1.a);//10
System.out.println(t1.b);//20
t1.a=444;
t1.b=555;
System.out.println(t2.a);//10
System.out.println(t2.b);//555
t2.b=111;
System.out.println(t2.b);//111
System.out.println(t3.a);//10
System.out.println(t3.b);//111
System.out.println(t4.a);//10
System.out.println(t4.b);//111
Java is classes based based language we are able to design the program by using
classes and objects.
A class is a template or blue print from which type of objects are created.
Creation of object :
Test Class
t Reference variable
new Keyword/operator
Test() Constructor used to intialize
Arrays :
Arrays are used to store the multiple numbers of elements of single type.
The length of the array is established at the time of array creation. After creation
the length is fixed.
The items presented in the array are classed elements. Those elements can be accessed
by index values. The index is begins from (0).
Advantages of array:-
int[] a;
int []a;
int a[];
a[0]=10;
a[1]=20;
a[2]=30;
a[4]=40;
Example 1 :
package com.madhu.basics;
int a[]={10,20,30,40};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
package com.madhu.basics;
int a[]={10,20,30,40};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
Example 3 : (using for-each loop) (1.5 version)
package com.madhu.basics;
int a[]={10,20,30,40};
for(int a1:a)
System.out.println(a1);
int[][] a;
int [][]a;
int a[][];
int []a[];
Ex:-
class Test
int[][] a={{10,20,30},{40,50,60}};
System.out.println(a[0][0]); //10
System.out.println(a[1][0]); //40
System.out.println(a[1][1]); //50
}
Methods (behaviors):-
3) Inside the class it is possible to declare any number of methods based on the
developer requirement.
5) It will improve the reusability of the code. By using methods we can optimize the
code.
Syntax:-
Ex:-
Method Signature:-
The name of the method and parameter list is called Method Signature. Return type and
modifiers list not part of a method signature.
Ex:-
package com.madhu.basics;
1) Accessor methods just used to read the data. To read the reading the data use
getters methods.
2) Mutator methods used to store the data and modify the data for the storing of data
use setters methods.
class Test
String name;
int id;
this.name=name;
this.id=id;
}
String getName()
return name;
int getId()
return id;
t.setId(101);
String name=t.getName();
System.out.println(name);
int id=t.getId();
System.out.println(id);
Constructors :-
2) If we want to perform any operation at the time of object creation the suitable
place is constructor.
3) Inside the java programming the compiler is able to generate the constructor and
user is able to declare the constructor. so the constructors are provided by compiler
and user.
There are two types of constructors :
1) Default Constructor.
b. parameterized constructor
Default Constructor:-
1) in the java programming if we are not providng any constructor in the class then
compiler provides default constructor.
4) The compiler generated default constructor is executed by the JVM at the time of
execution.
Based on the user requirement user can provide zero argument constructor as well as
parameterized constructor.
2) Constructor doesn’t have no explicit return type if we are providing return type
we are getting any compilation error and we are not getting any runtime errors just
that constructor treated as normal method.
package com.madhu.constructors;
Test()
System.out.println("Default constructor");
}
Test(int a, int b)
System.out.println("parameterised constructor");
int c = a + b;
The main purpose of the inheritance is code extensibility whenever we are extending
automatically the code is reused.
In inheritance one class giving the properties and behavior and another class is
taking the properties and behavior.
Inheritance is also known as is-a relationship means two classes are belongs to the
same hierarchy.
In the inheritance the person who is giving the properties is called parent the
person who is taking the properties is called child.
To reduce length of the code and redundancy of the code sun peoples introducing
inheritance concept.
Types of inheritance :
Single inheritance : Extending the properties from single parent class to single
child class is known as single inheritance.
Ex:-
class Parent
{
void m1()
void m2()
Multi level inheritance : one super and one sub class at each and every level.
Multiple inheritance : The process of getting properties and behaviors form more than
one super class to the one child class. The multiple inheritance is not possible in
the java language using classes and it is supported using interfaces. so one class
can extends only one class at time it is not possible to extends more than one class
at time.
Hierarchical inheritance:- The process of getting properties and behaviors from one
super class to the more than one sub classes is called hierarchical inheritance.
Polymorphism is a Greek word poly means many and morphism means forms.
Method Overloading:-
1) Two methods are said to be overloaded methods if and only if two methods are
having same name but different argument list.
Eg:-
package com.madhu.oops;
void add()
void add(int a)
{
int c=a+b;
m.add();
m.add(12);
m.add(12, 14);
Eg:-
package com.madhu.oops;
class OverLoadMain
System.out.println(a);
System.out.println(ch);
main('r');
Method Overriding :-
1) If the child class not satisfy the parent class method implementation then it is
possible to override that method in the child class based on child class requirement.
3) In the overriding concept the child class and parent class method signatures must
be same otherwise we are getting compilation error.
Eg:-
package com.madhu.oops;
void show()
package com.madhu.oops;
void show()
super.show();
s.show();
Super keyword : if we have same method name with same number of arguments in parent
class and child class, if we call the method by using child class object child class
method will be called. In order to call parent class method we have to use super
keyword.
Abstraction:-
Hiding the internal implementation and highlighting the set of services that process
is called abstraction.
Ex:-
a. Bank ATM Screens (Hiding thee internal implementation and highlighting set of
services like withdraw, money transfer, mobile registration).
b. Mobile phones (The mobile persons are hiding the internal circuit implementation
and highlighting touch screen).
c. Syllabus copy (the institutions persons just highlighting the set of contents that
persons provided the persons are not highlighting the whole content).
Interfaces
The way of representation the methods are divided into two types
1) Normal methods
2) Abstract methods
Normal methods:-
Ex:-
Void m1()
---------
--------body;
---------
Abstract methods:-
The method which is having declaration but not implementations such type of methods
are called abstract Method. Hence every abstract method should end with “;”.
The child classes are responsible to provide implementation for parent class abstract
methods.
Based on above representation of methods the classes are devided into two types
1) Normal classes
2) Abstract classes
Normal classes:-
Abstract class:- Abstract class is a jav class which contains at least one abstract
method.To specify the particular class is abstract and particular method is abstract
method to the compiler use abstract modifier.
For the abstract classes it is not possible to create an object. Because it contains
the un implemented methods.
For any class if we don’t want instantiation then we have to declare that class as
abstract i.e., for abstract classes instantiation (creation of object) is not
possible.
Eg:-
package com.madhu.oops;
void deposit()
void withDrawl()
{
System.out.println("we can with draw upto 2 lakhs");
package com.madhu.oops;
void loan()
void interest()
System.out.println("interest is 2%");
b.deposit();
b.withDrawl();
b.loan();
b.interest();
if the child class is unable to provide the implementation for parent class abstract
methods at that situation we can declare that class is an abstract then take one more
child class in that class provide the implementation for remaining methods.
Even though class does not contain any abstract method still we can declare the class
as abstract i.e. abstract class can contain zero number of abstract methods. The
abstract classes it is not possible to create object.
Interfaces :
Interface is also one of the type of class it contains only abstract methods.
Each and every interface by default abstract hence it is not possible to create an
object.
Interfaces not alternative for abstract class it is extension for abstract classes.
Interfaces giving the information about the functionalities it are not giving the
information about internal implementation.
To provide implementation for abstract methods we have to take separate class that
class we can called it as implementation class for that interface.
Eg:-
package com.madhu.oops;
void deposit();
void withDrawl();
void loan();
void interest();
package com.madhu.oops;
System.out.println("interest is 2%");
b.deposit();
b.withDrawl();
b.loan();
b.interest();
Encapsulation:-
The process of binding the data and code as a single unit is called encapsulation.
We are able to provide more encapusulation by taking the private data(variables)
members. To get and set the values from private members use getters and setters to
set the data and to get the data.
Ex:-
class Encapsulation
this.sid=sid;
return sid;
this.sname=sname;
return sname;
class Test
{
public static void main(String[] args)
e.setSid(100);
e.setSname("ratan");
int num=e.getSid();
String name=e.getSname();
System.out.println(num);
System.out.println(name);
Strictfp:-
If a class is declared as stictfp then every concrete method in that class will
follow IEEE754 standard so we will get platform independent results.
Native:-
Native is the modifier only for methods but not for variables and classes.
The native methods are implemented in some other languages like C and C++ hence
native methods also known as “foreign method”.
For native methods implementation is always available in other languages and we are
not responsible to provide implementation hence native method declaration should
compulsory ends with “;”.
Scanner :-
Eg :-
import java.util.*;
class Test
String ename;
int eid;
double esal;
int eage;
void details()
String ename=s.next();
this.ename=ename;
int eid=s.nextInt();
this.eid=eid;
System.out.println("enter emp sal");
double esal=s.nextDouble();
this.esal=esal;
System.out.println("enter age");
int eage=s.nextInt();
this.eage=eage;
void display()
System.out.println("************emp details***********");
System.out.println(ename);
System.out.println(eid);
System.out.println(esal);
System.out.println(eage);
void status()
if (eage>40)
System.out.println("not elgible");
else
System.out.println("elgible");
{
Test t=new Test();
t.details();
t.display();
t.status();
Packages :-
5) Whenever we are dividing the project into the packages(modules) the sharability of
the project will be increased.
Syntax:-
Package package_name;
1) Predefined packages
Predefined packages:-
The java predefined packages are introduced by sun peoples these packagescontains
predefined classes and interfaces.
Ex:- java.lang
Java.io
Java.awt
Java.util
Java.net………………………..etc
Java.lang:-
The most commonly required classes and interfaces to write a sample program is
encapsulated into a separate package is called java.lang package.
` Ex:- String(class)
StringBuffer(class)
Object(class)
Runnable(interface)
Cloneable(nterface)
Note:-
the default package in the java programming is java.lang if we are importing or not
importing by default this package is available for our programs.
Java.io package:-
The classes which are used to perform the input output operations that are present in
the java.io packages.
Ex:- FileInputStream(class)
FileOutputStream(class)
FileWriter(class)
FileReader(class)
Java.net package :-
The classes which are required for connection establishment in the network that
classes are present in the java.net package.
Ex:- Socket
ServerSocket
InetAddress
URL
Java.awt package:-
The classes which are used to prepare graphical user interface those classes are
present in the java.awt package.
Ex:- Button(class)
Checkbox(class)
Choice(Class)
List(class)
1) The packages which are declared by the user are called user defined packages.
2) In the single source file it is possible to take the only one package. If we are
trying to take two packages at that situation the compiler raise a compilation error.
Whenever we taking package name don’t take the names like pack1, pack2, madhu,
ramu……… these are not a proper coding formats.
Access Modifiers :-
Public :-
This is the modifier applicable for classes, methods and variables (only for instance
and static variables but not for local variables).
If a class is declared with public modifier then we can access that class from
anywhere (within the package and outside of the package).
Default :-
This is the modifier applicable for classes, methods and variables (only for instance
and static variables but not for local variables).
If a class is declared with <default> modifier then we can access that class only
within that current package but not from outside of the package.
If a member declared as private then we can access that member only from within the
current class.
If a method declare as a private we can access that method only within the class. it
is not possible to call even in the child classes also.
Protected :-
If a member declared as protected then we can access that member with in the current
package anywhere but outside package only in child classes.
But from outside package we can access protected members only by using child
reference. If we try to use parent reference we will get compile time error.
Members can be accesses only from instance area directly i.e., from static area we
can’t access instance members directly otherwise we will get compile time error.
String :-
Eg :-
package com.madhu.strings;
String s="madhu";
System.out.println(s);
s.concat("kumar");
System.out.println(s);
String s1=s.concat("kumar");
System.out.println(s1);
System.out.println(s1.length());
System.out.println(s1.getClass());
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.hashCode());
StringBuffer :-
StinrgBuffer is mutable:-
Ex:-
class Test
s1.append("addanki");//mutability
System.out.println(s1);
StringBuffer s3=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1==s2);
System.out.println(s1==s3);
class Test
Test t2=t1;
System.out.println(t1.equals(t2)); //true
System.out.println(t1.equals(t3)); //false
String str1="ratan";
String str2="ratan";
System.out.println(str1.equals(str2)); //true
StringBuffer sb3=sb2;
System.out.println(sb1.equals(sb2)); //false
System.out.println(sb2.equals(sb3)); //true
StringBuilder :-
multiple threads are allow to operate on StringBuilder methods hence the performance
of the application is increased.
Cloneable :-
Eg :-
int a=10;
int b=20;
Test t2=(Test)t1.clone();
t1.a=100;
t1.b=200;
System.out.println(t1.a+"----"+t1.b);
System.out.println(t2.a+"----"+t2.b);
Wrapper classes :-
To represent primitive data types as a Object form we required some classes these
classes are called wrapper classes.
We are having 8 primitive data types hence sun peoples are providing 8 wrapper
classes.
Byte, Short, Integer, Long, Float, Double these are child classes of Number class.
Eg :-
class Test
float f=10.7f;
System.out.println(f1);
System.out.println(f2);
System.out.println(f3); //NumberFormatException
System.out.println(i1);
System.out.println(i2); //NumberFormatException
}
}
class Test
System.out.println(a);
System.out.println(i);
System.out.println(i.toString());
To convert a data types into the object means we are giving object from data types by
using constructor.
Utility methods:-
1. valueOf()
2. xxxValue()
3. parsexxx()
4. toString()
1) valueOf():-
Ex :-
class Test
{
public static void main(String[] args)
System.out.println(i);
Boolean b=Boolean.valueOf("true");
System.out.println(b);
XxxValue():-
by using XXXValue() method we are converting wrapper objects into the corresponding
primitive values.
Ex :-
class Test
Integer i=Integer.valueOf(150);
char ch=c.charValue();
System.out.println(ch);
Boolean b=new Boolean(false);
boolean bb=b.booleanValue();
System.out.println(bb);
parseXXX():-
by using above method we are converting String into the corresponding primitive.
Ex :-
class Test
String str1="10";
String str2="20";
System.out.println(str1+str2); //1020
int a=Integer.parseInt(str1);
float f=Float.parseFloat(str2);
System.out.println(a+f); //30.0
Until 1.4 version we are not allowed to place primitive in the palc wrapper and
wrapper in the place of primitive. The programmer is responsible person to do the
explicit conversion primitive to the wrapper and wrapper to the primitive.
Autoboxing :-
Integer i=10;
System.out.println(i);
The above statement does not work on the 1.4 and below versions. The auto conversion
of the primitive into the Wrapper object is called the autoboxing these conversions
done by compiler at the time of compilation.
Autounboxing:-
System.out.println(a);
The auto conversion of the wrapper object to the primitive value is called
autounboxing and these conversions are done by compiler at the time of compilation.
Ex :-
class Test
j=i;
System.out.println(j);
print(i);
System.out.println(j);
Java.io is a package which contains number of classes by using that classes we are
able to send the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
1. Byte format
2. Character format
Java.io.FileInputStream
To read the data from the destination file to the java application we have to use
FileInputSream class.
To read the data from the .txt file we have to read() method.
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.
import java.io.*;
class Test
try
fis=new FileInputStream("get.txt");
fos=new FileOutputStream("set.txt",true);
int c;
while ((c=fis.read())!=-1)
fos.write(c);
}
fis.close();
fos.close();
catch(IOException io)
System.out.println("getting IOException");
BufferedReader:- to read the data line by line format and we have to use readLine()
to read the data.
PrintWriter :- to write the data line by line format and we have to use println() to
write the data.
import java.io.*;
class Test
Try
String line;
while ((line=br.readLine())!=null)
{
pw.println(line);
br.close();
pw.close();
catch(IOException io)
System.out.println("getting IOException");
Buffered Streams:-
Up to we are working with non buffered streams these are providing less performance
because these are interact with the hard disk, network.
1. BufferedInputStream
2. BufferedOutputStream
3. BufferedReader
4. BufferedWriter
Ex:-
import java.io.*;
class Test
Try
String str;
while ((str=br.readLine())!=null)
bw.write(str);
br.close();
bw.close();
catch(Exception e)
System.out.println("getting Exception");
Serialization:-
The process of saving an object to a file (or) the process of sending an object
across the network is called serialization.
But strictly speaking the process of converting the object from java supported form
to the network supported form of file supported form.
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network supported form
to the java supported form is called deserialization.
1. FileInputStream
2. ObjectInputStream
Ex:-
import java.io.Serializable;
int id;
String name;
int marks;
this.id = id;
this.name = name;
this.marks=marks;
To perform serialization :- we are writing the object data to the file called abc.txt
file we are transferring that file across the network.
import java.io.*;
class Serializable1
oos.writeObject(s1);
oos.flush();
To perform deserialization:- in the network the file is available with java data to
read the data we have to go for deserialization.
import java.io.*;
class Deserialization
//deserialization process
Student s=(Student)ois.readObject();
System.out.println("deserialization success");
Transient :- Transient modifier is the modifier applicable for only variables and we
can’t apply for methods and classes.
Eg :-
import java.io.*;
import java.io.Serializable;
class Serializable1
oos.writeObject(s1);
Student s=(Student)ois.readObject();
}
Exception Handling :-
An unwanted unexpected event that disturbs normal flow of execution called exception.
Exception is occurred when the network has disconnected at the middle of the
communication.
Types of Exceptions:-
As per sun micro systems standards The Exceptions are divided into three types
1) Checked Exception
2) Unchecked Exception
3) Error
Checked Exception :-
The Exceptions which are checked by the compiler at compilation time for the proper
execution of the program at runtime is called CheckedExceptions.
Ex :- IOException,SQLException etc.
Exception Description
ClassNotFoundException If the loaded class is not available
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface.
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an object of an
abstract class or interface.
InterruptedException One thread has been interrupted by
another thread
NoSuchMethodException If the requested method is not available
UncheckedException :-
The exceptions which are not checked by the compiler at compilation time is called
uncheckedException. These checking down at run time only.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.(out of
range)
ClassCastException If the conversion is Invalid.
IllegalArgumentException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NullPointerException Invalid use of a null reference.
Error :-
Errors are caused by lack of system resources . these are non recoverable.
Good point:-
Exception:-
An exception is unwanted unexpected event these are caused by the programmer mistake.
Exceptions are recoverable.
Error :-
Errors are caused by lack of system resources . these are non recoverable.
Ex :- StackOverFlowError,AssertionError etc.
Note :-
1) RuntimeException and its child classes and Error and its child classes are
Unchecked remaining all are checkedExceptions.
1) try
2) catch
3) finally
4) throw
5) throws
Exception Handling :-
1) In java language we are handling the exceptions By using try and catch blocks. try
block contains risky code of the program and catch block contains handling code of
the program.
2) Catch block code is a alternative code for Exceptional code. If the exception is
raised the alternative code is executed fine then rest of the code is executed
normally.
Syntax :-
try
Risky code
Catch(ExceptionName reference_variable)
}
Before try and catch :- The program goes to abnormal termination
class Test
System.out.println("Techfort");
System.out.println(10/0);
System.out.println("solutions");
Output :- Techfort
Software
1) If we are taking try-catch the program goes to normal termination. Because the
risky code we are taking inside the try block and handling code we are taking inside
the catch block.
2) If the exception is raised in the try block the corresponding catch block is
executed.
class Test
System.out.println("Techfort");
System.out.println("software");
try
{
System.out.println(10/0);
catch (ArithmeticException e)
System.out.println("solutions");
Output:- Techfort
Software
Solutions.
Ex :-
Exception raised in try block the JVM will search for corresponding catch block if
the catch block is matched, corresponding catch block will be executed and rest of
the code is executed normally.
class Test
System.out.println("program starts");
try
int[] a={10,20,30};
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
catch(ArrayIndexOutOfBoundsException ae)
Finally block :-
Syntax :-
try
risky code;
handling code;
finally
free code;
}
Ex :- Exception raised in try block and corresponding catch block is matched then
rest of the code is executed normally.
class Test
try
System.out.println("Techfort");
System.out.println(10/0);
finally
Output :- Techfort
2) Throw keyword works like a try block. The difference is try block is automatically
find the situation and creates a Exception object implicitly. Whereas throw keyword
creates a Exception object explicitly.
Ex :-
class Test
try
System.out.println(10/0);
Note :-
In the above program the main method is responsible to create a exception object. So
the main method is creating exception object implicitly. The programmer is not
responsible person to creates a exception object.
Ex :-
class Test
Output:-
Throws :-
1) Throw keyword is used to create exception object explicitly. But the main purpose
of the throws keyword is bypassing the generated exception from present method to
caller method.
2) Throw keyword is used in the method body. But throws keyword we have to use in the
method declaration.
Ex :-
import java.io.*;
class Student
void studentDetails()
try
String sname=br.readLine();
System.out.println(“u r name is:”+sname);
catch(IOException e)
s1.studentDetails();
Ex 1:-
import java.io.*;
class Student
String sname=br.readLine();
s1.studentDetails();
}
Ex 2 :-
import java.io.*;
class Student
String sname=br.readLine();
try
s1.studentDetails();
}
Exceptions :-
1) Predefined Exceptions.
Predefined Exception:-
Predefined classes comes along with the software based on your requirement we have to
create a objects.
Ex :- ArithmeticException,IOException,NullPointerException…………..etc
Based on the user requirement user can creates a Exception is called user defined
Exception.
Ex:InvaliedAgeException,BombBlostException………..etc
1) To create user defined exception we have to take an user defined class that is a
sub class to the RuntimeException(for creation of unchecked Exceptions) .
2) To create user defined exception we have to take user defined class that is
subclass to the Exception(for creation of checked Exceptions)
a) default constructor
b) parameterized constructor
Eg :-
import java.util.*;
class Test
if (age<18)
else
int age=s.nextInt();
validate(age);
ArrayIndexOutOfBoundsException:-
whenever we are calling array with out of range at that moment we are getting
ArrayIndexOutOfBoundsException.
Ex :-
class Test
try
int[] a={10,20,30};
System.out.println(a[0]);//10
System.out.println(a[1]);//20
System.out.println(a[2]);//30
System.out.println(a[3]);//ArrayIndexOutOfBoundsException
NumberFormatException :-
At the time of converting String value into the integer value we are getting
NumberFormatException.
Ex:-
class Test
try
String str="123";
int a=Integer.parseInt(str);
String str1="abc";
int b=Integer.parseInt(str1);
System.out.println(b);//NumberFormatException
NullPointerException :-
If we are having ‘null’ in any variable in that variable we are performing any
operation we are getting NummpointerException.
Ex :-
class Test
try
String str="rattaiah";
System.out.println(str.length());//8
String str1=null;
System.out.println(str1.length());//NullPointerException
}
ArithmeticException :-
Ex:-
class Test
try
int a=10/2;
System.out.println(a);//5
184 | P a g e
int b=10/0;
System.out.println(b);//ArithmeticExceptiom
IllegalArgumentException :-
1--low priority
10--high priority
class Test
t.setPriority(11);//IllegalArgumentException
IllegalThreadStateException :-
Whenever we are trying to restart the already start thread then we are getting
IllegalThreadStateException.
Ex :-
class Test
t.start();
t.start();//IllegalThreadStateException
StackOverflowError:-
Ex :-
class Test
{
void m1()
m2();
System.out.println("this is Rattaiah");
void m2()
m1();
System.out.println("from durgasoft");
t.m1();
OutOfMemoryError:-
If we are creating objects greater than the heap memory then we are getting
OutOfMemoryError.
Ex :-
class Test
}
NoClassDefFoundError :-
Whatever the class if we want to execute if the class is not available at runtime we
are getting NoClassDefFoundError.
Ex :-
class Test
Java Test
if we are executing class ABC (java ABC) if that class is not available then we are
getting NoClassDefFoundError.
Multi Threading :
The earlier days the computer’s memory is occupied only one program after completion
of one program it is possible to execute another program is called uni programming.
Whenever one program execution is completed then only second program execution will
be started such type of execution is called co operative execution, this execution we
are having lot of disadvantages.
b. CPU utilization will be reduced because only program allow executing at a time.
3) CPU scheduler will allocate a particular time period for each and every program.
4) Executing several programs simultaneously is called multiprogramming.
a. Ready state.
b. Running state.
c. Waiting state.
Advantages of multiprogramming:-
Thread :-
3) Whenever different parts of the program executed simultaneously that each and
every part is called thread.
4) The thread is light weight process because whenever we are creating thread it is
not occupying the separate memory it uses the same memory. Whenever the memory is
shared means it is not consuming more memory.
class Test
System.out.println("Hello World!");
System.out.println("hello techfort");
}
} In the above program only one thread is available is called main thread to know the
name of the thread we have to execute the fallowing code.
class Test
System.out.println("Hello World!");
Thread t=Thread.currentThread();
System.out.println("hi rattaiah");
System.out.println("hello durgasoft");
In the above program only one thread is available name of that thread is main thread.
3. Developing animations
Step 1:-
Creates a class that is extend by Thread classes and override the run() method
{
public void run()
Step 2:-
Step 3:-
t.start();
In this approach take one user defined class class that is extending Thread class .
Ex :-
class ThreadDemo
t.start();
}
Note :-
1) Whenever we are calling t.start() method the JVM search for the start() in the
MyThread class but the start() method is not present in the MyThread class so JVM
goes to parent class called Thread class and search for the start() method.
2) In the Thread class start() method is available hence JVM is executing start()
method.
3) Whenever the thread class start() that start() is responsible person to call run()
method.
4) Finally the run() automatically executed whenever we are calling start() method.
5) Whenever we are giving a chance to the Thread class start() method then only a new
thread will be created.
1) New
2) Ready
3) Running state
5) Dead state
New :-
Ready :-
t.start()
Running state :-
If thread scheduler allocates CPU for particular thread. Thread goes to running state
Blocked State :-
If the running thread got interrupted of goes to sleeping state at that moment it
goes to the blocked state.
Dead State :-
If the business logic of the project is completed means run() over thread goes dead
state.
Step 1 :-
Step 2 :-
Creating a object.
Step 3 :-
Step 4 :-
t.start();
class ThreadDemo
t.start();
Step 1:-
the Class MyClass implements the Runnable interface and overriding run() method and
contains the logic associates with the body of the thread.
Step 2:-
Creates the object of implementation class this is not like a first mechanism.
Step 3 :-
Creates a generic thread object then pass the MyClass reference variable as a
parameter to that object.
Step 4 :-
First approach:-
1) By extending the thread class, the derived class itself is a thread object and it
gains full control over the thread life cycle.
2) Another important point is that when extending the Thread class, the sub class
cannot extend any other base classes because Java allows only single inheritance.
if the program needs a full control over the thread life cycle, then extending the
Thread class is a good choice.
Second approach :-
1) Implementing the Runnable interface does not give developers any control over the
thread itself, as it simply defines the unit of work that will be executed in a
thread.
2) By implementing the Runnable interface, the class can still extend other base
classes if necessary.
if the program needs more flexibility of extending other base classes, implementing
the
In the case of t.start(), Thread class start() is executed a new thread will be
created that is responsible for the execution of run() method.
But in the case of t.run() method, no new thread will be created and the run() is
executed like a normal method call by the main thread.
If we are overriding start() method then JVM is executes override start() method at
this situation we are not giving chance to the thread class start() hence n new
thread will be created only one thread is available the name of that thread is main
thread.
1) Every Thread in java has some name if may be default name provided by the jvm or
customized name provided by the programmer.
The following methods are useful to set and get the name of a Thread.
Ex :-
class Test
{
public static void main(String args[])
System.out.println(Thread.currentThread().getName());
System.out.println(t.getName());
Thread.currentThread().setName("madhu");
System.out.println(Thread.currentThread().getName());
Thread Priorities :-
Every Thread in java has some property. It may be default priority provided be the
JVM or customized priority provided by the programmer.
The valid range of thread priorities is 1 – 10. Where one is lowest priority and 10
is highest priority.
The default priority of main thread is 5. The priority of child thread is inherited
from the parent.
Thread Scheduler will use priorities while allocating processor the thread which is
having highest priority will get chance first and the thread which is having low
priority.
If two threads having the same priority then we can’t expect exact execution order it
depends upon Thread Scheduler.
The thread which is having low priority has to wait until completion of high priority
threads.
a. MIN_PRIORITY = 1
b. NORM_PRIORITY = 5
c. MAX_PRIORITY = 10
Thread class defines the following methods to get and set priority of a Thread.
Sleep() :-
The sleep() method causes the current thread to sleep for a specified amount of time
in milliseconds.
For example, the code below puts the thread in sleep state for 5 minutes:
Ex :-
class Test
try
System.out.println("Rattaiah");
Thread.sleep(5*60*1000); // 5 minutes
}
}
Ex :-
class Test
System.out.println("Rattaiah");
Thread.sleep(3*1000);
yield() :-
yield() method causes to pause current executing Thread for giving the chance for
waiting threads of same priority.
If there are no waiting threads or all threads are having low priority then the same
thread will continue its execution once again.
Syntax:-
Ex:-
for(int i=0;i<10;i++)
Thread.yield();
System.out.println("child thread");
}
}
class ThreadYieldDemo
t1.start();
for(int i=0;i<10;i++)
System.out.println("main thread");
join() :-
If a Thread wants to wait until completing some other thread then we should go for
join() method.
Ex :-
Try
{
System.out.println("rattaiah");
Thread.sleep(3*1000);}
catch(InterruptedException iee)
class ThreadDemo
t1.start();
try
t1.join();
System.out.println("interrupted Exception");
t2.start();
}
Synchronized :-
Synchronized modifier is the modifier applicable for methods but not for classes and
variables.
But the main disadvantage of synchronized modifier is it increases the waiting time
of the Thread and effects performance of the system .Hence if there is no specific
requirement it is never recommended to use.
The main purpose of this modifier is to reduce the data inconsistence problems.
Daemon threads:-
Non-daemon threads:-
The threads which are executed fore ground is called non-daemon threads.
Limitations of arrays:-
Ex :-
S[0]=new Student();
S[1]=new Student();
To overcome the above limitations of array the sun peoples are introduced collections
concept
Collections:-
Collections :-
1. Collection
2. List
3. Set
4. SortedSet
5. NavigablaSet
6. Queue
7. Map
8. SotedMap
9. NavigableMap
ArrayList:-
the collection classes stores only objects but we are passing primitives these
primitives are automatically converts into objects is called autoboxing.
2) ArrayList supports dynamic array that can be grow as needed.it can dynamically
increase and decrease the size.
Ex:-
import java.util.*;
class ArrayListDemo
//creation of ArrayList
al.add("a");
al.add("A");
al.add("a");
al.add(null);
al.add(10);
al.add(1,"simon");
System.out.println(al);
System.out.println("ArrayList size:"+al.size());
al.remove("a");
System.out.println("ArrayList size:"+al.size());
System.out.println(al);
}
LinkedList :-
1) Introduced in 1.2 v
Ex :-
import java.util.*;
class Demo
System.out.println(ll.size());
ll.add("a");
ll.add(10);
ll.add(10.6);
ll.addFirst("ratan");
ll.addLast("anu");
System.out.println(ll.size());
ll.remove(10.6);
ll.remove(0);
ll.removeFirst();
ll.removeLast();
int a=(Integer)ll.get(0);
ll.set(0,a+"madhu");
7) Every method present in the Vector is synchronized and hence vector object is
Thread safe.
Ex:-
import java.util.*;
class Test
v.addElement(i);
System.out.println(v);
v.addElement("veeresh");
System.out.println(v);
v.removeElement(0);
System.out.println(v);
v.clear();
System.out.println(v);
Ex :-
import java.util.*;
class Test
s.push("A");
s.push(10);
s.push("aaa");
System.out.println(s);
s.pop();
System.out.println(s);
System.out.println(s.search("A"));
Cursors:-
The main purpose of the constructors is to retrieve the data from the collection
objects.
1. Enumaration
2. Iterator
3. ListIteator
Enumeration :-
3. By using this cursor it is possible to read the data only it not possible to
update the data an not possible to delete the data.
Ex:-
import java.util.*;
class Test
v.addElement(i);
}
System.out.println(v);
Enumeration e=v.elements();
while (e.hasMoreElements())
Integer i=(Integer)e.nextElement();
if (i%2==0)
System.out.println(i);
System.out.println(v);
Iterator:-
2. By using this it is possible to read the data and remove the data.
Ex:-
import java.util.*;
class Test
v.addElement(i);
}
System.out.println(v);
Iterator itr=v.iterator();
while (itr.hasNext())
Integer i=(Integer)itr.next();
if (i%2==0)
System.out.println(i);
else
itr.remove();
System.out.println(v);
LIstIterator :-
2. By using this it is possible to read the data upate the data and delete data also.
Ex :-
import java.util.*;
class Test
{
v.addElement(i);
System.out.println(v);
ListIterator litr=v.listIterator();
while (litr.hasNext())
Integer i=(Integer)litr.next();
if (i==0)
litr.add("veeru");
if (i==5)
litr.set("sambha");
if (i==9)
litr.remove();
System.out.println(v);
HashSet :-
Introduced in 1.2 v
Duplicate objects are not allowed if we are trying to insert duplicate values then we
won’t get any compilation errors an won’t get any Execution errors simply add method
return false.
Null insertion is possible
Ex :-
import java.util.*;
class Test
h.add("a");
h.add("a");
h.add("aaaa");
h.add(10);
h.add(null);
System.out.println(h);
LinkedHashSet :-
Introduced in 1.4 v
Duplicate objects are not allowed if we are trying to insert duplicate values then we
wont get any compilation errors an won’t get any Execution errors simply add method
return false.
Ex :-
import java.util.*;
class Test
h.add("a");
h.add("a");
h.add("aaaa");
h.add(10);
h.add(null);
System.out.println(h);
TreeSet :-
Ex :-
import java.util.*;
class Test
{
TreeSet t=new TreeSet();
t.add(50);
t.add(20);
t.add(40);
t.add(10);
t.add(30);
System.out.println(t);
SortedSet s1=t.headSet(50);
System.out.println(s1); //[10,20,30,40]
SortedSet s2=t.tailSet(30);
System.out.println(s2); //[30,40,50]
SortedSet s3=t.subSet(20,50);
System.out.println(s3); //[20,30,40]
Map:-
2. Up to know we are working with single object and single value where as in the map
collections we are working with two objects and two elements.
3. The main purpose of the collection is to compare the key value pairs and to
perform necessary operation.
HashMap :-
5. Null is allowed for key (only once)and allows for values any number of times.
Eg :-
import java.util.*;
class Test
h.put("sambha",100);
h.put("veeru",100);
h.put("durga",100);
System.out.println(h);
Set s=h.keySet();
System.out.println(s);
Collection c=h.values();
System.out.println(c);
Set s1=h.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
while (itr.hasNext())
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+"------"+m1.getValue());
if (m1.getKey().equals("sambha"))
{
m1.setValue("gayan TeamLead");
System.out.println(s1);
HashTable :-
4. Null insertion is not possible if we are trying to insert null values we are
getting NullPointerException.
Ex :-
import java.util.*;
class Test
h.put("hyd",100);
h.put("bang",200);
h.put("pune",300);
System.out.println(h);
System.out.println(h.contains(300));//true
System.out.println(h.containsValue(500));//false
Collection c=h.values();
System.out.println(c);
Set c1=h.keySet();
System.out.println(c1);
LinkedHashMap :-
Eg :-
import java.util.*;
class Test
h.put("sambha",100);
h.put("veeru",100);
h.put("durga",100);
System.out.println(h);
Set s=h.keySet();
System.out.println(s);
Collection c=h.values();
System.out.println(c);
Set s1=h.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
while (itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey()+"------"+m1.getValue());
if (m1.getKey().equals("sambha"))
m1.setValue("Simon TeamLead");
System.out.println(s1);
==================================*******************===========================