Oops Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 125

Unit-

1OOPConcepts

ObjectOrientedProgrammingisaparadigmthatprovidesmanyconceptssuchas
inheritance,databinding,polymorphismetc.

Simulaisconsideredasthefirstobject-orientedprogramminglanguage.Theprogramming
paradigmwhereeverythingisrepresentedasanobjectisknownastrulyobject-oriented programming
language.

Smalltalkisconsideredasthefirsttrulyobject-orientedprogramminglanguage.

OOPs(ObjectOrientedProgrammingSystem)

Objectmeansarealwordentitysuchaspen,chair,tableetc.Object-OrientedProgrammingis
amethodologyorparadigmtodesignaprogramusingclassesandobjects.Itsimplifiesthe software
development and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Anyentitythathasstateandbehaviorisknownasanobject.Forexample:chair,pen,table,keyboard,bik
eetc.Itcanbephysicalandlogical.

Class

Collectionofobjectsiscalledclass.Itisalogicalentity.

Inheritance

Whenoneobjectacquiresallthepropertiesandbehavioursofparentobject i.e.knownas inheritance.


Itprovidescode reusability. Itis used to achieve runtime polymorphism.

JAVAPROGRAMMING Page1
Polymorphism

When onetaskisperformedbydifferentways i.e. known as polymorphism. For example: to


convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. catspeaks meaw, dog barks woof etc.

Abstraction

Hidinginternaldetailsandshowingfunctionalityisknownasabstraction.Forexample:phone
call,wedon'tknowtheinternalprocessing.

Injava,weuseabstractclassandinterfacetoachieveabstraction.

Encapsulation

Binding(orwrapping)codeanddatatogetherintoasingleunitisknownasencapsulation. For
example: capsule, it is wrapped with different medicines.

A javaclass is the example of encapsulation. Javabean is the fullyencapsulatedclassbecause all the


data members are private here.

BenefitsofInheritance

 One of the key benefits of inheritance is to minimize the amount of duplicate code in an

application by sharing common code amongst several subclasses. Where equivalent code

exists in two related classes, the hierarchy can usually be refactored tomove the commoncode

uptoa mutual superclass. This alsotends toresult in a better organization of code and smaller,

simpler compilation units.

 Inheritance can also make application code more flexible to change because classesthat

inherit from a common superclass can be usedinterchangeably. If the return type of a

method is superclass

 Reusability-facilitytousepublicmethodsof baseclasswithoutrewritingthesame.

 Extensibility-extendingthebaseclasslogicasperbusinesslogicofthederivedclass.

JAVAPROGRAMMING Page2
 Datahiding-base class can decide to keepsome data private so that it cannotbe

altered by the derived class


Proceduralandobjectorientedprogrammingparadigms

JAVAPROGRAMMING Page3
JavaProgramming-HistoryofJava

ThehistoryofjavastartsfromGreenTeam.Javateammembers(alsoknownasGreenTeam),i
nitiatedarevolutionarytasktodevelopalanguagefordigitaldevicessuchasset-
topboxes,televisionsetc.

Forthegreenteammembers,itwasanadvanceconceptatthattime.But,itwassuitedforinter
netprogramming.Later,JavatechnologyasincorporatedbyNetscape.

Currently,Javaisusedininternetprogramming,mobiledevices,games,e-
businesssolutionsetc.Therearegiventhemajorpointsthatdescribesthehistoryofjava.

1) JamesGosling,MikeSheridan,andPatrickNaughtoninitiatedtheJavalanguageproj
ectinJune1991.ThesmallteamofsunengineerscalledGreenTeam.

2) Originallydesignedforsmall,embeddedsystemsinelectronicapplianceslikeset-
topboxes.

3) Firstly,itwascalled"Greentalk"byJamesGoslingandfileextensionwas.gt.

4) Afterthat,itwascalledOakandwasdevelopedasapartoftheGreenproject.

JavaVersionHistory

Therearemanyjavaversionsthathasbeenreleased.CurrentstablereleaseofJavaisJavaSE8
.

1. JDKAlphaandBeta(1995)
2. JDK1.0(23rdJan,1996)
3. JDK1.1(19thFeb,1997)
4. J2SE1.2(8thDec,1998)
5. J2SE1.3(8thMay,2000)
6. J2SE1.4(6thFeb,2002)
7. J2SE5.0(30thSep,2004)
8. JavaSE6(11thDec,2006)
9. JavaSE7(28thJuly,2011)
10.JavaSE8(18thMarch,2014)

JAVAPROGRAMMING Page4
FeaturesofJava
There isgivenmany featuresof java.They are alsoknown as javabuzzwords. The Java Features given
below are simple and easy to understand.

1. Simple
2. Object-Oriented
3. Portable
4. Platformindependent
5. Secured
6. Robust
7. Architectureneutral
8. Dynamic
9. Interpreted

10. HighPerformance
11. Multithreaded
12. Distributed

JavaComments

The java comments are statements that are not executed by the compiler and interpreter. Thecomments
can be used to provide information or explanation about the variable, method, class orany
statement. It can alsobe used tohide program code for specific time.

TypesofJavaComments

Thereare3typesofcommentsinjava.

1. SingleLineComment
2. MultiLineComment
3. DocumentationComment

JavaSingleLineComment

Thesinglelinecommentisusedtocommentonlyoneline.

Syntax:

1.//Thisissinglelinecomment

JAVAPROGRAMMING Page5
Example:

publicclassCommentExample1{
publicstaticvoidmain(String[] args) {
inti=10;//Here, i is a variable
System.out.println(i);
}
}

Output:

10

JavaMultiLineComment

Themultilinecommentisusedtocommentmultiplelinesofcode.

Syntax:

/*
This
is
multiline
comment
*/

Example:

publicclassCommentExample2{
publicstaticvoidmain(String[]args){
/* Let'sdeclareand print
variable injava.*/
inti=10;
System.out.println(i);
}}

Output:

10

JAVAPROGRAMMING Page6
JavaDocumentationComment

ThedocumentationcommentisusedtocreatedocumentationAPI.Tocreatedocumentation API,youneed to use


javadoctool.

Syntax:

/**
This
is
documentation
comment
*/

Example:

/**TheCalculatorclass providesmethodstogetadditionandsubtractionofgiven2numbers.*/
publicclassCalculator {
/**Theadd()methodreturns additionofgiven numbers.*/
publicstaticintadd(inta,intb){returna+b;}
/**Thesub()methodreturnssubtractionofgiven numbers.*/
publicstaticintsub(inta,intb){returna-b;}
}

Compileitbyjavactool:

javacCalculator.java

CreateDocumentationAPIbyjavadoctool:

javadocCalculator.java

Now,therewillbeHTMLfilescreatedfor your Calculator classinthecurrentdirectory. OpentheHTML files


and see the explanation of Calculator class provided through documentation comment.

JAVAPROGRAMMING Page7
DataTypes
Datatypesrepresentthedifferentvaluestobestoredinthevariable.Injava,therearetwotypesofdatatypes:

o Primitivedatatypes
o Non-primitivedatatypes

DataType DefaultValue Defaultsize

boolean False 1bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

JavaVariableExample:AddTwoNumbers
classSimple{
publicstaticvoidmain(String[]args){
inta=10;
intb=10;
intc=a+b;
System.out.println(c);
}}

Output:20

JAVAPROGRAMMING Page8
VariablesandDataTypesinJava
Variable is a name ofmemorylocation.There are three types of variables in java: local,instance and
static.

Therearetwotypesof datatypesinjava:primitiveandnon-primitive.

TypesofVariable
Therearethreetypesofvariablesinjava:

o localvariable
o instancevariable
o staticvariable

1) LocalVariable

Avariablewhichisdeclaredinsidethemethodiscalledlocalvariable.

2) InstanceVariable

Avariablewhichisdeclaredinsidetheclassbutoutsidethemethod,iscalledinstancevariable.It is not
declared as static.

3) Staticvariable

Avariablethatisdeclaredasstaticiscalledstaticvariable.Itcannotbelocal. We will

have detailed learning of these variables in next chapters.

Exampletounderstandthetypesofvariablesinjava

classA{
intdata=50;//instance variable
staticintm=100;//static variable
voidmethod(){
intn=90;//localvariable
}
}//endofclass

ConstantsinJava

A constant is a variable which cannot have itsvaluechanged after declaration. It uses the
'final'keyword.

Syntax
modifierfinal dataTypevariableName=value;//globalconstant

modifierstaticfinaldataTypevariableName=value;//constantwithinac

JAVAPROGRAMMING Page9
ScopeandLifeTimeofVariables
The scope of a variable defines the section of the code in which the variable is visible. As a
generalrule,variablesthataredefinedwithinablockarenotaccessibleoutsidethatblock.
Thelifetimeofavariablereferstohowlongthevariableexistsbeforeitisdestroyed. Destroying variables
refers to deallocating the memory that was allotted to the variables when declaring it. We have
written a few classes till now. You might have observed that not all variables arethesame.
Theones declaredinthebody of amethodweredifferentfromthose
thatweredeclaredintheclassitself.Therearethreetypesofvariables:instancevariables, formal
parameters or local variables and local variables.

Instancevariables

Instance variables are those that are defined within a class itself and not in any method or
constructor of theclass.They areknownasinstancevariablesbecauseeveryinstanceof the
class(object)containsacopy of thesevariables.Thescopeof instancevariablesisdetermined by the
access specifier that is appliedtothese variables. We have already seen about it earlier.
Thelifetimeof thesevariables is the sameas the lifetimeoftheobject towhichitbelongs. Object once
created do not exist for ever. They are destroyed by the garbage collector of Java when there are
no more reference to that object. We shall see about Java's automatic garbage collector later on.

Argumentvariables

Thesearethevariables thataredefinedintheheaderoafconstructor oramethod.Thescope


ofthesevariablesisthemethodorconstructorinwhichtheyaredefined.Thelifetimeis
limitedtothetimeforwhichthemethodkeepsexecuting.Oncethemethodfinishes execution, these
variables are destroyed.

Localvariables

Alocalvariableistheonethatisdeclaredwithinamethodoraconstructor(notinthe header). The scope


and lifetime are limited to the method itself.

Oneimportantdistinctionbetweenthesethreetypesof variablesisthataccessspecifierscan be applied to


instance variables only and not to argument or local variables.

Inadditiontothelocal variables definedinamethod,wealsohavevariables thataredefined


inbockslifeanifblockandanelseblock.Thescopeandisthesameasthatoftheblock itself.

JAVAPROGRAMMING Page10
Operatorsinjava

Operator injavais a symbol thatis used to perform operations. For example: +, -, *, /etc.

There are manytypes of operators in java which are given below:

o UnaryOperator,
o ArithmeticOperator,
o shiftOperator,
o RelationalOperator,
o BitwiseOperator,
o LogicalOperator,
o TernaryOperatorand
o AssignmentOperator.

OperatorsHierarchy

JAVAPROGRAMMING Page11
Expressions
Expressions are essential building blocks ofany Java program, usually createdto produce a new
value, although sometimes an expression simply assignsavalueto avariable. Expressions are built
using values, variables, operators and method calls.

TypesofExpressions

While an expression frequently produces aresult, it doesn't always. There are three typesof
expressions in Java:

 Thosethatproduceavalue,i.e.theresultof(1+1)
 Thosethatassignavariable,forexample(v=10)
 Thosethathavenoresultbutmight havea"sideeffect" becauseanexpressioncaninclude a
widerangeofelementssuchasmethodinvocationsorincrementoperatorsthatmodify the state (i.e.
memory) of a program.

JavaTypecastingandTypeconversion

WideningorAutomaticTypeConversion
Widening conversion takes place when two data types are automatically converted. This happens
when:
 The twodata typesarecompatible.
 Whenweassignvalueofasmallerdatatypetoabiggerdatatype.

For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

NarrowingorExplicitConversion
If wewant toassign avalue of larger data type to asmallerdata type we perform explicit type casting
or narrowing.
 Thisisusefulforincompatibledatatypeswhereautomaticconversioncannotbedone.
 Here,target-typespecifiesthedesiredtypetoconvertthespecifiedvalueto.

JAVAPROGRAMMING Page12
JavaEnum

Enuminjavaisadatatypethatcontainsfixedsetofconstants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY,FRIDAYandSATURDAY),directions(NORTH,SOUTH,EASTandWEST)
etc.Thejavaenumconstantsarestaticandfinalimplicitly.ItisavailablefromJDK1.5. Java

Enums can be thought of as classes that have fixed set of constants.

