Documente Academic
Documente Profesional
Documente Cultură
Java
Object
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
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.
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
2. Web Application
3. Enterprise Application
Banking applications
4. Mobile Application
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)
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
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
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
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
default:
codetobeexecutedifallc
asesarenotmatched;
}
Java do-while
Loop
Syntax:
while(condition)
{
//codetobeexecute
d
}
Syntax:
do{
//codetobeexecut
ed
}while(condition);
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
obj.sum(10,10,10);
obj.sum(20,20);
}
obj.sum(10.5,10.5);
obj.sum(20,20);
}
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
classBike1 {
Bike1() { System.out.println("Bikeiscreated"); }
publicstaticvoidmain(Stringargs[]){
Bike1b=newBike1();
}
}
Rule: If there is no constructor in a class,
compiler automatically creates a default
publicstaticvoidmain(Stringargs[]) {
Student4s1=newStudent4(111,"Karan");
Student4s2=newStudent4(222,"Aryan");
s1.display();
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();
}
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.
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());
}
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();
classHondaextendsBike{
voidrun()
{System.out.println("runningsafelywith100kmph");}
publicstaticvoidmain(Stringargs[]){
Hondahonda=newHonda();
honda.run();
classHonda1extendsBike{
voidrun()
{System.out.println("runningsafelywith100k
mph");}
publicstaticvoidmain(Stringargs[]){
Honda1honda=newHonda();
honda.run();
}
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.
Understanding relationship
between classes and interfaces
nterfaceprintable{
voidprint();
}
lassA6implementsprintable{
publicvoidprint(){System.out.println("Hello");}
publicstaticvoidmain(Stringargs[]){
A6obj=newA6();
obj.print();
}
}
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
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
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
String Methods
char charAt(int index)
int compareTo(String
anotherString)
int
compareToIgnoreCase(String
str)
int length()
String trim()
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
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
2) public int
available()throws
IOException:
FileInputStream and
FileOutputStream
(File
Handling)
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.
FileReader(String file)
FileReader(File file)
Description
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();
}
}
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
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
while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2));
}
etableemp(idnumber(10),namevarchar2(40),agenumber(
//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);}}}