You are on page 1of 105

Core

Java

OOPs (Object Oriented


Programming System)
Object means a real word entity such as pen, chair, table etc. ObjectOriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

Object

OOPs (Object Oriented


Programming System)

Any entity that has state and behavior is known as an


object. For example: chair, pen, table, keyboard, bike etc. It
can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and
behaviors of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime
polymorphism.

Polymorphism
When one task is performed by different ways i.e.
known as polymorphism.
In java, we use method overloading and method overriding

OOPs (Object Oriented


Programming System)

Abstraction

Hiding internal details and showing functionality is


known as abstraction.
For example: phone call, we don't know the internal
processing.
In java, we use abstract class and interface to achieve
abstraction.

Encapsulation
Binding (or wrapping) code and data together into
a single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.
A java class is the example of encapsulation.

Advantage of OOPs over


Procedure-oriented programming
language
1)OOPs makes development and maintenance easier
where as in Procedure-oriented programming
language it is not easy to manage if code grows as
project size grows.
2)OOPs provides data hiding whereas in Procedureoriented programming language a global data can be
accessed from anywhere.
3)OOPs provides ability to simulate real-world event
much more effectively. We can provide the solution of
real word problem if we are using the ObjectOriented Programming language.

Introduction
Java is a programming language
and a platform.
Java is a high level, robust, secured
and object-oriented programming
language.
Platform: Any hardware or software
environment in which a program
runs, is known as a platform.

Where it is used?
According to Sun, 3 billion devices run java. There
are many devices where java is currently used.
Some of them are as follows:
1. Desktop Applications such as acrobat reader,
media player, antivirus etc.
2. Web Applications such as irctc.co.in.
3. Enterprise Applications such as banking
applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc

Types of Java
Applications
There are mainly 4 type of applications
that can be created using java
programming
1. Standalone Application

Desktop application or Window-based application

2. Web Application

Servlet, JSP, Struts, JSF

3. Enterprise Application

Banking applications

4. Mobile Application

Android and Java ME

Features of Java
The Java Features given below are simple and
easy to understand.
Simple
Object-Oriented
Platform independent
Secured
Robust
Portable
High Performance
Multithreaded
Distributed

Platform Independent
A platform is the hardware or
software environment in which a
program runs.
There are two types of platforms
software-based and hardware-based.
Java provides software-based
platform.
It has two components:
Runtime Environment
API(Application Programming Interface)

Java code can be run on multiple platforms


e.g.Windows,Linux,Sun Solaris,Mac/OS etc.
Java code is compiled by the compiler and
converted into bytecode.
This bytecode is a platform independent
code because it can be run on multiple
platforms i.e. Write Once and Run
Anywhere(WORA).

JVM
JVM (Java Virtual Machine) is an
abstract machine. It is a specification
that provides runtime environment in
which java bytecode can be executed.
The JVM performs following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment

Internal Details of Hello Java Program


What happens at compile time?
At compile time, java file is compiled by Java
Compiler (It does not interact with OS) and converts
the java code into bytecode.

What happens at run time?


At runtime, following steps are performed

Variable and Data Type in


Java
Variable
Variable is name of reserved area allocated in memory
data type variable [ = value][, variable [= value] ...] ;
intdata=50;//Heredataisvariable

Local Variable
A variable that is declared inside the method is called
local variable.
Instance Variable
A variable that is declared inside the class but outside
the method is called instance variable . It is not
declared as static.
Static variable
A variable that is declared as static is called static

Data Types in Java

Default
Data Type
Value
boolean
False
char
'\u0000'
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d

Default
size
1 bit
2 byte
1 byte
2 byte
4 byte
8 byte
4 byte
8 byte

Why char uses 2 byte in java and what


is \u0000 ?
because java uses unicode system rather
than ASCII code system. \u0000 is the lowest

Operators in java
There are many types of operators in java such as unary operator,
arithmetic operator, relational operator, shift operator, bitwise operator,
ternary operator and assignment operator

Operators

Precedence

Postfix
Unary
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise exclusive OR
Bitwise inclusive OR
Logical AND
Logical OR
Ternary

expr++ expr--

Assignment

= += -= *= /= %= &= ^= |= <<= >>=


>>>=

++expr --expr +expr -expr ~ !