Simpleexampleofjavaenum
classEnumExample1{
publicenumSeason{WINTER,SPRING,SUMMER,FALL}

publicstaticvoidmain(String[]args){
for(Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL

ControlFlowStatements

The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.

The“if”Statement
The“if” statementin Java worksexactlylike in most programming languages.Withthe help of
“if”youcanchoosetoexecuteaspecificblockofcodewhenapredefinedconditionismet.The structure
of the “if” statement in Java looks like this:

if(condition){
//executethiscode
}

JAVAPROGRAMMING Page13
The conditionisBoolean. Boolean meansitmaybe true or false. For example youmayputa
mathematical equation as condition. Look at this full example:

CreatingaStand-AloneJavaApplication
1. Write a main methodthat runs your program. Youcan write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods.
Forexample:
2. publicclassMain
3. {
4. publicstaticvoidmain(String[]args)
5. {
6. Game.play();
7. }}
8. Make sureyourcodeiscompiled,andthatyouhavetesteditthoroughly.
9. Ifyou're using Windows,youwill need to setyour path to include Java, ifyou haven't done
so already. This is a delicate operation. Open Explorer, and look inside C:\ProgramFiles\Java,
andyou shouldseesomeversionoftheJDK.Openthisfolder,and then open the bin folder. Select
the complete path from the topof the Explorer window,and press Ctrl-C to copy it.

Next, find the "My Computer" icon (on your Start menu or desktop), right-click it, and select
properties.ClickontheAdvancedtab,andthenclickontheEnvironmentvariablesbutton. Look atthe
variableslistedfor allusers,andclickonthe Pathvariable. Donotdelete the contents of this variable!
Instead, edit the contents by moving the cursor to the right end,
enteringasemicolon(;),andpressingCtrl-Vtopastethepathyoucopiedearlier.Thengo ahead and save
your changes. (If you have any Cmd windows open,youwill need to close them.)

10. If you're using Windows, go to the Start menu and type "cmd" to run a program that
brings up a command prompt window. If you're using a Mac or Linux machine, run the
Terminal program to bring up a command prompt.
11. In Windows, type dir atthe command prompt to listthe contents of the current directory. On
a Mac or Linux machine, type ls to do this.

JAVAPROGRAMMING Page14
12. Now we wantto change to the directory/folder that containsyour compiled code. Look at the
listing of sub-directories within this directory, and identify which one contains yourcode. Type
cdfollowed by the name ofthatdirectory, tochange to that directory. For example, to change to a
directory called Desktop, you would type:

cdDesktop

Tochangetotheparentdirectory,type:

cd..

Every timeyouchange toa new directory,list the contents of thatdirectorytosee where to go


next.Continue listingandchanging directories untilyoureach the directory thatcontains
your.classfiles.

13. Ifyoucompiledyour programusing Java 1.6,but plan torun iton a Mac, you'll need to
recompile your code from the command line, by typing:

javac-target1.5*.java

14. Nowwe'llcreateasingleJARfilecontainingallofthefilesneededtorunyourprogram.

Arrays
Java provides a data structure, thearray, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
usefulto thinkof anarrayas a collection of variables of the sametype.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,numbers[99]
to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

DeclaringArrayVariables:
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way.


or
dataTypearrayRefVar[];//worksbutnotpreferredway.
Note:ThestyledataType[]arrayRefVarispreferred.ThestyledataTypearrayRefVar[] comes
from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

JAVAPROGRAMMING Page15
Thefollowingcodesnippetsareexamplesofthissyntax:

double[]myList; //preferredway.
or
doublemyList[];
//worksbutnotpreferredway.
CreatingArrays:
Youcancreateanarraybyusingthenewoperatorwiththefollowingsyntax:

arrayRefVar=newdataType[arraySize];
Theabovestatementdoestwothings:

 ItcreatesanarrayusingnewdataType[arraySize];

 ItassignsthereferenceofthenewlycreatedarraytothevariablearrayRefVar.

Declaring an arrayvariable,creating an array,and assigning the reference of the array to the variable
can be combinedin one statement, as shown below:

dataType[]arrayRefVar=newdataType[arraySize];
Alternativelyyoucancreatearraysasfollows:

dataType[]arrayRefVar={value0,value1,...,valuek};
The array elements are accessedthrough the index. Array indicesare 0-based; that is, they start from
0 to arrayRefVar.length-1.

Example:
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:

double[]myList=newdouble[10];
Following picture represents array myList. Here, myList holds ten double values andthe indices
are from 0 to 9.

JAVAPROGRAMMING Page16
ProcessingArrays:
When processing array elements,we often use either for loopor for each loopbecause all of the
elements in an arrayareofthe same type and the sizeof the array isknown.

Example:
Hereisacompleteexampleofshowinghowtocreate,initializeandprocessarrays:

publicclassTestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all thearray elementsfor
(int i = 0; i <myList.length;i++){
System.out.println(myList[i]+"");
}
// Summing all elements
double total = 0;
for(inti=0;i<myList.length;i++){ total
+= myList[i];
}
System.out.println("Totalis"+total);
// Finding the largest element
double max = myList[0];
for (int i =1; i <myList.length;i++) { if
(myList[i] >max)max=myList[i];
}
System.out.println("Maxis"+max);
}
}

JAVAPROGRAMMING Page17
Thiswouldproducethefollowingresult:

1.9
2.9
3.4
3.5
Totalis11.7
Maxis3.5
publicclassTestArray{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
//Printallthearrayelements
for(double element: myList){
System.out.println(element);
}}}

JavaConsoleClass

The JavaConsole class isbe usedtogetinput from console.It provides methods to read texts and
passwords.

IfyoureadpasswordusingConsoleclass,itwillnotbedisplayedtotheuser.

The java.io.Console class is attached with system console internally. The Console class
isintroduced since 1.5.

Let'sseeasimpleexampletoreadtextfromconsole.

1. Stringtext=System.console().readLine();
2. System.out.println("Textis:"+text);

JavaConsoleExample

importjava.io.Console;
classReadStringTest{
publicstaticvoidmain(String args[])
{ Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n); } }

JAVAPROGRAMMING Page18
Output

Enteryourname:NakulJain
WelcomeNakulJain

Constructors

Constructorinjavaisaspecialtypeofmethodthatisusedtoinitializetheobject.

Java constructoris invokedatthetimeofobjectcreation.It constructs the valuesi.e. provides data for the
object that is why it is known as constructor.

Therearebasicallytworulesdefinedfortheconstructor.

1. Constructornamemustbesameasitsclassname
2. Constructormusthavenoexplicitreturntype

Typesofjavaconstructors

Therearetwotypesofconstructors:

1. Defaultconstructor(no-argconstructor)
2. Parameterizedconstructor

JavaDefaultConstructor

Aconstructorthathavenoparameterisknownasdefaultconstructor.

Syntaxofdefaultconstructor:
1.<class_name>(){}

Exampleofdefaultconstructor

In this example, we are creatingtheno-arg constructor in the Bike class.It will be invokedat the
time of object creation.
classBike1{
Bike1(){System.out.println("Bikeiscreated");}
publicstaticvoidmain(String args[]){ Bike1
b=newBike1();
}}
Output:Bikeiscreated

JAVAPROGRAMMING Page19
Exampleofparameterizedconstructor
In this example,we have created the constructor of Student class that have two parameters. Wecan
have any number of parameters in the constructor.
classStudent4{
intid;
Stringname;

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

publicstaticvoidmain(String args[])
{ Student4 s1 = newStudent4(111,"Karan");
Student4 s2 = newStudent4(222,"Aryan");
s1.display();
s2.display();
}}

Output:

111Karan
222Aryan

ConstructorOverloadinginJava

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
bytaking intoaccountthe number of parameters in the list andtheir type.

ExampleofConstructorOverloading
classStudent5{
intid;Stringn
ame; intage;
Student5(inti,String n)
{ id = i;
name=n;
}
Student5(inti,String n,inta)
{ id = i;
name=n;
age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}

publicstaticvoidmain(String args[]){ Student5


s1 = newStudent5(111,"Karan"); Student5 s2 =
newStudent5(222,"Aryan",25); s1.display();

JAVAPROGRAMMING Page20
s2.display();
}}

Output:

111Karan0
222Aryan25
JavaCopyConstructor

There is no copyconstructor in java. But, we can copythe values of oneobject to another like copy
constructor in C++.

Therearemanywaystocopythevaluesofoneobjectintoanotherinjava.Theyare:

oByconstructor
oByassigningthevaluesofoneobjectintoanother
oByclone()methodofObjectclass

In this example, we are going to copythe values of one object into another using java
constructor.
classStudent6{
intid;
Stringname;
Student6(inti,String n)
{ id = i;
name=n;
}

Student6(Student6 s)
{ id = s.id;
name=s.name;
}
voiddisplay(){System.out.println(id+""+name);}

publicstaticvoidmain(String args[])
{ Student6 s1 = newStudent6(111,"Karan");
Student6 s2 = newStudent6(s1);
s1.display();
s2.display();
}}

Output:

111Karan
111Karan

JAVAPROGRAMMING Page21
Java-Methods
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
methodwith orwithout parameters, andapply methodabstractionin theprogram design.

CreatingMethod
Consideringthefollowingexampletoexplainthesyntaxofamethod−

Syntax

publicstaticintmethodName(inta,intb){
//body
}
Here,

 publicstatic−modifier

 int−returntype

 methodName−nameofthemethod

 a,b−formalparameters

 inta,intb−list ofparameters

Method definition consists of amethodheader and a method body. The same is shown in the
following syntax −

Syntax

modifierreturnTypenameOfMethod(ParameterList){
//methodbody
}
Thesyntaxshownaboveincludes−

 modifier−Itdefinestheaccesstypeofthemethodanditisoptionaltouse.

 returnType−Methodmayreturnavalue.

 nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.

JAVAPROGRAMMING Page22
 ParameterList− The list ofparameters,itis the type, order, and number of parametersof a
method. These are optional, method may contain zero parameters.

 methodbody−Themethodbodydefineswhatthemethoddoeswiththestatements.

CallbyValueandCallbyReferenceinJava
Thereisonly call by valueinjava,notcallby reference.Ifwecall amethodpassingavalue,it is known as
call by value. The changes being done in the called method, is not affected in the calling method.

Exampleofcallbyvalueinjava
Incaseofcallbyvalueoriginalvalueisnotchanged.Let'stakeasimpleexample:
classOperation{
intdata=50;
voidchange(intdata){
data=data+100;//changeswillbeinthelocalvariableonly
}
publicstaticvoidmain(String args[]){ Operation
op=newOperation(); System.out.println("before
change"+op.data); op.change(500);
System.out.println("afterchange"+op.data);
}
}
Output:beforechange50
afterchange50

InJava,parametersarealwayspassedby value.Forexample,followingprogramprints i = 10, j


= 20.
//Test.java
classTest{
//swap()doesn'tswapiandj
public static void swap(Integer i, Integer j)
{ Integer temp = new Integer(i);
i=j;
j=temp;
}
public static void main(String[] args)
{ Integer i = new Integer(10);
Integer j = new Integer(20);
swap(i, j);
System.out.println("i=" +i +",j="+j);

JAVAPROGRAMMING Page23
}
}

StaticFieldsandMethods

The statickeyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the classthan instance
of the class.

Thestaticcanbe:

1. variable(alsoknownasclassvariable)
2. method(alsoknownasclassmethod)
3. block
4. nestedclass

Javastaticvariable

Ifyoudeclareanyvariableasstatic, itisknownstaticvariable.

o Thestaticvariablecanbeusedtoreferthecommonpropertyofallobjects(thatisnotuniquefor each
object) e.g. companyname ofemployees,college name ofstudentsetc.

o Thestaticvariablegetsmemoryonlyonce inclassareaatthetimeofclassloading.

Advantageofstaticvariable

Itmakesyourprogrammemoryefficient(i.eitsavesmemory).

Understandingproblemwithoutstaticvariable
1. classStudent{
2. introllno;
3. Stringname;
4. String college="ITS";
5.}

Exampleofstaticvariable
//Programofstaticvariable
classStudent8{
introllno;

JAVAPROGRAMMING Page24
Stringname;
staticString college ="ITS";
Student8(intr,String n)
{ rollno = r;
name=n;
}
voiddisplay(){System.out.println(rollno+""+name+""+college);}
publicstaticvoidmain(String args[])
{ Student8s1=newStudent8(111,"Karan");
Student8s2=newStudent8(222,"Aryan");

s1.display();
s2.display();
}}
Output:111KaranITS
222AryanITS

Javastaticmethod

Ifyouapplystatickeywordwithanymethod,itisknownasstaticmethod.

o Astaticmethodbelongstotheclassratherthanobjectofaclass.
o Astaticmethodcanbeinvokedwithouttheneedforcreatinganinstanceofaclass.
o staticmethodcanaccessstaticdatamemberandcanchangethevalueofit.

Exampleofstaticmethod
//Programofchangingthecommonpropertyofallobjects(staticfield).

classStudent9{ in
trollno;
Stringname;
staticStringcollege="ITS";
staticvoidchange()
{ college = "BBDIT";
}
Student9(intr, Stringn)
{ rollno = r;
name=n;

JAVAPROGRAMMING Page25
}
voiddisplay(){System.out.println(rollno+""+name+""+college);}
publicstaticvoidmain(String args[]){
Student9.change();
Student9 s1 = newStudent9 (111,"Karan");
Student9 s2 = newStudent9 (222,"Aryan");
Student9 s3 = newStudent9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}}
Output:111 Karan BBDIT
222 Aryan BBDIT
333SonooBBDIT

Javastaticblock

o Isusedtoinitializethestaticdatamember.
o Itis executedbeforemainmethodatthetimeofclassloading.

Exampleofstaticblockclass
A2{
static{System.out.println("static block is invoked");}
publicstaticvoidmain(String args[])
{ System.out.println("Hello main");
}}
Output: static block is invoked
Hello main

AccessControl

AccessModifiersinjava

Therearetwotypesofmodifiersinjava:accessmodifiersandnon-accessmodifiers.

The accessmodifiers injavaspecifiesaccessibility (scope) ofa datamember,method, constructor or


class.

Thereare4typesofjavaaccessmodifiers:

JAVAPROGRAMMING Page26
1. private
2. default
3. protected
4. public

privateaccessmodifier
Theprivateaccessmodifierisaccessibleonlywithinclass.

Simpleexampleofprivateaccessmodifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is compile time error.
classA{
privateintdata=40;
privatevoidmsg(){System.out.println("Hellojava");}}
publicclassSimple{
publicstaticvoidmain(String args[]){ A
obj=newA();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}

2) defaultaccessmodifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Exampleofdefaultaccessmodifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from outside
the package.
//savebyA.java
packagepack;
classA{
voidmsg(){System.out.println("Hello");}
}

//save by B.java
packagemypack;
importpack.*;

JAVAPROGRAMMING Page27
classB{
publicstaticvoidmain(String args[]){A
obj = newA();//Compile Time Error
obj.msg();//Compile Time Error } }

Intheaboveexample,thescopeofclassAand itsmethodmsg()isdefaultsoitcannotbe accessed from


outside the package.

3) protectedaccessmodifier

The protectedaccessmodifieris accessiblewithin package and outside the package but through
inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.

Exampleofprotectedaccessmodifier

Inthisexample,wehavecreatedthetwopackagespackandmypack.TheAclassofpack packageis
public,socanbeaccessedfromoutsidethepackage.Butmsgmethodofthispackage is declaredasprotected, so
it can be accessedfrom outside the class only throughinheritance.

//save byA.java
packagepack;
publicclassA{
protectedvoidmsg(){System.out.println("Hello");}}
//save byB.java
packagemypack;
importpack.*;
classB extendsA{
publicstaticvoidmain(String args[]){ B
obj = newB();
obj.msg();
}}
Output:Hello

4) publicaccessmodifier
The publicaccessmodifier is accessible everywhere.Ithas the widestscope among all other
modifiers.

JAVAPROGRAMMING Page28
Exampleofpublicaccessmodifier
//save byA.java
packagepack;
publicclassA{
publicvoidmsg(){System.out.println("Hello");}}
//save by B.java
packagemypack;
importpack.*;
classB{
publicstaticvoidmain(String args[]){ A
obj = newA();
obj.msg();
}}
Output:Hello

Understandingalljavaaccessmodifiers

Let'sunderstandtheaccessmodifiersbyasimpletable.

AccessM within withinp outsidepackagebys outsidep


odifier class ackage ubclassonly ackage

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

thiskeywordinjava

Usageofjavathiskeyword

Hereisgiventhe6usageofjavathiskeyword.

1. thiscanbe usedtorefercurrentclassinstancevariable.
2. thiscanbeusedtoinvokecurrentclassmethod(implicitly)
3. this()canbeusedtoinvokecurrentclassconstructor.

JAVAPROGRAMMING Page29
4. thiscanbepassedasanargumentinthemethodcall.
5. thiscanbepassedasargumentintheconstructorcall.
6. thiscanbeusedtoreturnthecurrentclassinstancefromthemethod.

classStudent{ i
ntrollno; String
name; floatfee;
Student(introllno,Stringname,floatfee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
voiddisplay(){System.out.println(rollno+""+name+""+fee);}
}
classTestThis2{
publicstaticvoidmain(String args[]){ Student
s1=newStudent(111,"ankit",5000f); Student
s2=newStudent(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:
111 ankit5000
112 sumit6000

Differencebetweenconstructorandmethodinjava

JavaConstructorJavaMethod

Constructorisusedtoinitializethestateofanobject. Methodisusedtoexposebehaviour of
an object.

Constructormustnothavereturntype. Methodmusthavereturntype.

Constructorisinvokedimplicitly. Methodisinvokedexplicitly.

Thejavacompilerprovidesadefaultconstructorifyou don't Method is not provided bycompiler in


have any constructor. anycase.

Constructornamemustbesameastheclassname. Methodnamemayormaynotbe

JAVAPROGRAMMING Page30
sameasclassname.

Therearemanydifferencesbetweenconstructorsandmethods.Theyaregivenbelo

ConstructorOverloadinginJava

Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.

ExampleofConstructorOverloading
classStudent5{int
id; String name;
int
age;
Student5(inti,String n)
{ id = i;
name=n;
}
Student5(inti,String n,inta)
{ id = i;
name=n;
age=a;
}
voiddisplay(){System.out.println(id+""+name+""+age);}

publicstaticvoidmain(String args[]){ Student5


s1 = newStudent5(111,"Karan"); Student5 s2
=newStudent5(222,"Aryan",25); s1.display();
s2.display();
}
}

Output:

JAVAPROGRAMMING Page31
111Karan0
222Aryan25

MethodOverloadinginjava

If aclasshas multiplemethods having same namebut differentin parameters,itis known as


MethodOverloading.

If wehave to performonly one operation, having samename ofthemethods increases the readability
of the program.

MethodOverloading:changingno.ofarguments

In this example, we have created two methods, first add() method performs addition of
twonumbers and second add method performs addition of three numbers.

In this example, we are creating staticmethods so that we don't need to create instance forcalling
methods.

classAdder{
staticintadd(inta,intb){returna+b;}
staticintadd(inta,intb,intc){returna+b+c;}
}
classTestOverloading1{
publicstaticvoidmain(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33
MethodOverloading:changingdatatypeofarguments

In this example, we have created two methods that differs in data type. The first add
methodreceives twointegerarguments andsecondaddmethod receives twodouble arguments.

JAVAPROGRAMMING Page32
RecursioninJava
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

JavaRecursionExample1:FactorialNumber

publicclassRecursionExample3{
staticintfactorial(intn){
if(n == 1)
return1;
else
return(n*factorial(n-1));
}}
publicstaticvoidmain(String[] args)
{ System.out.println("Factorial of 5 is: "+factorial(5));
}}

Output:

Factorialof5is:120

JavaGarbageCollection

Injava,garbagemeansunreferencedobjects.

Garbage Collection is process of reclaiming the runtime unusedmemoryautomatically. In other


words, it is a way to destroy the unused objects.

To doso,wewere using free() functionin C language anddelete()in C++. But, in java itis performed
automatically. So, java provides better memory management.

AdvantageofGarbageCollection
o It makes java memoryefficient because garbage collector removes theunreferenced
objects from heap memory.

o Itis automaticallydone bythe garbage collector(a part of JVM) sowe don't needtomake extra
efforts.

gc()method

JAVAPROGRAMMING Page33
The gc()method isused to invoke the garbage collector to perform cleanup processing.The
gc() is found in System and Runtime classes.

publicstaticvoidgc(){}

SimpleExampleofgarbagecollectioninjavapub
licclassTestGarbage1{
publicvoidfinalize(){System.out.println("objectisgarbagecollected");}
publicstaticvoidmain(String args[])
{ TestGarbage1s1=newTestGarbage1();
TestGarbage1s2=newTestGarbage1();
s1=null;
s2=null;
System.gc();
}}
objectisgarbagecollected
objectisgarbagecollected
JavaString
string is basicallyan objectthatrepresents sequence of charvalues. An array of charactersworks same
as java string. For example:

1. char[]ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=newString(ch);

ssame as:

1. Strings="javatpoint";
2. JavaString class provides a lot of methods to perform operations on string such ascompare(),
concat(), equals(),split(), length(), replace(), compareTo(), intern(),substring()etc.
3. The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

CharSequenceInterface

JAVAPROGRAMMING Page34
The CharSequence interface is used to represent sequence of characters. It is implemented by
String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.

The java String is immutable i.e. it cannot be changed. Whenever we change


anystring, a new instanceis created. For mutable string,you can use StringBufferand StringBuilder
classes.
TherearetwowaystocreateStringobject:
1. Bystringliteral
2. Bynewkeyword

StringLiteral

JavaStringliteraliscreatedbyusingdoublequotes.ForExample:

1. Strings="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in
the pool, a new string instance is created and placed in the pool. For example:

1. Strings1="Welcome";
2. Strings2="Welcome";//willnotcreatenewinstance

Bynewkeyword
1. Strings=newString("Welcome");//createstwoobjectsandonereferencevariable

In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal"Welcome"willbeplacedinthestringconstantpool.Thevariableswillrefertotheobject in heap
(non pool).

JavaStringExample
publicclassStringExample{
publicstaticvoidmain(Stringargs[]){
Strings1="java";//creatingstringbyjavastringliteral
charch[]={'s','t','r','i','n','g','s'};
Strings2=newString(ch);//convertingchararraytostring
String s3=newString("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java

JAVAPROGRAMMING Page35
strings
example
ImmutableStringinJava

In java, stringobjectsareimmutable. Immutable simply means unmodifiable or unchangeable.

Once string object is created its data or state can't be changed but anew string object is created.Let's

try to understand the immutability concept by theexamplegiven below:

classTestimmutablestring{
publicstaticvoidmain(String args[])
{ String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will printSachin becausestrings are immutable objects
}}
Output:Sachin
classTestimmutablestring1{
publicstaticvoidmain(Stringargs[])
{Strings="Sachin";
s=s.concat("Tendulkar");System.o
ut.println(s);
}}Output:SachinTendulkar

JAVAPROGRAMMING Page36
Unit-
2InheritanceinJava
Inheritanceinjava is a mechanism in which one object acquires all the properties and behaviors
of parent object.Inheritance representsthe IS-Arelationship, alsoknownas parent-
childrelationship.

Whyuseinheritanceinjava
o ForMethodOverriding(soruntimepolymorphismcanbeachieved).
o ForCodeReusability.

SyntaxofJavaInheritance
1. classSubclass-nameextendsSuperclass-name
2. {
3. //methodsandfields
4.}

The extendskeyword indicates thatyou aremaking a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

classEmployee{
floatsalary=40000;
}
classProgrammerextendsEmployee{
intbonus=10000;
publicstaticvoidmain(String args[])
{ Programmer p=newProgrammer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmeris:"+p.bonus);
}}

Programmersalaryis:40000.0

JAVAPROGRAMMING Page37
Bonusofprogrammeris:10000

Typesofinheritanceinjava

SingleInheritanceExample

File:TestInheritance.java

classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classTestInheritance{
publicstaticvoidmain(String args[])
{ Dog d=newDog();
d.bark();
d.eat();
}}
Output:
barking...
eating...

MultilevelInheritanceExample
File:TestInheritance2.java

classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classBabyDogextendsDog{
voidweep(){System.out.println("weeping...");}
}
classTestInheritance2{

JAVAPROGRAMMING Page38
publicstaticvoidmain(Stringargs[])
{ BabyDog
d=newBabyDog();d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating...

HierarchicalInheritanceExample
File:TestInheritance3.java

classAnimal{
voideat(){System.out.println("eating...");}
}
classDogextendsAnimal{
voidbark(){System.out.println("barking...");}
}
classCatextendsAnimal{
voidmeow(){System.out.println("meowing...");}
}
classTestInheritance3{
publicstaticvoidmain(String args[])
{ Cat c=newCat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

JAVAPROGRAMMING Page39
MemberaccessandInheritance

A subclass includesall ofthe members of its super class but itcannot access those members of the
super class that have been declared as private. Attempt to access a private variable would cause
compilation error as it causes access violation. The variables declared as private, is only
accessible byother members of its own class. Subclass have no access toit.

superkeywordinjava

The superkeywordin javais a referencevariable which is used to referimmediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

UsageofjavasuperKeyword

1. supercanbeusedtoreferimmediateparentclass instancevariable.

2. supercanbeusedtoinvokeimmediateparentclassmethod.

3. super()canbeusedto invokeimmediateparentclassconstructor.

superisusedtoreferimmediateparentclassinstancevariable.

classAnimal{
Stringcolor="white";
}
classDog
extendsAnimal{ Stringcolor
="black";
voidprintColor(){System.out.println(color);//prints
color of Dog class
System.out.println(super.color);//printscolorofAnimalclass
}
}
classTestSuper1{
publicstaticvoidmain(String args[])
{ Dog d=newDog();

JAVAPROGRAMMING Page40
d.printColor();
}}

Output:

black
white
FinalKeywordinJava

The finalkeyword in java is used to restrict the user. The java finalkeyword can be used in manycontext.
Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only.

ObjectclassinJava

The Objectclass is theparent classof all the classes in javabydefault. In otherwords, itis the topmost
class of java.

The Objectclass is beneficial ifyouwantto referanyobjectwhose typeyou don'tknow. Notice that


parent class referencevariable can referthechildclassobject, know as upcasting.

Let's take an example, thereisgetObject()method thatreturnsan object but itcan be of anytype like
Employee,Student etc,we canuse Objectclassreference toreferthatobject. For example:

1. Objectobj=getObject();//wedon'tknowwhatobjectwillbereturnedfromthismethod

The Objectclass provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

MethodOverridinginJava

If subclass(childclass)has the samemethod as declaredin the parent class, itis known as


methodoverridinginjava.

JAVAPROGRAMMING Page41
UsageofJavaMethodOverriding
o Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
o Methodoverridingisusedforruntimepolymorphism

RulesforJavaMethodOverriding
1. methodmusthavesamenameasintheparentclass
2. methodmusthavesameparameterasintheparentclass.
3. mustbeIS-Arelationship(inheritance).

ExampleofmethodoverridingCl
assVehicle{
voidrun(){System.out.println("Vehicleisrunning");}
}
classBike2extendsVehicle{
voidrun(){System.out.println("Bikeisrunningsafely");}
publicstaticvoidmain(String args[]){ Bike2
obj = newBike2();
obj.run();
}

Output:Bikeisrunningsafely

1.classBank{
intgetRateOfInterest(){return0;}
}
classSBIextendsBank{
intgetRateOfInterest(){return8;}
}
classICICIextendsBank{
intgetRateOfInterest(){return7;}
}
classAXISextendsBank{
intgetRateOfInterest(){return9;}
}
classTest2{
publicstaticvoidmain(String args[])
{ SBI s=newSBI();
ICICI i=newICICI();
AXIS a=newAXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}

Output:
SBIRateofInterest:8

JAVAPROGRAMMING Page42
ICICI Rate of Interest: 7
AXISRateofInterest:9

AbstractclassinJava

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). It needs to be extended and its method
implemented. It cannot be instantiated.

Exampleabstractclass
1.abstractclassA{}

abstractmethod
1.abstractvoidprintStatus();//nobodyandabstract

Exampleofabstractclassthathasabstractmethod
abstractclassBike{
abstractvoidrun();
}
classHonda4extendsBike{
voidrun(){System.out.println("runningsafely..");}
publicstaticvoidmain(String args[])
{ Bike obj = newHonda4();
obj.run();
}
1.}
runningsafely..
InterfaceinJava
Aninterfaceinjavaisablueprintofaclass.Ithasstaticconstantsandabstractmethods.

Theinterfaceinjavaisamechanismtoachieveabstraction.Therecanbeonlyabstractmethods in the java


interface not method body. It is used to achieve abstraction and multiple inheritance inJava.

Java Interface also representsIS-Arelationship.It

cannot be instantiated just like abstract class.

Therearemainlythreereasonstouseinterface.Theyaregivenbelow.
o Itisusedtoachieveabstraction.
o Byinterface,wecansupportthefunctionalityofmultiple inheritance.
o Itcanbeusedtoachieveloosecoupling.

JAVAPROGRAMMING Page43
Internaladditionbycompiler

Understandingrelationshipbetweenclassesandinterfaces

//Interfacedeclaration:by firstuser
interfaceDrawable{
voiddraw();
}
//Implementation:byseconduser
classRectangleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingrectangle");}
}
classCircleimplementsDrawable{
publicvoiddraw(){System.out.println("drawingcircle");}
}
//Usinginterface:bythirduser
classTestInterface1{
publicstaticvoidmain(Stringargs[]){
Drawable d=newCircle();//In real scenario, object is provided by method e.g.
getDrawable()d.draw();
}}
Output:drawingcircle

MultipleinheritanceinJavabyinterface

interfacePrintable{

JAVAPROGRAMMING Page44
voidprint();
}
interfaceShowable{
voidshow();
}
classA7implementsPrintable,Showable{
publicvoidprint(){System.out.println("Hello");}
publicvoidshow(){System.out.println("Welcome");}
publicstaticvoidmain(String args[]){
A7 obj= newA7();
obj.print();
obj.show();
}}

Output:Hello
Welcome
Abstractclass Interface

1) Abstract class can Interface can have onlyabstract methods. Since


haveabstractandnon-abstract Java8,itcanhave default and
methods. staticmethods also.
2) Abstract support Interfacesupportsmultipleinheritance.

classdoesn'tmultipleinherita
nce.
3) Abstract class canhavefinal,non- Interfacehasonlystaticandfinalvariables.
final,staticandnon-staticvariables.
4)Abstractclasscanprovidetheimple Interface
mentationofinterface. can'tprovidetheimplementationofabstractclass.
5) The abstractkeyword is used to Theinterface keywordis used to declare
declare abstract class. interface.
6)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

JavaInnerClasses
Javainnerclassornestedclassisaclasswhichisdeclaredinsidetheclassorinterface.

We use inner classes tologicallygroupclasses andinterfaces in one place sothatit can be more
readable and maintainable.

SyntaxofInnerclass
1. classJava_Outer_class{
2. //code
3. classJava_Inner_class{
4. //code
JAVAPROGRAMMING Page45
5. }}

JAVAPROGRAMMING Page46
Advantageofjavainnerclasses

Therearebasicallythreeadvantagesofinnerclassesinjava.Theyareasfollows:

1) Nested classes representa special type ofrelationshipthatis


itcanaccessallthemembers(datamembersandmethods)ofouterclass including private.

2) Nested classes are used todevelopmorereadableandmaintainablecode because


itlogically group classes and interfaces in one placeonly.

3) CodeOptimization:Itrequireslesscodetowrite.

DifferencebetweennestedclassandinnerclassinJava

Innerclassisapartofnestedclass.Non-staticnestedclassesareknownasinnerclasses.

TypesofNestedclasses

There are two types of nestedclasses non-static and static nested classes.The non-static nested
classes are also known as inner classes.

o Non-staticnestedclass(innerclass)
1. Memberinnerclass
2. Anonymousinnerclass
3. Localinnerclass
o Staticnestedclass

JavaPackage
A javapackageisagroupof similar typesofclasses,interfacesandsub-packages. Package in java

can be categorized in two form, built-in package and user-defined package. There are

manybuilt-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

AdvantageofJavaPackage

1) Java package is used to categorize the classes and interfaces so that they can beeasily
maintained.

2) Javapackageprovidesaccessprotection.

3) Javapackageremovesnamingcollision.

packagemypack;
publicclassSimple{
publicstaticvoidmain(String args[])
{ System.out.println("Welcome to package");
}}

JAVAPROGRAMMING Page47
Howtocompilejavapackage

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename


Howtorunjavapackageprogram

ToCompile:javac-d.Simple.java
ToRun:javamypack.Simple

Usingfullyqualifiedname

Exampleofpackageby importfullyqualifiedname

//save byA.java
packagepack;
publicclassA{
publicvoidmsg(){System.out.println("Hello");}}
//save by B.java
packagemypack;
classB{
publicstaticvoidmain(Stringargs[]){
pack.A obj = newpack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

JAVAPROGRAMMING Page48
UNIT-3

ExceptionHandling
Theexceptionhandlinginjavaisoneofthepowerfulmechanismtohandletheruntimeerrors so that
normal flow of the application can be maintained.

Whatisexception

Injava, exception isan eventthatdisrupts the normalflow of the program.Itisan objectwhichis thrown at
runtime.

AdvantageofExceptionHandling

The core advantage of exception handling is tomaintainthenormalflowoftheapplication.


Exception normally disrupts the normal flow of the application that is why we use exception
handling.

TypesofException

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. CheckedException
2. UncheckedException
3. Error

Differencebetweencheckedanduncheckedexceptions

1) CheckedException:TheclassesthatextendThrowableclassexceptRuntimeExceptionandErro
rareknownascheckedexceptionse.g.IOException,SQLExceptionetc.Checkedexceptionsarecheck
edatcompile-time.

2) UncheckedException:TheclassesthatextendRuntimeExceptionareknownasunchecked
exceptionse.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExceptionetc
.Uncheckedexceptionsarenotcheckedatcompile-timerathertheyarecheckedatruntime.

3) Error:Errorisirrecoverablee.g.OutOfMemoryError,VirtualMachineError,AssertionErroretc.