* / %
+ << >> >>>
< > <= >= instanceof
== !=
&
^
|
&&
||
? :

Java If-else Statement


The Java if statement is used to test the condition.
It returns true or false.
There are various types of if statement in java.
if statement
if-else statement
nested if statement
if-else-if ladder
Java IF Statement
Syntax:
if(condition){
//codetobeexecuted
}

Java If-else Statement


Java IF-else
Statement
Syntax:
if(condition){
//codeifconditionist
rue
}else{
//codeifconditionisf
alse
}

Java IF-else-if ladder


Statement
Syntax:
if(condition1){
//codetobeexecutedifcondition1is
true
}elseif(condition2){
//codetobeexecutedifcondition2is
true
}
elseif(condition3){
//codetobeexecutedifcondition3is
true
}
...
else{
//codetobeexecutedifalltheconditi
onsarefalse

Java Switch Statement


Syntax:
switch(expression){
casevalue1:
//codetobeexecuted;
break;//optional
casevalue2:
//codetobeexecuted;
break;//optional
......

default:
codetobeexecutedifallc
asesarenotmatched;
}

Java For Loop


There are three types of for loop
in java.
Simple For Loop
For-each or Enhanced For Loop
Labeled For Loop
Java Simple For Loop
Syntax:
for(initialization;condition;incr/dec
r)
{
//codetobeexecuted

Java For Loop


Java For-each Loop
The for-each loop is used to traverse array or
collection in java.
It is easier to use than simple for loop because we
don't need to increment value and use subscript
notation.
Syntax:
for(Typevar:array) {
//codetobeexecuted
}
publicclassForEachExample{
publicstaticvoidmain(String[]args){
intarr[]={12,23,44,56,78};
for(inti:arr){
System.out.println(i);
}

Java Labeled For Loop


We can have name of each for loop.
To do so, we use label before the for loop. It is useful
if we have nested for loop so that we can
break/continue specific for loop.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//codetobeexecuted
}
publicclassLabeledForExample {
publicstaticvoidmain(String[]args){
aa:
for(inti=1;i<=3;i++ ){
bb:
for(intj=1;j<=3;j++){
if(i==2&&j==2){
breakaa;}

Java While Loop

Java do-while
Loop

Syntax:
while(condition)
{
//codetobeexecute
d
}

Syntax:
do{
//codetobeexecut
ed
}while(condition);

Object and Class in Java


Object in Java
Object is the physical as
well as logical entity
whereas class is the logical
entity only.
An entity that has state
and behavior is known as
an object e.g. chair, bike,
marker, pen, table, car etc.
It can be physical or logical

Class in Java
A class is a group of objects that has common
properties. It is a template or blueprint from
which objects are created.
A class in java can contain:
data member
method
constructor
block
class and interface

Syntax to declare a class:


class<class_name>{
datamember;
method;
}

Simple Example of Object and


Class
classStudent1
{
intid=10;
//datamember(alsoinstancevariable)
Stringname=JAVA;
//datamember(alsoinstancevariable)
publicstaticvoidmain(Stringargs[])
{
Student1s1=newStudent1();//creatinganobject
ofStudent
System.out.println(s1.id);
System.out.println(s1.name);

Method Overloading in Java


If a class have multiple
methods by same name
but different parameters,
it is known as Method
Overloading.

Advantage of method overloading?

Method overloading increases the readability of


the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing
the return type of the method.

Example of Method Overloading by


changing the no. of arguments
classCalculation{
voidsum(inta,intb)
{ System.out.println(a+b);
}
voidsum(inta,intb,intc)
{ System.out.println(a+b+c); }
publicstaticvoidmain(Stringargs[]
) {
Calculationobj=newCalculation();

obj.sum(10,10,10);
obj.sum(20,20);
}

Example of Method Overloading by


data type of argument
classCalculation{
voidsum(inta,intb)
{ System.out.println(a+b);
}
voidsum(doublea,doubleb)
{ System.out.println(a+b); }
publicstaticvoidmain(Stringargs[]
) {
Calculationobj=newCalculation();

obj.sum(10.5,10.5);
obj.sum(20,20);
}

Why Method Overloading is


not possible by changing the
return type of method?
classCalculation3
{
intsum(inta,intb)
{ System.out.println(a+b); }
doublesum(inta,intb)
{ System.out.println(a+b); }

publicstaticvoidmain(Stringargs[]) {
Calculation3obj=newCalculation3();
intresult=obj.sum(20,20);//CompileTim
eError

Constructor in Java
Constructor in java is a special type of method that
is used to initialize the object.
Java constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the
constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type

Java Default Constructor


A constructor that have no parameter is known as
default constructor.
Example of default constructor

classBike1 {
Bike1() { System.out.println("Bikeiscreated"); }
publicstaticvoidmain(Stringargs[]){
Bike1b=newBike1();
}
}
Rule: If there is no constructor in a class,
compiler automatically creates a default

Java parameterized constructor


A constructor that have parameters is known as parameterized
constructor.

Why use parameterized constructor?


Parameterized constructor is used to provide different values to the
distinct objects.

Example of parameterized constructor


classStudent4 {
intid;
Stringname;
Student4(inti,Stringn) {
id=i;name=n;}
voiddisplay()
{ System.out.println(id+""+name); }

publicstaticvoidmain(Stringargs[]) {
Student4s1=newStudent4(111,"Karan");
Student4s2=newStudent4(222,"Aryan");
s1.display();

Java Copy Constructor


There is no copy constructor in java. But, we
can copy the values of one object to another
like copy constructor in C++.
There are many ways to copy the values of one
object into another in java. They are:
By constructor
By assigning the values of one object into
another
By clone() method of Object class

Java Static keyword


The static keyword in java is used for memory
management mainly.
We can apply java static keyword with variables,
methods, blocks and nested class.
The static can be:
Variable (also known as class variable)
Method (also known as class method)

1)Java static variable


) If you declare any variable as static, it is known static
variable.
) The static variable can be used to refer the common
property of all objects (that is not unique for each
object)
) e.g. company name of employees,college name of
students etc.
) The static variable gets memory only once in class
area at the time of class loading.

ramofstaticvariable

Student8 {
rollno;
ngname;
icStringcollege="ITS";

dent8(intr,Stringn) {
no=r;
me=n;

display() { System.out.println(rollno+""+name+""+college); }

cstaticvoidmain(Stringargs[]) {
ent8s1=newStudent8(111,"Karan");
ent8s2=newStudent8(222,"Aryan");

splay();
splay();
}

2) Java static method


If you apply static keyword with any method, it is
known as static method.
A static method belongs to the class rather than object
of a class.
A static method can be invoked without the need for
creating an instance of a class.
Static method can access static data member and can
change the value of it.


classStudent9 {
introllno;
Stringname;
staticStringcollege="ITS";

staticvoidchange() {
college="BBDIT";
}

Student9(intr,Stringn){
rollno=r;
name=n;
}

voiddisplay()
{ System.out.println(rollno+""+name+""+
college); }

publicstaticvoidmain(Stringargs[]){
Student9.change();

s1.display();
s2.display();
s3.display();
}
Student9s1=newStudent9(111,"Karan"); }
Student9s2=newStudent9(222,"Aryan");

Inheritance in Java
Inheritance in java is that you can create new
classes that are built upon existing classes.
When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also
known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism
can be achieved).
For Code Reusability.

Syntax of Java Inheritance


classSubclass-nameextendsSuperclass-name
{
//methodsandfields
}
The extends keyword indicates that you are making
a new class that derives from an existing class.
classEmployee{
floatsalary=40000;
}
classProgrammerextendsEmployee{
intbonus=10000;
publicstaticvoidmain(Stringargs[]){
Programmerp=newProgrammer();
System.out.println("Programmersalaryis:"+p.salary
);
System.out.println("BonusofProgrammeris:"+p.bo

Types of inheritance in java

Multiple inheritance is not supported in java through

Method Overriding in Java


If subclass (child class) has the same method as declared
in the parent class, it is known as method overriding
in java.
Usage of Java Method Overriding
Method overriding is used to provide specific
implementation of a method that is already provided by
its super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
method must have same name as in the parent class
method must have same parameter as in the parent
class.
must be IS-A relationship (inheritance).

assBank {
getRateOfInterest(){return0;}

assSBIextendsBank {
getRateOfInterest() { return8; }

assICICIextendsBank {
getRateOfInterest() { return7; }

assAXISextendsBank {
getRateOfInterest() { return9; }

assTest2 {
blicstaticvoidmain(Stringargs[]) {
Is=newSBI();
CIi=newICICI();
XISa=newAXIS();
stem.out.println("SBIRateofInterest:"+s.getRateOfInterest());
stem.out.println("ICICIRateofInterest:"+i.getRateOfInterest());
stem.out.println("AXISRateofInterest:"+a.getRateOfInterest());
}

Super keyword in java


The super keyword in java is a reference variable that
is used to refer immediate parent class object.
Whenever you create the instance of subclass, an
instance of parent class is created implicitly i.e.
referred by super reference variable.
Usage of java super Keyword
super is used to refer immediate parent class
instance variable.
super() is used to invoke immediate parent class
constructor.
super is used to invoke immediate parent class
method.

classVehicle{
intspeed=50;
}

classBike3extendsVehicle{
intspeed=100;
voiddisplay(){
System.out.println(speed);
}
publicstaticvoidmain(Strin
gargs[]){
Bike3b=newBike3();
b.display();
}
}

//exampleofsuperkeyword

classVehicle{
intspeed=50;
}

classBike4extendsVehicle{
intspeed=100;

voiddisplay(){
System.out.println(super.spee
d);//willprintspeedofVehiclen
ow
}
publicstaticvoidmain(String
args[])
{
Bike4b=newBike4();
b.display();

Final Keyword In Java


The final keyword in java is used to
restrict the user.
The java final keyword can be used in
many context.
Final can be:
variable
method
class

1) Java final variable


If you make any variable as final, you cannot change
the value of final variable(It will be constant).
Example of final variable
classBike9{
finalintspeedlimit=90;//finalvariable
voidrun(){
speedlimit=400;
}
publicstaticvoidmain(Stringargs[]){
Bike9obj=newBike9();
obj.run();
}
}//endofclass

2) Java final method


If you make any method as final, you cannot override
it.
Example of final method
classBike{
finalvoidrun() { System.out.println("running"); }
}

classHondaextendsBike{
voidrun()
{System.out.println("runningsafelywith100kmph");}

publicstaticvoidmain(Stringargs[]){
Hondahonda=newHonda();
honda.run();

3) Java final class


If you make any class as final, you cannot
extend it.
Example of final class
finalclassBike{}

classHonda1extendsBike{
voidrun()
{System.out.println("runningsafelywith100k
mph");}

publicstaticvoidmain(Stringargs[]){
Honda1honda=newHonda();
honda.run();
}

Abstract class in Java


A class that is declared with abstract keyword, is known
as abstract class in java.
It can have abstract and non-abstract methods (method
with body).
Before learning java abstract class, let's understand the
abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class in Java


Abstract class in Java
A class that is declared as abstract is known as
abstract class. It needs to be extended and its method
implemented. It cannot be instantiated.
Example abstract class
abstractclassA{}
Abstract method
A method that is declared as abstract and does not have
implementation is known as abstract method.
Example abstract method
abstractvoidprintStatus();//nobodyandabstract

abstractclassBike{
abstractvoidrun();
}

classHonda4extendsBike{
voidrun()
{System.out.println("runningsafely..");}

publicstaticvoidmain(Stringargs[]){
Bikeobj=newHonda4();
obj.run();
}
}

Interface in Java
An interface in java is a blueprint of a class. It has
static constants and abstract methods only.
The interface in java is a mechanism to achieve
fully abstraction.
There can be only abstract methods in the java
interface not method body.
It is used to achieve fully abstraction and multiple
inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They
are given below.
It is used to achieve fully abstraction.

By interface, we can support the functionality of


multiple inheritance.
The java compiler adds public and abstract
keywords before the interface method and public,
static and final keywords before data members.
In other words, Interface fields are public, static and final
by default, and methods are public and abstract.

Understanding relationship
between classes and interfaces

nterfaceprintable{
voidprint();
}

lassA6implementsprintable{
publicvoidprint(){System.out.println("Hello");}

publicstaticvoidmain(Stringargs[]){
A6obj=newA6();
obj.print();
}
}

Multiple inheritance in Java by


interface

nterfacePrintable{
voidprint();
}

nterfaceShowable{
voidshow();
}

classA7implementsPrintable,Showable{

publicvoidprint(){System.out.println("Hello");}
publicvoidshow(){System.out.println("Welcome");}

publicstaticvoidmain(Stringargs[]){
A7obj=newA7();
obj.print();
obj.show();
}
}

Java Packages

To prevent naming conflicts, to control access, to make


searching/locating and usage of classes, interfaces and
enumerations.
A Package can be defined as a grouping of related types
(classes, interfaces, enumerations ) providing access
protection and namespace management
Some of the existing packages in Java are:
java.lang - bundles the fundamental classes
java.io - classes for input, output functions are
bundled in this package

Creating a Package
While creating a package, you should choose a name for the
package and include a package statement along with that
name at the top of every source file.
The package statement should be the first line in the source
file.

Syntax
package packagename;
public class classname
{
------------

Example
/* File name : A.java */
Package p1;
public class A
{
public void display()
{
System.out.println(Package one);
}
}

Import Package
If a class wants to use another class in the same
package, the package name need not be used.
If a class want to use some other package, you
have to use the package name
It can be achieved by using Import statement

Syntax
Import packagename.classname;
Or

Import packagename.*;

Example
import p1.A; or import p1.*;
Class B
{
Public static void main(String args[])
{
A a1=new A();
A1.display();
}
}

Java String
Strings, which are widely used in Java
programming, are a sequence of characters. In Java
programming language, strings are treated as
objects.
The Java platform provides the String class to
create and manipulate strings.

Creating String
The most direct way to create a string is to
write:

Java String
The String class is immutable, so that once it is
created a String object cannot be changed.
If there is a necessity to make a lot of modifications
to Strings of characters, then you should use
String Buffer
String Builder Classes.

String Buffer
The StringBuffer and StringBuilder classes are used
to make a lot of modifications to Strings of
characters
The main difference between the StringBuffer and
StringBuilder is that StringBuilders methods are not
thread safe.
It is recommended to use StringBuilder whenever
possible because it is faster than StringBuffer.
However, if the thread safety is necessary, the best
option is StringBuffer objects.

StringBuffer Methods
Sl.No

Methods

Description

public StringBuffer append(String


s)

Updates the value of


the object that
invoked the method.

2
public StringBuffer reverse()

3
public delete(int start, int end)

4
public insert(int offset, int i)

5
replace(int start, int end, String

The method reverses


the value of the
StringBuffer object
that invoked the
method.
Deletes the string
starting from the start
index until the end
index.
This method inserts a
string s at the position
mentioned by the
offset.
This method replaces
the characters in a

public class Test {


public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Test");
StringBuffer sb1 = new
StringBuffer("sample");
sb.append(" Javapgm");
System.out.println(sb);
sb1.reverse();
System.out.println(sb1);
sb.delete(3,6);
System.out.println(sb);
sb.insert(3,"123");
System.out.println(sb);
sb.replace(3, 7, "ZARA");
System.out.println(sb);
}

String Methods
char charAt(int index)

Returns the character at the


specified index.

int compareTo(String
anotherString)

Compares two strings

int
compareToIgnoreCase(String
str)

Compares two strings ignoring case


differences.

String concat(String str)

Concatenates the specified string to


the end of this string

int indexOf(int ch)

Returns the index within this string of


the first occurrence of the specified
character

int lastIndexOf(int ch)

Returns the index within this string of


the last occurrence of the specified
character

int length()

Returns the length of this string.

String trim()

Returns a copy of the string, with


leading and trailing whitespace
omitted

/* Java program for using string


methods */
public class Test1 {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = new String("Strings are immutable");
String str3 = new String("Integers are not immutable");
char result = str1.charAt(8);
System.out.println(result);
int result1 = str1.compareTo(str2);
System.out.println(result1);
result1= str2.compareTo( str3 );
System.out.println(result1);
str1 = str1.concat(" all the time");
System.out.println(str1);
System.out.println(str1.toUpperCase());
System.out.println(str1.toLowerCase());

Java- Files and I/O


Java I/O (Input and Output) is used to process the
input and produce the output based on the input.
Java uses the concept of stream to make I/O
operation fast.
The java.io package contains all the classes required
for input and output operations.
Stream
A stream is a sequence of data. In Java a stream is
composed of bytes.
There are 3 streams are created for us automatically.
All these streams are attached with console.
1. System.out: standard output stream
2)

System.in: standard input stream

OutputStream
To write data to a destination, it may be a file, an array,
peripheral device or socket.
InputStream
To read data from a source, it may be a file, an array,
peripheral device or socket.

OutputStream class
OutputStream class is an abstract class.
It is the super class of all classes representing an
output stream of bytes.
An output stream accepts output bytes and sends them
to some sink.
Commonly used methods of OutputStream class
Method

Description

1) public void write(int)throws


IOException:

Is used to write a byte to the


current output stream.

2) public void write(byte[])throws


IOException:

is used to write an array of


byte to the current output
stream.

3) public void flush()throws


IOException:
4) public void close()throws
IOException:

flushes the current output


stream.
is used to close the current
output stream.

InputStream class
InputStream class is an abstract class.
It is the superclass of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class
Method

Description

1) public abstract int


read()throws IOException:

reads the next byte of data from


the input stream.It returns -1 at
the end of file.

2) public int
available()throws
IOException:

returns an estimate of the


number of bytes that can be read
from the current input stream.

3) public void close()throws


IOException:

is used to close the current input


stream.

FileInputStream and
FileOutputStream
(File
Handling)

FileInputStream and FileOutputStream classes are


used to read and write data in file.

Java FileInputStream class


Java FileInputStream class obtains input bytes from
a file.
It is used for reading streams of raw bytes such as
image data.
For reading streams of characters, consider using
FileReader.
It should be used to read byte-oriented data for
example to read image, audio, video etc.

Java FileOutputStream class


Java FileOutputStream is an output stream for writing
data to a file.
For character-oriented data, prefer FileWriter.
It should be used to write byte-oriented data for
example to store image, audio, video etc.

Example of Reading the data of current


java file and writing it into another file
importjava.io.*;
classC{
publicstaticvoidmain(Stringargs[])throwsEx
ception{
FileInputStreamfin=newFileInputStream("C.ja
va");
FileOutputStreamfout=newFileOutputStream(
"M.java");inti=0;
while((i=fin.read())!=-1){
fout.write((byte)i);
}
fin.close();

Java FileWriter and


FileReader
(File
Handling in java)
Java FileWriter and FileReader classes are used to
write and read data from text files.
These are character-oriented classes, used for file
handling in java.
Java has suggested not to use the FileInputStream
and FileOutputStream classes if you have to read and
write the textual information.

Java FileWriter class


Java FileWriter class is used to write character-oriented
data to the file.
Constructors
of FileWriter classDescription
Constructor
FileWriter(String file)
FileWriter(File file)

creates a new file. It gets file


name in string.
creates a new file. It gets file
name in File object.

ethods of FileWriter class


1)
2)
3)
4)
5)

public
public
public
public
public

Method
void write(String text)
void write(char c)
void write(char[] c)
void flush()
void close()

Description
writes the string into FileWriter.
writes the char into FileWriter.
writes char array into FileWriter.
flushes the data of FileWriter.
closes FileWriter.

Java FileReader class


Java FileReader class is used to read data from the file. It
returns data in byte format like FileInputStream class.

Constructors of FileReader class


Constructor

FileReader(String file)
FileReader(File file)

Description

It gets filename in string.


It gets filename in file
instance.

ethods of FileWriter class


Method

1) public int read()


2) public void close()

Description

returns a character in
ASCII form. It returns -1 at
the end of file.
closes FileReader.

Java FileWriter/FileReader
Example

mportjava.io.*;
classSimple{
publicstaticvoidmain(Stringargs[]){
try{
FileWriterfw=newFileWriter("abc.txt");
fw.write("mynameissachin");
fw.close();
}catch(Exceptione){System.out.println(e);}
FileReaderfr=newFileReader("abc.txt");
inti;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}

Reading data from keyboard


There are many ways to read data from the keyboard.
For example:
InputStreamReader
Console
Scanner
DataInputStream etc.

InputStreamReader class
InputStreamReader class can be used to read data
from keyboard.It performs two tasks:
connects to input stream of keyboard
converts the byte-oriented stream into characteroriented stream

BufferedReader class

Example of reading data from


keyboard by InputStreamReader
and BufferdReader class

portjava.io.*;
ssG5{
blicstaticvoidmain(Stringargs[])throwsException{

utStreamReaderr=newInputStreamReader(System
fferedReaderbr=newBufferedReader(r);

stem.out.println("Enteryourname");
ingname=br.readLine();
stem.out.println("Welcome"+name);

JDBC

JDBC (Java Database Connectivity) API allows Java


programs to connect to databases
Database access is the same for all database vendors
The JVM uses a JDBC driver to translate generalized
JDBC calls into vendor specific database calls

There are 5 steps to connect any java


application with the database in java using
JDBC. They are as follows:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection

1) Register the driver class


The forName() method of Class class is used to register
the driver class.
This method is used to dynamically load the driver class.

Syntax of forName() method


publicstaticvoidforName(StringclassName)throwsCl
assNotFoundException

Example to register the OracleDriver class


Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager
class is used to establish connection with the
database.
Syntax of getConnection() method
1)publicstaticConnectiongetConnection(Stringurl)thr
owsSQLException
2)publicstaticConnectiongetConnection(Stringurl,Stri
ngname,Stringpassword)throwsSQLException

Example to establish connection with the


Oracle database
Connectioncon=DriverManager.getConnection(

3) Create the Statement object


The createStatement() method of Connection interface
is used to create statement. The object of statement is
responsible to execute queries with the database.

Syntax of createStatement() method


publicStatementcreateStatement()throwsSQLExceptio
n

Example to create the statement object


Statementstmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is
used to execute queries to the database.
This method returns the object of ResultSet that can be
used to get all the records of a table.

Syntax of executeQuery() method


publicResultSetexecuteQuery(Stringsql)throwsSQLEx
ception

Example to execute query


ResultSetrs=stmt.executeQuery("select*fromemp");

while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and
ResultSet will be closed automatically.
The close() method of Connection interface is
used to close the connection.

Syntax of close() method


publicvoidclose()throwsSQLException

Example to close connection


con.close();

Example to connect to the Oracle


database
For connecting java application with the oracle database, you need
to follow 4 steps to perform database connectivity. In this example
we are using Oracle10g as the database. So we need to know
following informations for the oracle database:
1. Driver class: The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G
database is jdbc:oracle:thin:@localhost:1521:xe
3. Username: The default username for the oracle database is
system.
4. Password: Password is given by the user at the time of installing
the oracle database.

t create a table in oracle database.

etableemp(idnumber(10),namevarchar2(40),agenumber(

ert the values for the Table emp

t into emp values(101,AAAA,28);

t into emp values(102,BBBB,20);

t into emp values(103,CCCC,32);

Example to Connect Java Application with Oracle


database
importjava.sql.*;
classOracleCon{
publicstaticvoidmain(Stringargs[]){
try{
//step1loadthedriverclass
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver");

//step2createtheconnectionobject
Connectioncon=DriverManager.getConnection(jdbc:odbc:mydsn");

//step3createthestatementobject
Statementstmt=con.createStatement();

//step4executequery
ResultSetrs=stmt.executeQuery("select*fromemp");
while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3))
;

//step5closetheconnectionobject
con.close();

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

To connect java application with the Oracle


database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
2) set classpath:
Firstly, search the ojdbc14.jar file then open command prompt and
write:
C:>setclasspath=c:\folder\ojdbc14.jar;.;

MINI Project(Select one project in the below list


based on your USN).
1. Develop a project "Employee Information System" using Eclipse
IDE and JDBC to connect with Database and fetch the records.
2. Develop a project "Student Information System" using Eclipse IDE
and JDBC to connect with Database and fetch the records.
3. Develop a project "Departmental Management System" using
Eclipse IDE and JDBC to connect with Database and fetch the records.
4. Develop a project "Hospital Management System" using Eclipse
IDE and JDBC to connect with Database and fetch the records.
5. Develop a project "Library Management System" using Eclipse IDE
and JDBC to connect with Database and fetch the records.
6. Develop a project "Payroll Management System" using Eclipse IDE
and JDBC to connect with Database and fetch the records.
7. Develop a project "Hostel Management System" using Eclipse IDE
and JDBC to connect with Database and fetch the records.
8. Develop a project Ticket Reservation Management System" using
Eclipse IDE and JDBC to connect with Database and fetch the records.
9. Develop a project "HR Management System" using Eclipse IDE and
JDBC to connect with Database and fetch the records.
10.Develop a project "Examination Management System" using