JAVAPROGRAMMING Page49
HierarchyofJavaExceptionclasses

CheckedandUnCheckedExceptions

JAVAPROGRAMMING Page50
Javatryblock

Java tryblock isused to enclose the code thatmightthrow an exception. Itmust be used within the
method.

Javatryblockmustbefollowedbyeithercatchorfinallyblock.

Syntaxofjavatry-catch

1. try{
2. //codethatmaythrowexception
3. }catch(Exception_class_Name ref){}

Syntax of try-finallyblock

1. try{
2. //codethatmaythrowexception
3. }finally{}

Javacatchblock

Java catch block is usedto handle the Exception.Itmust be used after the tryblock only.

You can use multiple catch block with a single try.

Problemwithoutexceptionhandling

Let'strytounderstandtheproblemifwedon'tusetry-catchblock.

publicclassTesttrycatch1{
publicstaticvoidmain(String args[])
{intdata=50/0;//may throw exception
System.out.println("rest of the code...");
}}
Output:
Exceptioninthreadmainjava.lang.ArithmeticException:/byzero

Asdisplayedintheaboveexample,restofthecodeisnotexecuted(insuchcase,restofthe code...
statement is not printed).

There can be 100 lines of code after exception. So all the code afterexception will notbe
executed.

Solutionbyexceptionhandling

Let'sseethesolutionofaboveproblembyjavatry-catchblock.

publicclassTesttrycatch2{

JAVAPROGRAMMING Page51
publicstaticvoidmain(Stringargs[]){
try{
intdata=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Now, as displayedin the above example, rest of the code is executedi.e. rest of the code...
statement is printed.

JavaMulticatchblock

Ifyou have to performdifferent tasks at the occurrence of different Exceptions, use java multi
catch block.

Let'sseeasimpleexampleofjavamulti-catchblock.

1. publicclassTestMultipleCatchBlock{
2. publicstaticvoidmain(Stringargs[]){
3. try{
4. inta[]=newint[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticExceptione){System.out.println("task1iscompleted");}
8. catch(ArrayIndexOutOfBoundsExceptione){System.out.println("task2completed");
9.}
10. catch(Exceptione){System.out.println("commontaskcompleted");
11.}
12. System.out.println("restofthecode...");
13. }}

Output:task1 completed
rest of the code...

Javanestedtryexample

Let'sseeasimpleexampleofjavanestedtryblock.

classExcep6{
publicstaticvoidmain(Stringargs[]){
try{ tr
y{
System.out.println("goingtodivide");
intb=39/0;
}catch(ArithmeticExceptione){System.out.println(e);}

try{

JAVAPROGRAMMING Page52
inta[]=newint[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1.}
Javafinallyblock

Javafinallyblock is ablock that is usedtoexecuteimportantcode such as closing connection, stream


etc.

Java finallyblock is always executed whether exception is handled or not.

Java finally block follows try or catch block.

UsageofJavafinally

Case1

Let's see the java finally example where exceptiondoesn'toccur.

classTestFinallyBlock{
publicstaticvoidmain(Stringargs[]){
try{
intdata=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

Javathrowkeyword

TheJavathrowkeywordisusedtoexplicitlythrowanexception.

We can throw eitherchecked or unchekedexception in javabythrow keyword. Thethrow


keywordismainly usedtothrow custom exception.Wewill seecustom exceptionslater.

Thesyntaxofjavathrowkeywordisgivenbelow.

1. throwexception;

JAVAPROGRAMMING Page53
Javathrowkeywordexample

Inthisexample,wehavecreatedthevalidatemethodthattakesintegervalueasaparameter.If the age


is less than 18, we are throwing the ArithmeticException otherwise print a message welcome
to vote.

1. publicclassTestThrow1{
staticvoidvalidate(intage){
if(age<18)
thrownewArithmeticException("notvalid");
else
System.out.println("welcometovote");
}
publicstaticvoidmain(String args[]){
validate(13);
System.out.println("restofthecode...");
}}

Output:

Exceptioninthreadmainjava.lang.ArithmeticException:notvalid
Javathrowskeyword

TheJavathrowskeyword is used to declare an exception. It gives an information to the


programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Syntaxofjavathrows
1. return_typemethod_name()throwsexception_class_name{
2. //methodcode
3.}
4.

Javathrowsexample

Let's see the example of java throws clausewhich describes thatcheckedexceptions can be
propagated by throws keyword.

importjava.io.IOException;
classTestthrows1{
voidm()throwsIOException{
thrownewIOException("deviceerror");//checkedexception

JAVAPROGRAMMING Page54
}
voidn()throwsIOException{ m
();
}
voidp(){
try{ n(
);
}catch(Exceptione){System.out.println("exceptionhandled");}
}
publicstaticvoidmain(String args[])
{ Testthrows1 obj=newTestthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...

JavaCustomException

If you are creating your own Exception thatis known as custom exception or user-defined
exception.Javacustom exceptionsare usedtocustomizetheexception according touserneed.

Bythe helpof custom exception, youcan haveyour own exception and message.

Let's see a simple example of java custom exception.

classInvalidAgeException
extendsException{ InvalidAgeException(String s){
super(s);
}}
classTestCustomException1{
staticvoidvalidate(intage)throwsInvalidAgeException{
if(age<18)
thrownewInvalidAgeException("notvalid");
else
System.out.println("welcometovote");
}
publicstaticvoidmain(Stringargs[]){
try{ validate
(13);
}catch(Exceptionm){System.out.println("Exceptionoccured:"+m);}

System.out.println("restofthecode...");
}}

Output:Exceptionoccured:InvalidAgeException:notvalidrestofthecode...

JAVAPROGRAMMING Page55
Multithreading

Multithreadinginjavaisaprocessofexecutingmultiplethreadssimultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

JavaMultithreadingismostlyusedingames,animationetc.

AdvantagesofJavaMultithreading

1) It doesn'tblocktheuser because threads are independent and you can performmultiple


operations at same time.

2) Youcanperformmanyoperationstogethersoitsavestime.

3) Threadsareindependentsoitdoesn'taffectotherthreadsif exceptionoccurinasinglethread.

LifecycleofaThread(ThreadStates)

Athreadcanbeinoneofthefivestates.Accordingtosun,thereisonly4 statesinthreadlifecycleinjava
new, runnable, non-runnable and terminated. There is no running state.

Butforbetterunderstandingthethreads,weareexplainingitinthe5states.

ThelifecycleofthethreadinjavaiscontrolledbyJVM.Thejavathreadstatesareasfollows:

1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated

JAVAPROGRAMMING Page56
Howtocreatethread

Therearetwowaystocreateathread:

1. By extendingThreadclass
2. ByimplementingRunnableinterface.

Threadclass:

Thread class provide constructors and methods to create and perform operations on
athread.Thread class extends Object class and implements Runnable interface.

CommonlyusedConstructorsofThreadclass:

o Thread()
oThread(String name)
oThread(Runnable r)
o Thread(Runnabler,Stringname)

JAVAPROGRAMMING Page57
CommonlyusedmethodsofThreadclass:

1. publicvoidrun():isusedtoperformactionforathread.
2. publicvoidstart():startstheexecutionofthethread.JVMcallstherun()methodonthethread.
3. publicvoidsleep(longmiliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. publicvoidjoin():waitsforathreadtodie.
5. publicvoidjoin(longmiliseconds):waitsforathreadtodie forthespecifiedmiliseconds.
6. publicintgetPriority():returnsthepriorityofthethread.
7. publicintsetPriority(intpriority):changesthepriorityofthethread.
8. publicStringgetName():returnsthenameofthethread.
9. publicvoidsetName(Stringname):changesthenameofthethread.
10. publicThreadcurrentThread():returnsthereferenceofcurrentlyexecutingthread.
11. publicintgetId():returnstheidofthethread.
12. publicThread.StategetState():returnsthestateofthethread.
13. publicbooleanisAlive():testsifthethreadisalive.
14. publicvoidyield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. publicvoidsuspend():isusedtosuspendthethread(depricated).
16. publicvoidresume():isusedtoresumethesuspendedthread(depricated).
17. publicvoidstop():isusedtostopthethread(depricated).
18. publicbooleanisDaemon():testsifthethreadisadaemonthread.
19. publicvoidsetDaemon(booleanb):marksthethreadasdaemonoruserthread.
20. publicvoidinterrupt():interruptsthethread.
21. publicbooleanisInterrupted():testsifthethreadhasbeeninterrupted.
22. publicstaticbooleaninterrupted():testsifthecurrentthreadhasbeeninterrupted.

Runnableinterface:

The Runnable interface should be implementedby any class whoseinstances are intendedto be
executed by a thread. Runnable interfacehave only onemethod named run().
1. publicvoidrun():isusedtoperformactionforathread.

Startingathread:

start()method of Threadclass is used tostart a newly created thread. It performs following


tasks:
o Anewthreadstarts(withnewcallstack).
oThethreadmovesfromNewstatetotheRunnablestate.
oWhenthethreadgetsachancetoexecute,itstargetrun()methodwillrun.

JAVAPROGRAMMING Page58
JavaThreadExamplebyextendingThreadclassclass

Multi extendsThread{
publicvoidrun(){ System.out.println("thread
is running...");
}
publicstaticvoidmain(String args[])
{ Multi t1=newMulti();
t1.start();
}}
Output:threadisrunning...

JavaThreadExamplebyimplementingRunnableinterfaceclassMu

lti3 implementsRunnable{
publicvoidrun(){ System.out.println("thread
is running...");
}
publicstaticvoidmain(String args[]){ Multi3
m1=newMulti3();
Thread t1 =newThread(m1);
t1.start();
}}
Output:threadisrunning...

PriorityofaThread(ThreadPriority):
Each thread have a priority. Priorities are represented bya number between 1and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptivescheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.

3constantsdefinedinThreadclass:

1. publicstaticintMIN_PRIORITY
2. publicstaticintNORM_PRIORITY
3. publicstaticintMAX_PRIORITY

Default priorityof a threadis 5(NORM_PRIORITY). The value of MIN_PRIORITY is 1and the


value of MAX_PRIORITY is 10.

ExampleofpriorityofaThread:classTe
stMultiPriority1extendsThread{ publicvoi
drun(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running threadpriority is:"+Thread.currentThread().getPriority());
}
publicstaticvoidmain(Stringargs[]){

JAVAPROGRAMMING Page59
TestMultiPriority1 m1=newTestMultiPriority1();
TestMultiPriority1 m2=newTestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Output:running thread name is:Thread-0
runningthreadpriorityis:10running
thread name is:Thread-1 running
thread priority is:1

Javasynchronizedmethod

If you declare any method as synchronized, it is known as synchronized method.

Synchronizedmethodis usedtolock an object for any shared resource.

When a threadinvokes a synchronizedmethod, itautomaticallyacquires the lock for that object and
releases it when the thread completes its task.

Exampleofinterthreadcommunicationinjava

Let'sseethesimpleexampleofinterthreadcommunication.

classCustomer{
intamount=10000;
synchronizedvoidwithdraw(intamount)
{ System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Lessbalance;waitingfordeposit...");
try{wait();}catch(Exceptione){}
}
this.amount-=amount;
System.out.println("withdrawcompleted...");
}
synchronizedvoiddeposit(intamount)
{ System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("depositcompleted... ");
notify();
}
}
classTest{
publicstaticvoidmain(String args[]){
finalCustomer
c=newCustomer();newThread(){
publicvoidrun(){c.withdraw(15000);}
}.start();
newThread(){

JAVAPROGRAMMING Page60
publicvoidrun(){c.deposit(10000);}
}
start();
}}
Output:goingtowithdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
ThreadGroupinJava
Java provides a convenientwaytogroupmultiple threads in asingle object.In such way, we can
suspend, resume or interrupt group of threads by a single method call.

Note:Nowsuspend(),resume()andstop()methodsaredeprecated.

Java thread group is implemented by java.lang.ThreadGroup class.

Constructors of ThreadGroup class

ThereareonlytwoconstructorsofThreadGroupclass.

ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)

Let'sseeacodetogroupmultiplethreads.

1. ThreadGrouptg1=newThreadGroup("GroupA");
2. Threadt1=newThread(tg1,newMyRunnable(),"one");
3. Threadt2=newThread(tg1,newMyRunnable(),"two");
4. Threadt3=newThread(tg1,newMyRunnable(),"three");

Now all 3threads belong to one group. Here, tg1 is the threadgroup name, MyRunnable is the
class thatimplements Runnableinterface and"one","two" and"three" arethe threadnames.

Nowwecaninterruptallthreadsbyasinglelineofcodeonly.

1. Thread.currentThread().getThreadGroup().interrupt();

Exploringjava.netandjava.text
JAVAPROGRAMMING Page61
java.net
The term networkprogramming refers to writing programs that execute across multiple devices
(computers),in which the devices are all connectedtoeach other using anetwork.

The java.net package of the J2SE APIs contains a collection of classes and interfaces thatprovide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.

Thejava.netpackageprovidessupportforthetwocommonnetworkprotocols−

 TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.

 UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows
for packets of data to be transmitted between applications.

Thischaptergivesagoodunderstandingonthefollowingtwosubjects−

 SocketProgramming − This is the most widely used concept in Networking and it has
been explained in very detail.

 URLProcessing−Thiswouldbecoveredseparately.

java.text

The java.text package is necessary forevery java developer tomaster because it has a lot of
classes that is helpful in formatting such as dates, numbers, and messages.

java.textClasses

The following are the classes available for java.text package

[table]
Class|Description
SimpleDateFormat|is a concrete class that helps in formatting and parsing of dates.
[/table]

JAVAPROGRAMMING Page62
UNIT-4
CollectionFrameworkinJava

Collectionsinjava is a framework that provides an architecture to store and manipulate the group
of objects.

All the operations that you perform ona data suchas searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.

Java Collection simplymeans a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

Whatisframeworkinjava
o providesreadymadearchitecture.
o representssetofclassesandinterface.
o isoptional.

WhatisCollectionframework

Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

1. Interfacesanditsimplementationsi.e.classes
2. Algorithm

JAVAPROGRAMMING Page63
HierarchyofCollectionFramework

JavaArrayListclass
JavaArrayListclassusesadynamicarrayforstoringtheelements.ItinheritsAbstractListclass and
implements List interface.

TheimportantpointsaboutJavaArrayListclassare:

o JavaArrayListclasscancontainduplicateelements.
o JavaArrayListclassmaintainsinsertionorder.
o JavaArrayListclassisnonsynchronized.
o JavaArrayListallowsrandomaccessbecausearrayworksattheindexbasis.
o InJavaArrayListclass,manipulationis slow because alot of shifting needstobeoccurred if any
element is removed from the array list.

JAVAPROGRAMMING Page64
ArrayListclassdeclaration

Let'sseethedeclarationforjava.util.ArrayListclass.

ConstructorsofJavaArrayList

Constructor Description

ArrayList() Itisusedtobuildanemptyarraylist.

ArrayList(Collection It is used to build an arraylist that is initialized withthe


c) elements of the collection c.

ArrayList(int It is used to build an array list that has the specified


capacity) initial capacity.

JavaArrayListExampleimportj
ava.util.*;
classTestCollection1{
publicstaticvoidmain(Stringargs[]){
ArrayList<String> list=newArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next()); } }}

Ravi
Vijay
Ravi
Ajay

JAVAPROGRAMMING Page65
vector

ArrayListandVectorbothimplementsListinterfaceandmaintainsinsertionorder.

ButtherearemanydifferencesbetweenArrayListandVectorclassesthataregivenbelow.

ArrayList Vector

1)ArrayListisnotsynchronized. Vectorissynchronized.

2)ArrayListincrements50% of Vector increments100% means doubles the array


current array size if number of size if total number of element exceeds than its
element exceeds from itscapacity. capacity.

3)ArrayList is notalegacy class, it Vectorisalegacyclass.


is introduced in JDK 1.2.

4)ArrayListisfastbecauseitis Vector is slow because it is synchronized i.e. in


non-synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until
current thread releases the lock of object.

5) ArrayLis tuses Iterator interface Vector uses Enumeration interface to traverse the
to traverse the elements. elements. But it can use Iterator also.

ExampleofJavaVector

Let'sseeasimpleexampleofjavaVectorclassthatusesEnumerationinterface.

1. importjava.util.*;
2. classTestVector1{
3. publicstaticvoidmain(Stringargs[]){
4. Vector<String>v=newVector<String>();//creatingvector
5. v.add("umesh");//methodofCollection
6. v.addElement("irfan");//methodofVector
7. v.addElement("kumar");
8. //traversingelementsusingEnumeration

JAVAPROGRAMMING Page66
9. Enumeratione=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }}}

Output:

umesh
irfan
kumar

JavaHashtableclass

JavaHashtableclassimplementsahashtable,whichmapskeystovalues.ItinheritsDictionary class
and implements the Map interface.

TheimportantpointsaboutJavaHashtableclassare:

o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on thekey.
o Itcontainsonlyuniqueelements.
o Itmayhavenothave anynullkeyorvalue.
o Itissynchronized.

Hashtableclassdeclaration

Let'sseethedeclarationforjava.util.Hashtableclass.

1. publicclassHashtable<K,V>extendsDictionary<K,V>implementsMap<K,V>, Cloneable, Ser


ializable

HashtableclassParameters

Let'sseetheParametersforjava.util.Hashtableclass.

o K:Itisthetypeofkeysmaintainedbythismap.
o V:Itisthetypeofmappedvalues.

JAVAPROGRAMMING Page67
ConstructorsofJavaHashtableclass

Constructor Description

Hashtable() It is the default constructorof hash table it instantiates the


Hashtable class.

Hashtable(intsize) It is used to accept an integer parameter and creates a hashtable


that has an initial size specified by integer value size.

Hashtable(int size, float It is used to create a hashtable that has an initial size specified by
fillRatio) size and a fill ratio specified by fillRatio.

JavaHashtableExample
importjava.util.*;
classTestCollection16{
publicstaticvoidmain(Stringargs[])
{Hashtable<Integer,String>hm=newHashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entrym:hm.entrySet()){ System.out.println(m.getKey()
+""+m.getValue());
}}}

Output:

103Rahul
102Ravi
101Vijay
100Amit

Stack

StackisasubclassofVectorthatimplementsastandardlast-in,first-outstack.

Stack only definesthe default constructor,which creates an empty stack. Stack includes all the
methods defined by Vector, and adds several of its own.

JAVAPROGRAMMING Page68
Stack()
Example
Thefollowingprogramillustratesseveralofthemethodssupportedbythiscollection−

importjava.util.*;

publicclassStackDemo{

static void showpush(Stack st, int a) {

st.push(new Integer(a));

System.out.println("push("+ a + ")");

System.out.println("stack: "+ st);}

static void showpop(Stack st) {

System.out.print("pop->");Integer a

= (Integer) st.pop();

System.out.println(a);

System.out.println("stack: "+ st); }

public static void main(String args[]) {

Stack st = new Stack();

System.out.println("stack: "+ st);

showpush(st, 42);

showpush(st,66);

showpush(st, 99);

showpop(st);

showpop(st);

showpop(st);

try{

showpop(st);

} catch (EmptyStackException e) {

System.out.println("empty stack");

JAVAPROGRAMMING Page69
}}}

Thiswillproducethefollowingresult−

Output
stack: [ ]
push(42)
stack: [42]
push(66)
stack:[42,66]
push(99)
stack:[42,66,99]
pop->99
stack:[42,66]
pop->66
stack:[42]
pop->42
stack: [ ]
pop->emptystack

Enumeration
TheEnumerationInterface

The Enumeration interface defines the methods bywhichyoucan enumerate (obtain one at a time)
the elements in a collection of objects.
ThemethodsdeclaredbyEnumerationaresummarizedinthefollowingtable−

Sr.No. Method&Description

booleanhasMoreElements(
1 )

Whenimplemented,itmustreturntruewhiletherearestillmoreelementstoextract,and false when


all the elements have been enumerated.

ObjectnextElement(
2 )

ThisreturnsthenextobjectintheenumerationasagenericObjectreference.

Example

JAVAPROGRAMMING Page70
FollowingisanexampleshowingusageofEnumeration.

import

java.util.Vector;importjava.ut

il.Enumeration;

publicclassEnumerationTester{

public static void main(String args[]) {

Enumeration days;

Vector dayNames = new Vector();

dayNames.add("Sunday");

dayNames.add("Monday");

dayNames.add("Tuesday");

dayNames.add("Wednesday");

dayNames.add("Thursday");

dayNames.add("Friday");

dayNames.add("Saturday");

days =

dayNames.elements();while

(days.hasMoreElements()) {

Thiswillproducethefollowingresult−

Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Iterator

JAVAPROGRAMMING Page71
Itis auniversal iterator as we can apply it toany Collection object. Byusing Iterator,we can perform
both read and remove operations.It is improved version of Enumeration with additionalfunctionality
of remove-ability of a element.
Iterator must be used whenever we want to enumerate elements in all Collection framework
implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map
interface. Iterator is the only cursor available for entire collection framework.
Iteratorobjectcanbecreatedbycallingiterator()methodpresentinCollectioninterface.

//Here"c"isanyCollectionobject.itrisof
//typeIteratorinterfaceandrefersto"c" Iterator
itr = c.iterator();

Iteratorinterfacedefinesthreemethods:
//Returnstrueiftheiterationhasmoreelements

publicbooleanhasNext();

//Returnsthenextelementintheiteration
//ItthrowsNoSuchElementExceptionifnomore
//elementpresent
publicObjectnext();

//Removethenextelementintheiteration
//Thismethodcanbecalledonlyoncepercall
//tonext()

publicvoidremove();
remove()methodcanthrowtwoexceptions
 UnsupportedOperationException:Iftheremoveoperationisnotsupportedbythisiterator
 IllegalStateException: If the next method has not yetbeen called, or the removemethod has
already been calledafter the last call to the nextmethod
LimitationsofIterator:
 Onlyforwarddirectioniteratingispossible.
 ReplacementandadditionofnewelementisnotsupportedbyIterator.

StringTokenizerinJava

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.

Itdoesn'tprovidethefacilitytodifferentiatenumbers,quotedstrings,identifiersetc.

ConstructorsofStringTokenizerclass

Thereare3constructorsdefinedintheStringTokenizerclass.

JAVAPROGRAMMING Page72
ConstructorDescription

StringTokenizer(Stringstr) createsStringTokenizerwithspecifiedstring.

StringTokenizer(String str, creates StringTokenizer with specified string and


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter


String delim, boolean andreturnValue.Ifreturnvalue is true, delimiter
returnValue) characters are considered to be tokens. If it is false,
delimitercharactersservetoseparatetokens.

MethodsofStringTokenizerclass

The6usefulmethodsofStringTokenizerclassareasfollows:

Publicmethod Description

booleanhasMoreTokens() checksifthereismoretokensavailable.

StringnextToken() returnsthenexttokenfromtheStringTokenizerobject.

StringnextToken(Stringdelim) returnsthenexttokenbasedonthedelimeter.

booleanhasMoreElements() sameashasMoreTokens()method.

ObjectnextElement() sameasnextToken()butitsreturntypeisObject.

intcountTokens() returnsthetotalnumberoftokens.

SimpleexampleofStringTokenizerclass

Let's see the simpleexample ofStringTokenizer classthat tokenizes astring"mynameiskhan" on the


basis of whitespace.

importjava.util.StringTokenizer;
publicclassSimple{
publicstaticvoidmain(Stringargs[]){

JAVAPROGRAMMING Page73
StringTokenizerst=newStringTokenizer("mynameiskhan","");
while(st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}
Output:my
name
is
khan
ExampleofnextToken(Stringdelim)methodofStringTokenizerclass
importjava.util.*;
publicclassTest{
publicstaticvoidmain(String[]args){
StringTokenizerst=newStringTokenizer("my,name,is,khan");
//printingnexttoken
System.out.println("Nexttokenis:"+st.nextToken(","));
} }
Output:Nexttokenis:my

java.util.Random
 For using this class to generate random numbers, we have to first create aninstance of this
class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that
instance.
 We can generate random numbers of types integers, float, double, long, booleans using this
class.
 Wecanpassargumentstothemethodsforplacinganupperboundontherangeofthe numbersto be
generated. For example, nextInt(6) willgenerate numbersinthe range 0to 5 bothinclusive.
//AJavaprogramtodemonstraterandomnumbergeneration
// usingjava.util.Random;
import java.util.Random;

publicclassgenerateRandom{

publicstaticvoidmain(Stringargs[])
{
// create instance of Random class
Random rand = new Random();

// Generate random integers in range 0 to 999


int rand_int1 = rand.nextInt(1000);
intrand_int2=rand.nextInt(1000);

JAVAPROGRAMMING Page74
//Print randomintegersSystem.out.println("Random
Integers: "+rand_int1); System.out.println("Random
Integers:"+rand_int2);

//GenerateRandomdoubles
double rand_dub1 = rand.nextDouble();
doublerand_dub2=rand.nextDouble();

//Printrandomdoubles
System.out.println("Random Doubles: "+rand_dub1);
System.out.println("RandomDoubles:"+rand_dub2);
}}
Output:

RandomIntegers:547
RandomIntegers:126
RandomDoubles:0.8369779739988428

RandomDoubles:0.5497554388209912

JavaScannerclass

There are variouswaysto read input from the keyboard, the java.util.Scanner class isone of them.
TheJavaScannerclassbreakstheinputintotokensusingadelimiterthatiswhitespace bydefault. It
providesmany methods to readand parse various primitive values.

Java Scanner class is widely usedto parse text for string and primitive types using regular expression.

JavaScannerclassextendsObjectclassandimplementsIteratorandCloseableinterfaces.

CommonlyusedmethodsofScannerclass

ThereisalistofcommonlyusedScannerclassmethods:

Method Description

publicStringnext() itreturnsthenexttokenfromthescanner.

publicStringnextLine() itmovesthescannerpositiontothenextlineandreturnsthevalue as a
string.

publicbytenextByte() itscansthenexttokenasabyte.

JAVAPROGRAMMING Page74
publicshortnextShort() itscansthenexttokenasashortvalue.

publicintnextInt() itscansthenexttokenasanintvalue.

publiclongnextLong() itscansthenexttokenasalongvalue.

publicfloatnextFloat() itscansthenexttokenasafloatvalue.

public double itscansthenexttokenasadoublevalue.


nextDouble()

JavaScannerExampletogetinputfromconsole

Let's see the simpleexample of the Java Scanner class which reads the int, string and
doublevalue as an input:

importjava.util.Scanner;
classScannerTest{
publicstaticvoidmain(String args[])
{ Scanner sc=newScanner(System.in);
System.out.println("Enter your rollno");
introllno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
doublefee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
sc.close();
}}Output:
Enter yourrollno
111
Enteryourname Ratan
Enter
450000
Rollno:111name:Ratanfee:450000

JAVAPROGRAMMING Page75
JavaCalendarClass

Java Calendar class is an abstract class that provides methods for converting date between a
specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.

JavaCalendarclassdeclaration

Let'sseethedeclarationofjava.util.Calendarclass.

1. publicabstractclassCalendarextendsObject
2. implementsSerializable,Cloneable,Comparable<Calendar>

JavaCalendarClassExample

importjava.util.Calendar;
publicclassCalendarExample1{
publicstaticvoidmain(String[] args)
{ Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : "+calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: "+ calendar.getTime());
calendar.add(Calendar.MONTH, 4);System.out.println("4
months later: "+ calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2yearslater:"+calendar.getTime());
}}

Output:

The current date is :Thu Jan 19 18:47:02 IST 2017


15 days ago: Wed Jan 04 18:47:02 IST 2017
4monthslater:ThuMay0418:47:02IST2017
2yearslater:SatMay0418:47:02IST2019

JAVAPROGRAMMING Page76
Java-FilesandI/O
The java.io package contains nearly every class you might ever need to perform input and
output(I/O)inJava.Allthesestreamsrepresentaninputsourceandanoutputdestination.Thestream in
thejava.iopackage supportsmanydatasuch asprimitives, object,localizedcharacters, etc.

Stream
Astreamcanbedefinedasasequenceofdata.TherearetwokindsofStreams−

 InPutStream−TheInputStreamisusedtoreaddatafromasource.

 OutPutStream−TheOutputStreamisusedforwritingdatatoadestination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −

ByteStreams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classesrelatedtobytestreamsbutthemostfrequentlyusedclasses are,FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file−

Example

importjava.io.*;public class CopyFile {


public static void main(String args[]) throws IOException { FileInputStream in = null;
FileOutputStreamout = null; try{
in=newFileInputStream("input.txt");

out = new FileOutputStream("output.txt"); int c;


while((c=in.read())!=-1){

JAVAPROGRAMMING Page77
out.write(c);

}finally{

if(in!=null){

in.close();

if (out!=null) {

out.close();

}}}}

Nowlet'shaveafileinput.txtwiththefollowingcontent−

Thisistestforcopyfile.

Asanextstep,compiletheabove program andexecuteit,whichwill resultincreatingoutput.txt


filewiththesamecontentaswehaveininput.txt.Solet'sputtheabovecodeinCopyFile.java file and do the
following−

$javacCopyFile.java
$javaCopyFile
CharacterStreams
JavaByte streamsareusedtoperforminputandoutputof8-bitbytes,whereas Java Character streams
are used to perform input and output for 16-bit unicode. Though there
aremanyclassesrelatedtocharacterstreamsbutthemostfrequentlyusedclasses are,FileReader
andFileWriter. Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.

We can re-write the above example,which makes theuseof these twoclasses tocopyaninput file
(having unicode characters) into an output file −

Example

importjava.io.*;public

class CopyFile {

publicstaticvoidmain(Stringargs[])throwsIOException{

JAVAPROGRAMMING Page78
FileReader in = null;

FileWriterout=null;

try{

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);}

}finally{

if(in!=null){

in.close();}

if (out!=null) {

out.close();

}}}}

Nowlet'shaveafileinput.txtwiththefollowingcontent−

Thisistestforcopyfile.

Asa nextstep,compiletheaboveprogramandexecuteit, which willresult increatingoutput.txt file


with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −

$javacCopyFile.java
$javaCopyFile
StandardStreams
AlltheprogramminglanguagesprovidesupportforstandardI/Owheretheuser'sprogramcan take input
from a keyboard and then produce an output on the computer screen. Java provides the following
three standard streams −

 StandardInput − Thisisusedtofeedthe data touser'sprogram andusually akeyboard is used


as standard input stream and represented asSystem.in.

JAVAPROGRAMMING Page79
 StandardOutput − This is used to output the data produced by the user's program and
usually acomputerscreenisusedforstandardoutputstreamandrepresented as System.out.

 StandardError − This is used to output the error data produced by the user's program
andusuallyacomputerscreenisusedforstandarderrorstreamandrepresented as System.err.

Following is a simple program, which creates InputStreamReader to read standard input


streamuntil the user types a "

Example
importjava.io.*;

publicclassReadConsole{

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

InputStreamReader cin = null;

try{

cin = new InputStreamReader(System.in);

System.out.println("Enter characters, 'q' to quit.");

char c;

do{

c= (char) cin.read();

System.out.print(c);

}while(c!='q');

}finally{

if(cin!=null){

cin.close();

}}}}

Thisprogramcontinuestoreadandoutputthesamecharacteruntilwepress'q'−

$javacReadConsole.java
$javaReadConsole

JAVAPROGRAMMING Page80
Enter characters, 'q' to quit.
1
1
e
e
q

q
ReadingandWritingFiles
Asdescribedearlier,astreamcanbedefinedasasequenceofdata.TheInputStreamisusedto read data
from a sourceand the OutputStream is used for writing data to a destination.

HereisahierarchyofclassestodealwithInputandOutputstreams.

ThetwoimportantstreamsareFileInputStreamandFileOutputStream

FileInputStream
This stream is used forreading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.

Followingconstructor takes afile nameas a string to create an input stream objecttoread the file −

InputStreamf=newFileInputStream("C:/java/hello");

JAVAPROGRAMMING Page81
Followingconstructor takes afile object tocreate an input stream object to readthe file. Firstwe
create a file object using File() method as follows −

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Onceyouhave InputStream object in hand, then there is alistof helpermethodswhich can be used to
read to stream or to do other operations on the stream.

 ByteArrayInputStream

 DataInputStream

FileOutputStream
FileOutputStreamisusedtocreateafileandwritedataintoit.Thestreamwouldcreateafile,if it doesn't
already exist, before opening it for output.

HerearetwoconstructorswhichcanbeusedtocreateaFileOutputStreamobject.

Followingconstructor takes afile nameas a string tocreate an input stream objecttowrite the file −
Following constructor takes a file object to create an output stream object to writethe file. First,we

OutputStreamf=newFileOutputStream("C:/java/hello")
create a file object using File() method as follows −

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);
Onceyouhave OutputStreamobject in hand, then there is a listof helper methods, whichcan be used
towrite to stream or to do other operations on the stream.
 ByteArrayOutputStream
 DataOutputStream

Example

Following is the example to demonstrate InputStream and OutputStream −

import java.io.*;

publicclassfileStreamTest{

public static void main(String args[]) {

try{

JAVAPROGRAMMING Page82
bytebWrite[]={11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x <bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes} os.close();
InputStream is = new FileInputStream("test.txt"); int size = is.available();
for(inti=0;i<size;i++){
System.out.print((char)is.read()+ "");} is.close();
}catch(IOExceptione){
System.out.print("Exception");

} }}

Java.io.RandomAccessFileClass
The Java.io.RandomAccessFileclass file behaves like alarge arrayofbytes stored in the file
system.Instances ofthisclass support both reading and writing to a random access file.

Classdeclaration
FollowingisthedeclarationforJava.io.RandomAccessFileclass−

public class RandomAccessFile


extends Object
implementsDataOutput,DataInput,Closeable
Classconstructors
S.N Constructor&Description

1
RandomAccessFile(Filefile,Stringmode)

This creates a random access file stream toread from,and optionallyto write to, the file
specified by the File argument.

JAVAPROGRAMMING Page83
2
RandomAccessFile(Filefile,Stringmode)

This creates a random access file stream to read from,and optionallyto write to, a file with the
specified name.

Methodsinherited
Thisclassinheritsmethodsfromthefollowingclasses−

 Java.io.Object

Java.io.FileClassinJava
The File class is Java’s representation of a file or directory path name. Because file and
directorynameshavedifferentformatsondifferentplatforms, asimplestringisnotadequate toname them.
TheFileclasscontainsseveralmethodsforworkingwiththepathname,deletingandrenaming
files,creatingnewdirectories,listingthecontentsofadirectory,anddeterminingseveral common attributes of
files and directories.
 Itisanabstractrepresentationoffileanddirectorypathnames.
 Apathname,whetherabstractorinstringformcanbe eitherabsoluteorrelative.Theparent ofan
abstractpathnamemay be obtainedby invokingthegetParent()methodofthisclass.
 Firstofall,weshouldcreatetheFileclassobjectbypassingthefilenameordirectory name
toit.Afilesystemmayimplementrestrictionstocertainoperationsontheactualfile- system object,
suchasreading, writing, andexecuting. These restrictionsare collectively known as access
permissions.
 Instances of the File class are immutable; that is, once created, the abstract pathname
represented by a File object will never change.
HowtocreateaFileObject?
A File object is created by passing in a String that represents the name of a file, or a String or
another File object. For example,
Filea=newFile("/usr/local/bin/geeks");

defines an abstract filename for thegeeks file in directory/usr/local/bin. This is an absolute abstract
file name.

Programtocheckifafileordirectoryphysicallyexistornot.
//Inthisprogram,weacceptsafileordirectorynamefrom
//commandlinearguments.Thentheprogramwillcheckif
//thatfileordirectory physicallyexistornot and
//itdisplaysthepropertyofthatfileordirectory.
*importjava.io.File;

// Displaying fileproperty
class fileProperty
{
publicstaticvoidmain(String[]args){

JAVAPROGRAMMING Page84
//accept file name or directory name through command line args
String fname =args[0];

//pass the filename or directoryname to File object


File f = new File(fname);

//apply File class methods on File object


System.out.println("File name :"+f.getName());
System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
if(f.exists())
{
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable"+f.canRead());
System.out.println("Is a directory:"+f.isDirectory());
System.out.println("FileSizeinbytes"+f.length());
}
}
}

Output:

Filename:file.txtP

ath:file.txt

Absolutepath:C:\Users\akki\IdeaProjects\codewriting\src\
file.txtParent:null

Exists:true

Iswriteable:tru

eIsreadabletru

Isadirectory:falseFi
leSizeinbytes20
ConncetingtoDB

WhatisJDBCDriver?
JDBC drivers implementthe defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable youtoopen database connections andtointeractwith it by
sending SQL or database commands then receiving results with Java.

JAVAPROGRAMMING Page85
The Java.sqlpackage thatshipswithJDK, containsvariousclasseswiththeir behavioursdefined
andtheiractualimplementaionsaredoneinthird-partydrivers.Thirdpartyvendorsimplements the
java.sql.Driver interface in their database driver.

JDBCDriversTypes
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −

Type1:JDBC-ODBCBridgeDriver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.

The JDBC-ODBC Bridge that comes with


JDK 1.2 is a good example of this kind of driver.

Type2:JDBC-NativeAPI
Ina Type2 driver, JDBC APIcalls areconverted into native C/C++ APIcalls, which areunique to
the database. These drivers are typically provided by the database vendors and used in the same
manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each client
machine.

JAVAPROGRAMMING Page86
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

TheOracleCallInterface(OCI)driverisanexampleofaType2driver.

Type3:JDBC-NetpureJava
In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
informationisthentranslatedbythe middlewareapplicationserverintothecallformat required bythe
DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver canactuallyprovideaccessto multiple databases.

JAVAPROGRAMMING Page87
Youcanthinkof the applicationserver asa JDBC"proxy,"meaningthatitmakescallsfor the
clientapplication.Asaresult,youneedsomeknowledgeoftheapplicationserver'sconfiguration in order to
effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type4:100%PureJava
In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
throughsocket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

WhichDrivershouldbeUsed?
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.

Type 2drivers areuseful in situations,wherea type 3ortype 4driveris not availableyet for your
database.

JAVAPROGRAMMING Page88
The type 1 driver isnot considered a deployment-level driver, and is typicallyusedfor
development and testing purposes only.

Exampletoconnecttothemysqldatabaseinjava

For connecting java application with themysql database,youneed to follow 5 stepsto perform
database connectivity.

InthisexampleweareusingMySqlasthedatabase.Soweneedtoknowfollowinginformations for the


mysql database:

1. Driverclass:Thedriverclassforthemysqldatabaseiscom.mysql.jdbc.Driver.
2. ConnectionURL:TheconnectionURLforthemysqldatabase
isjdbc:mysql://localhost:3306/sonoowherejdbcistheAPI,mysqlisthedatabase,
localhostistheservernameonwhichmysqlisrunning,wemay alsouseIPaddress,3306
istheportnumberandsonooisthedatabasename.Wemayuseanydatabase,insuch case, you need to
replace the sonoo with your databasename.
3. Username:Thedefaultusernameforthemysqldatabaseisroot.
4. Password: Password is given by the user at the time of installing the mysql database. Inthis
example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table,we need to create
database first.

1. createdatabasesonoo;
2. usesonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

ExampletoConnectJavaApplicationwithmysqldatabase

Inthisexample,sonooisthedatabasename,rootistheusernameandpassword.

importjava.sql.*;
classMysqlCon{
publicstaticvoidmain(String args[]){ try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//heresonooisdatabasename,rootisusernameandpassword

JAVAPROGRAMMING Page89
Statementstmt=con.createStatement();
ResultSetrs=stmt.executeQuery("select*fromemp");
while(rs.next())
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3)); con.close();
}catch(Exceptione){System.out.println(e);}
}}

Theaboveexamplewillfetchalltherecordsofemptable.

To connectjava applicationwith the mysql database mysqlconnector.jar file is required to be loaded.

Twowaystoloadthejarfile:
1. pastethemysqlconnector.jarfileinjre/lib/extfolder
2. setclasspath

1) pastethemysqlconnector.jarfileinJRE/lib/extfolder:
Downloadthemysqlconnector.jarfile.Gotojre/lib/extfolderandpastethejarfilehere.

2) setclasspath:
There are two ways to set the classpath:
1.temporary2.permanent

Howtosetthetemporaryclasspath
opencommandpromptandwrite:
1. C:>setclasspath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

Howtosetthepermanentclasspath

Go to environment variable then click on new tab. In variable name writeclasspath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;

JDBC-ResultSets

The SQL statements that read data from a database query, return the data in a result set. The
SELECTstatementisthestandardwaytoselect rows froma databaseandviewthemina result
set.Thejava.sql.ResultSetinterfacerepresentsthe resultset of adatabasequery.

JAVAPROGRAMMING Page90
AResultSetobjectmaintainsacursorthatpointstothecurrentrowintheresultset.Theterm "result set"
refers to the row and column data contained in a ResultSet object.

ThemethodsoftheResultSetinterfacecanbebrokendownintothreecategories−

 Navigationalmethods:Usedtomovethecursoraround.

 Getmethods: Used to view the data inthe columns of the current rowbeing pointed by the
cursor.

 Updatemethods: Usedto update the data inthe columns ofthe current row. The updates can
then be updated in the underlying database as well.

The cursoris movable based on the properties of the ResultSet.These properties are designated
when the corresponding Statement that generates the ResultSet is created.

JDBCprovidesthefollowingconnectionmethodstocreatestatementswithdesiredResultSet−

 createStatement(intRSType,intRSConcurrency);

 prepareStatement(StringSQL,intRSType,intRSConcurrency);

 prepareCall(Stringsql,intRSType,intRSConcurrency);

The firstargumentindicates the type of aResultSet objectandthe secondargumentis one of two


ResultSet constants for specifying whether a result set is read-only or updatable.

TypeofResultSet
The possible RSType are given below. Ifyou do not specifyanyResultSet type,youwill
automatically get one that is TYPE_FORWARD_ONLY.

Type Description

ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result


set.

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and backward, andthe


result set is not sensitive to changes made byothers
to the database that occur after the result set was
created.

JAVAPROGRAMMING Page91
ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forward and backward, and
the result set is sensitive to changes made by
otherstothedatabasethatoccuraftertheresultset was
created.

ConcurrencyofResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you
will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description

ResultSet.CONCUR_READ_ONLY Createsaread-onlyresultset.Thisisthedefault

ResultSet.CONCUR_UPDATABLE Createsanupdateableresultset.

ViewingaResultSet
The ResultSet interface contains dozens of methods for getting the data of the current row.

Thereisagetmethodforeachofthepossibledatatypes,andeachgetmethodhastwoversions

 Onethattakesinacolumnname.

 Onethattakesinacolumnindex.

Forexample,ifthecolumnyouareinterestedinviewingcontainsanint, youneedtouseoneof the


getInt() methods of ResultSet −

S.N. Methods&Description

1 publicintgetInt(StringcolumnName)throwsSQLException

ReturnstheintinthecurrentrowinthecolumnnamedcolumnName.

2 publicintgetInt(intcolumnIndex)throwsSQLException
Returns theintinthe currentrow inthe specifiedcolumn index.The columnindexstarts at 1,
meaning the firstcolumnof arow is 1, thesecondcolumn ofarowis2, andso on.

JAVAPROGRAMMING Page92
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types,aswell ascommontypessuchasjava.lang.String,java.lang.Object,andjava.net.URL.

There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.

For a better understanding, let us study Viewing - Example Code.

Updatinga Result Set

TheResultSetinterfacecontainsacollectionofupdatemethodsforupdatingthedataofaresult
set.

Aswiththegetmethods,therearetwoupdatemethodsforeachdatatype−

 Onethattakesinacolumnname.

 Onethattakesinacolumnindex.

JAVAPROGRAMMING Page93
Forexample,toupdateaStringcolumnofthecurrentrowofaresultset, youwoulduseoneof the
following updateString() methods −

S.N. Methods&Description

1 publicvoidupdateString(intcolumnIndex,Strings)throwsSQLException

ChangestheStringinthespecifiedcolumntothevalueofs.

2 publicvoidupdateString(StringcolumnName,Strings)throwsSQLExceptionSimilar tothe
previousmethod, except that the column is specifiedby its nameinstead of its index.

Thereareupdatemethodsfortheeightprimitivedatatypes, aswell asString, Object, URL, and the SQL


data types in the java.sql package.

Updating a row in the result set changes the columns of the current row in the ResultSet object,
but not in theunderlying database. To updateyour changes to therowin the database, you need to
invoke one of the following methods.

S.N. Methods&Description

1 publicvoidupdateRow()

Updatesthecurrentrowbyupdatingthecorrespondingrowinthedatabase.

2 publicvoiddeleteRow()
Deletesthecurrentrowfromthedatabase

3 publicvoidrefreshRow()
Refreshesthedataintheresultsettoreflectanyrecentchangesinthedatabase.

4 publicvoidcancelRowUpdates()
Cancelsanyupdatesmadeonthecurrentrow.

5 publicvoidinsertRow()
Inserts a row intothe database. This method can onlybe invokedwhen the cursor is pointing
to the insert row.

JAVAPROGRAMMING Page94
MALLAREDDY COLLEGEOF ENGINEERING

&TECHNOLOGYDEPARTMENTOFCSE(COMPUTATIONALINTEL
LIGENCE)

UNIT-5
GUIProgrammingwithjava
TheAWTClasshierarchy

JavaAWT (Abstract Window Toolkit) is anAPItodevelopGUIorwindow-


basedapplications in java.

JavaAWTcomponentsareplatform-dependenti.e.componentsaredisplayedaccording tothe view


ofoperating system.AWTisheavyweighti.e.itscomponentsareusing theresources ofOS.

The java.awtpackage provides classes forAWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

JavaAWTHierarchy

ThehierarchyofJavaAWTclassesaregivenbelow.

JAVAPROGRAMMING Page95
Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container thathave noborders andmenu bars. Youmust use frame, dialog or another
window for creating a window.

Panel

ThePanelisthecontainerthatdoesn'tcontaintitlebarandmenubars.Itcanhaveother components like


button, textfield etc.

Frame

The Frame is the container thatcontain title bar and can have menubars. It can have other components
like button, textfield etc.

UsefulMethodsofComponentclass

Method Description

publicvoidadd(Componentc) insertsacomponentonthiscomponent.

publicvoidsetSize(intwidth,intheight) setsthesize(widthandheight)ofthecomponent.

public void setLayout(LayoutManager definesthelayoutmanagerforthecomponent.


m)

publicvoidsetVisible(booleanstatus) changes the visibility of the component, bydefault


false.

JavaAWTExample

Tocreatesimpleawtexample,youneedaframe.TherearetwowaystocreateaframeinAWT.

o ByextendingFrameclass(inheritance)
o BycreatingtheobjectofFrameclass(association)

JAVAPROGRAMMING Page96
AWTExamplebyInheritance

Let'sseeasimpleexampleofAWTwhereweareinheritingFrameclass.Here,weareshowing Button
component on the Frame.

importjava.awt.*;
classFirst extendsFrame{
First(){
Button b=newButton("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//nowframewillbevisible,bydefaultnotvisible
}
publicstaticvoidmain(String args[])
{ First f=newFirst();
}}
The setBounds(int xaxis, intyaxis, intwidth, int height) method is used in the above example that
sets the position of the awt button.

JavaSwing

JavaSwingtutorial is a part of Java Foundation Classes (JFC) that is usedtocreatewindow-


basedapplications. It isbuilt on thetop of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

UnlikeAWT,JavaSwingprovidesplatform-independentandlightweightcomponents.

The javax.swing package provides classes for javaswing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

JAVAPROGRAMMING Page97
DifferencebetweenAWTandSwing.

No. JavaAWT JavaSwing

1) AWT components areplatform- Java swing components are platform-


dependent. independent.

2) AWTcomponentsareheavyweight. Swingcomponentsarelightweight.

3) AWT Swing supportspluggablelookandfeel.


doesn'tsupportpluggablelookandfeel.

4) AWT provides less components than Swing


Swing. providesmorepowerfulcomponentssuch
as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.

5) AWTdoesn'tfollowsMVC(Model View SwingfollowsMVC.


Controller) where model represents data,
view represents presentation andcontroller
acts as an interface between model and
view.

CommonlyusedMethodsofComponentclass

Method Description

publicvoidadd(Componentc) addacomponentonanothercomponent.

publicvoidsetSize(intwidth,intheight) setssizeofthecomponent.

public void setLayout(LayoutManager setsthelayoutmanagerforthecomponent.


m)

publicvoidsetVisible(booleanb) sets the visibilityof the component. It is bydefault


false.

JAVAPROGRAMMING Page98
HierarchyofJavaSwingclasses

ThehierarchyofjavaswingAPIisgivenbelow.

JavaSwingExamples

Therearetwowaystocreateaframe:

o BycreatingtheobjectofFrameclass(association)
o ByextendingFrameclass(inheritance)

Wecanwritethecodeofswinginsidethemain(),constructororanyothermethod.

SimpleJavaSwingExample

Let's see a simpleswing example whereweare creating one button and adding it on the JFrame object
inside the main() method.

File:FirstSwingExample.java

JAVAPROGRAMMING Page99
importjavax.swing.*;
publicclassFirstSwingExample{
publicstaticvoidmain(String[]args){
JFramef=newJFrame();//creatinginstance of JFrameJButton
b=newJButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}}
Containers

JavaJFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added
to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int)method.

JFrameExample

importjava.awt.FlowLayout;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.Jpanel;
publicclassJFrameExample {
publicstaticvoidmain(Strings[]){
JFrame frame = newJFrame("JFrame Example");
JPanel panel =
newJPanel();panel.setLayout(newFlowLayout());
JLabel label = newJLabel("JFrame By Example");
JButton button = newJButton();
button.setText("Button");
panel.add(label);

JAVAPROGRAMMING Page100
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
JApplet
As wepreferSwing to AWT. Now wecan use JApplet that can have all thecontrols of swing. The
JApplet class extends the Applet class.

ExampleofEventHandlinginJApplet:

importjava.applet.*;
importjavax.swing.*;
importjava.awt.event.*;
publicclassEventJApplet extendsJApplet
implementsActionListener{ JButtonb;
JTextFieldtf;publicv
oidinit()
{ tf=newJTextField()
;
tf.setBounds(30,40,150,20);
b=newJButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}}
In the above example,we have created all the controlsin init()method because it is invoked
onlyonce.

myapplet.html
1. <html>
2. <body>

JAVAPROGRAMMING Page101
3. <appletcode="EventJApplet.class"width="300"height="300">

JAVAPROGRAMMING Page102
</applet>
</body>
</html>

JDialog

The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.

UnlikeJFrame,itdoesn'thavemaximizeandminimizebuttons.

JDialogclassdeclaration

Let'sseethedeclarationforjavax.swing.JDialogclass.

1. publicclassJDialog extendsDialog implementsWindowConstants, Accessible, RootPaneContainer

CommonlyusedConstructors:

Constructor Description

JDialog() Itisusedtocreateamodelessdialogwithoutatitleand
without a specified Frame owner.

JDialog(Frameowner) It is used to create a modeless dialog with specified


Frame as its owner and an empty title.

JDialog(Frame owner, String title, Itisusedtocreateadialogwiththespecifiedtitle, owner


boolean modal) Frame and modality.

JAVAPROGRAMMING Page103
JavaJDialogExample
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
publicclassDialogExample {
privatestaticJDialog d;
DialogExample() {
JFramef=newJFrame();
d = newJDialog(f , "Dialog Example", true);
d.setLayout( newFlowLayout() );
JButton b = newJButton ("OK");
b.addActionListener ( newActionListener()
{
publicvoidactionPerformed(ActionEvente)
{
DialogExample.d.setVisible(false);
}

}); Output:

d.add( newJLabel("Click button to continue."));


d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newDialogExample();
}}

JPanel

The JPanel is asimplestcontainerclass. Itprovides space inwhich an application can attach any other
component. It inherits the JComponents class.

Itdoesn'thavetitlebar.

JAVAPROGRAMMING Page104
JPanelclassdeclaration

1.publicclassJPanelextendsJComponentimplementsAccessible

JavaJPanelExample

importjava.awt.*;
importjavax.swing.*;
publicclassPanelExample {
PanelExample()
{
JFrame f= newJFrame("Panel Example");
JPanel panel=newJPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=newJButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=newJButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1);panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newPanelExample();
}}
OverviewofsomeSwingComponentsJava

JButton

TheJButton classisusedto createalabeledbuttonthat has platformindependentimplementation. The


application result in some action when the button is pushed. It inherits AbstractButton class.

JAVAPROGRAMMING Page105
JButtonclassdeclaration
Let'sseethedeclarationforjavax.swing.JButtonclass.

1.publicclassJButtonextendsAbstractButtonimplementsAccessible

JavaJButtonExample

importjavax.swing.*;
publicclassButtonExample {
publicstaticvoidmain(String[] args) {
JFramef=newJFrame("ButtonExample");
JButton b=newJButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);}}

JavaJLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

JLabelclassdeclaration
Let'sseethedeclarationforjavax.swing.JLabelclass.

1.publicclassJLabelextendsJComponentimplementsSwingConstants,Accessible

CommonlyusedConstructors:

Constructor Description

JLabel() CreatesaJLabelinstancewithnoimageandwithan empty


string for the title.

JLabel(Strings) CreatesaJLabelinstancewiththespecifiedtext.

JLabel(Iconi) CreatesaJLabelinstancewiththespecifiedimage.

JLabel(String s, Icon i, in CreatesaJLabelinstancewiththespecifiedtext, image,


t
horizontalAlignment and horizontal alignment.
)

JAVAPROGRAMMING Page105
CommonlyusedMethods:

Methods Description

StringgetText() treturnsthetextstringthatalabeldisplays.

voidsetText(Stringtext) It defines the single line of text this component will


display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along


alignment) the X axis.

IcongetIcon() Itreturnsthegraphicimagethatthelabeldisplays.

intgetHorizontalAlignment() It returns the alignment of the label's contents along


the X axis.

JavaJLabelExample

importjavax.swing.*;
classLabelExample
{
publicstaticvoidmain(Stringargs[])
{
JFrame f= newJFrame("Label Example");
JLabel l1,l2;
l1=newJLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=newJLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

JAVAPROGRAMMING Page106
JTextField

The objectof a JTextFieldclassis a textcomponent that allows the editing of a single line text. It
inherits JTextComponent class.

JTextFieldclassdeclaration

Let'sseethedeclarationforjavax.swing.JTextFieldclass.

1.publicclassJTextFieldextendsJTextComponentimplementsSwingConstants

JavaJTextFieldExample

importjavax.swing.*;
classTextFieldExample
{
publicstaticvoidmain(Stringargs[])
{
JFrame f= newJFrame("TextField Example");
JTextField t1,t2;
t1=newJTextField("Welcome to Javatpoint.");
t1.setBounds(50,100,200,30);
t2=newJTextField("AWT Tutorial");
t2.setBounds(50,150,200,30);
f.add(t1);f.add(t2); f.setSize(400,400);
f.s etLayout(null);
f.setVisible(true);
} }
JavaJTextArea

The objectof a JTextArea class is a multi line regionthatdisplays text. Itallows the editing of
multiple line text. It inherits JTextComponent class

JTextAreaclassdeclaration
Let'sseethedeclarationforjavax.swing.JTextAreaclass.

1. publicclassJTextAreaextendsJTextComponent

JavaJTextAreaExample

JAVAPROGRAMMING Page107
importjavax.swing.*;
publicclassTextAreaExample
{
TextAreaExample(){JFrame
f= newJFrame();
JTextArea area=newJTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
publicstaticvoidmain(Stringargs[])
{
newTextAreaExample();
}}

SimpleJavaApplications

importjavax.swing.JFrame;import
javax.swing.SwingUtilities;

public class Example extends JFrame

{ public Example() {
setTitle("Simpleexample");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args)


{ Example ex = new Example();
ex.setVisible(true);
}}

JAVAPROGRAMMING Page108
LayoutManagement
JavaLayoutManagers

The LayoutManagers are usedtoarrange componentsin aparticular manner. LayoutManager is an


interface that is implemented byall the classes of layoutmanagers.

BorderLayout
TheBorderLayoutprovidesfiveconstantsforeachregion:

1. publicstaticfinalintNORTH
2. publicstaticfinalintSOUTH
3. publicstaticfinalintEAST
4. publicstaticfinalintWEST
5. publicstaticfinalintCENTER

ConstructorsofBorderLayoutclass:
o BorderLayout():createsaborderlayoutbutwithnogapsbetweenthecomponents.
o JBorderLayout(inthgap,intvgap): creates a border layout with the given horizontal
andvertical gaps between the components.

ExampleofBorderLayoutclass:
importjava.awt.*; Output:
importjavax.swing.*;
publicclassBorder
{
JFramef;
Border()
{
f=newJFrame();
JButton b1=newJButton("NORTH");;
JButton b2=newJButton("SOUTH");;
JButton b3=newJButton("EAST");;
JButton b4=newJButton("WEST");;
JButton b5=newJButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
etVisible(true);
}
publicstaticvoidmain(String[]args)
{
newBorder();
}}

JAVAPROGRAMMING Page109
JavaGridLayout
The GridLayout is usedto arrange the componentsin rectangular grid. One component is
displayed in each rectangle.

ConstructorsofGridLayoutclass
1. GridLayout():createsagridlayoutwithonecolumnpercomponentinarow.
2. GridLayout(introws,intcolumns): creates a grid layout with thegiven rowsand
columns but no gaps between the components.
3. GridLayout(introws,intcolumns,inthgap,intvgap): creates a grid layout with the given
rows and columns alongwith given horizontal and vertical gaps.

ExampleofGridLayoutclass
1. importjava.awt.*;
2. importjavax.swing.*;
publicclassMyGridLayout{ J
Frame f;
MyGridLayout(){
f=newJFrame();
JButton b1=newJButton("1");
JButton b2=newJButton("2");
JButton b3=newJButton("3");
JButton b4=newJButton("4");
JButton b5=newJButton("5");
JButton b6=newJButton("6");
JButton b7=newJButton("7");
JButton b8=newJButton("8");
JButton b9=newJButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(newGridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
etVisible(true);
}
publicstaticvoidmain(String[]args){
newMyGridLayout();}}
JavaFlowLayout

The FlowLayoutis usedto arrange the components ina line,one after another (in a flow).Itis the
default layout of applet or panel.

FieldsofFlowLayoutclass
1. publicstaticfinalintLEFT
2. publicstaticfinalintRIGHT
3. publicstaticfinalintCENTER
4. publicstaticfinalintLEADING
5. publicstaticfinalintTRAILING

JAVAPROGRAMMING Page110
ConstructorsofFlowLayoutclass
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(intalign): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(intalign,inthgap,intvgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

ExampleofFlowLayoutclass
importjava.awt.*;
importjavax.swing.*;publicc
lassMyFlowLayout{ JFrame
f;
MyFlowLayout(){
f=newJFrame();
JButton b1=newJButton("1");
JButton b2=newJButton("2");
JButton b3=newJButton("3");
JButton b4=newJButton("4");
JButton b5=newJButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(newFlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
etVisible(true);
}
publicstaticvoidmain(String[]args){
newMyFlowLayout();
}}
EventHandling
EventandListener(JavaEventHandling)
Changing the state of an object is known as an event. For example, click on button, draggingmouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event
handling.

Typesof Event

Theeventscanbebroadlyclassifiedintotwocategories:

 ForegroundEvents - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components
inGraphicalUserInterface.Forexample,clickingonabutton,movingthemouse,entering a
characterthrough keyboard,selecting an item fromlist, scrolling the page etc.

 BackgroundEvents-Thoseeventsthatrequiretheinteractionofenduserareknownas

JAVAPROGRAMMING Page111
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are theexample of background events.

EventHandling

Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
definesthestandardmechanismtogenerateandhandletheevents.Let'shaveabriefintroduction to this
model.

TheDelegationEventModelhasthefollowingkeyparticipantsnamely:

 Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with classes
for source object.

 Listener - It is also known as event handler. Listener is responsible for generating


response to an event. From java implementation point of view the listener is also an
object. Listener waits until it receives an event. Once the event is received , the listener
process the event an then returns.

EventclassesandListenerinterfaces:
EventClasses ListenerInterfaces

ActionEvent ActionListener

MouseEvent MouseListenerandMouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

JAVAPROGRAMMING Page112
StepstoperformEventHandling

Followingstepsarerequiredtoperformeventhandling:

1. ImplementtheListenerinterfaceandoverridesitsmethods
2. RegisterthecomponentwiththeListener

For registering the component with the Listener, many classes provide the registration
methods.For example:

o Button
o publicvoidaddActionListener(ActionListenera){}
o MenuItem
o publicvoidaddActionListener(ActionListenera){}

o TextField
o publicvoidaddActionListener(ActionListenera){}
o publicvoidaddTextListener(TextListenera){}
o TextArea
o publicvoidaddTextListener(TextListenera){}

o Checkbox
o publicvoidaddItemListener(ItemListenera){}

o Choice
o publicvoidaddItemListener(ItemListenera){}
o List
o publicvoidaddActionListener(ActionListenera){}
o publicvoidaddItemListener(ItemListenera){}

EventHandlingCodes:
Wecanputtheeventhandlingcodeintooneofthefollowingplaces:
1. Sameclass
2. Otherclass
3. Annonymousclass

Exampleofeventhandlingwithinclass:
importjava.awt.*;
importjava.awt.event.*;
classAEvent extendsFrame implementsActionListener{ TextField
tf;

JAVAPROGRAMMING Page113
AEvent(){
tf=newTextField();
tf.setBounds(60,50,170,20);Button
b=newButton("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}
publicstaticvoidmain(Stringargs[]){
newAEvent();
}}
publicvoidsetBounds(intxaxis,intyaxis,intwidth,intheight); have been used in theabove
example thatsetsthe position of thecomponentitmay be button, textfieldetc.

JavaeventhandlingbyimplementingActionListener
importjava.awt.*;
importjava.awt.event.*;
classAEvent extendsFrame implementsActionListener{ TextField
tf;
AEvent(){
//
createcomponentstf=newTe
xtField();
tf.setBounds(60,50,170,20);
Buttonb=newButton("click me");
b.setBounds(100,120,80,30);
//registerlistenerb.addActionListener(this);//passing
currentinstance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
publicvoidactionPerformed(ActionEvente){
tf.setText("Welcome");
}
publicstaticvoidmain(Stringargs[]){
}}

JAVAPROGRAMMING Page114
newAEvent();

}}

JAVAPROGRAMMING Page115
JavaMouseListenerInterface

The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent.TheMouseListenerinterfaceisfoundinjava.awt.eventpackage.Ithasfive methods.

MethodsofMouseListenerinterface

Thesignatureof5methodsfoundinMouseListenerinterfacearegivenbelow:

1. publicabstractvoidmouseClicked(MouseEvente);
2. publicabstractvoidmouseEntered(MouseEvente);
3. publicabstractvoidmouseExited(MouseEvente);
4. publicabstractvoidmousePressed(MouseEvente);
5. publicabstractvoidmouseReleased(MouseEvente);

JavaMouseListenerExample
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener{ Labell;
MouseListenerExample()
{ addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{ l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{ l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{ l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{ l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{ l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();

}}

JAVAPROGRAMMING Page116
JavaKeyListenerInterface
The Java KeyListener is notified wheneveryou change the state of key.It is notified against
KeyEvent.TheKeyListenerinterfaceisfoundinjava.awt.eventpackage.Ithas three methods.

MethodsofKeyListenerinterface
Thesignatureof3methodsfoundinKeyListenerinterfacearegivenbelow:

1. publicabstractvoidkeyPressed(KeyEvente);
2. publicabstractvoidkeyReleased(KeyEvente);
3. publicabstractvoidkeyTyped(KeyEvente);

JavaKeyListenerExample
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener{ Labell;
TextArea area;
KeyListenerExample(){
l=newLabel();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);setLayout(null)
;setVisible(true);
}
public void keyPressed(KeyEvent e)
{ l.setText("KeyPressed");
}
public void keyReleased(KeyEvent e)
{ l.setText("KeyReleased");
}
public void keyTyped(KeyEvent e)
{ l.setText("KeyTyped");
}
public static void main(String[] args) {
new KeyListenerExample(); } }
JavaAdapterClasses

Java adapter classes providethedefaultimplementationoflistenerinterfaces. If you inherit theadapter


class, you will not be forced to provide the implementation of all the methods of listener interfaces. So
it savescode.

JAVAPROGRAMMING Page117
java.awt.eventAdapterclasses

Adapterclass Listenerinterface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

JavaWindowAdapterExample

1. importjava.awt.*;
importjava.awt.event.*;
publicclassAdapterExample{
Framef;AdapterExample(){
f=newFrame("Window Adapter");
f.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvent e) {
f.dispose(); } });
etSize(4
00,400);
f.setLayout(
null);
f.setVisible(
true);
}
publicstaticvoidmain(String[]args){

JAVAPROGRAMMING Page118
newAdapterExample();
}}

JAVAPROGRAMMING Page119
Applets

Appletisa special type of program that is embeddedin the webpage to generate the dynamic content.
It runs inside the browser and works at client side.

AdvantageofApplet

Therearemany advantagesofapplet.Theyareasfollows:

o Itworksatclientsidesolessresponsetime.
o Secured
o It can be executed bybrowsers running under many plateforms, including Linux,
Windows, Mac Os etc.

DrawbackofApplet
o Pluginisrequiredatclientbrowsertoexecuteapplet.

LifecycleofJavaApplet HierarchyofApplet
1. Appletisinitialized.
2. Appletisstarted.
3. Appletispainted.
4. Appletisstopped.
5. Appletisdestroyed.

LifecyclemethodsforApplet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Appletclass

Forcreating anyappletjava.applet.Appletclass mustbeinherited.It provides4lifecyclemethods of applet.

1. publicvoidinit():isusedtoinitializedtheApplet.Itisinvokedonlyonce.

2. publicvoidstart(): is invoked aftertheinit()method or browseris maximized.Itisused to start


the Applet.
3. publicvoidstop(): is used tostop the Applet. It is invokedwhen Applet isstop or
browser is minimized.
4. publicvoiddestroy():isusedtodestroytheApplet.Itisinvokedonlyonce.

JAVAPROGRAMMING Page120
java.awt.Componentclass

TheComponentclassprovides1lifecyclemethodofapplet.

1. publicvoidpaint(Graphicsg): is usedto paint the Applet. It provides Graphics class


object that can be used for drawing oval, rectangle,arc etc.

SimpleexampleofAppletbyhtmlfile:

To execute the applet byhtml file, create an applet and compileit. Afterthat create an html file and
place the applet code in html file. Now click the html file.

1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirst extendsApplet{
publicvoidpaint(Graphics g){
g.drawString("welcome",150,150);
}
}

SimpleexampleofAppletbyappletviewertool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
andcompileit.Afterthat runit by:appletviewerFirst.java.NowHtmlfileis not requiredbutitis for
testing purpose only.

1.//First.java
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassFirstextendsApplet{
publicvoidpaint(Graphics g)
{ g.drawString("welcometoapplet",150,150);
}
}
/*
<appletcode="First.class"width="300"height="300">
</applet>
*/

JAVAPROGRAMMING Page120
Toexecutetheappletbyappletviewertool,writeincommandprompt:

c:\>javacFirst.java
c:\>appletviewerFirst.java

DifferencebetweenAppletandApplicationprogramming

JAVAPROGRAMMING Page120
ParameterinApplet

WecangetanyinformationfromtheHTMLfileasaparameter.Forthispurpose,Appletclass provides a
method named getParameter(). Syntax:

publicStringgetParameter(StringparameterName)

ExampleofusingparameterinApplet:
importjava.applet.Applet;
importjava.awt.Graphics;
publicclassUseParam extendsApplet
{
publicvoidpaint(Graphicsg)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<appletcode="UseParam.class"width="300"height="300">
<paramname="msg"value="Welcometoapplet">
</applet>
</body>
</html>

JAVAPROGRAMMING Page121

You might also like