8
Introduction To JAVA
Unit # 2 : Introduction to Java
What is Java?
History Of Java
Java Features
Java Installation
First Java Application
Types of Java Applications
Java Editions
Java Software Components
Interview Questions
9
Introduction To JAVA
What is JAVA?
Javaissimple,highperformance,object-oriented,robust,
secure,multi-threaded,andplatformindependentprogramming
languagetodevelopsoftwarethatcanbeusedforgaming,web,
business,desktop,database,andotherapplications.
DesigngoalofJavalanguageproject
Writeonce,runanywhere(WORA)–thatmeansjava
programcanrunanywhereandonanyplatform.Whenjavacodeis
compileditisconvertedintobytecode.Nowthisbytecodeis
neededtorunusingJVM,noneedofsourcecodeand
recompilation.
10
Introduction To JAVA
History Of Java
1.JAVAwasdevelopedbyJamesGoslingandPatrick
NaughtonfromSunMicrosystemsIncin1991,
later(2010)acquiredbyOracleCorporation.
2.ThedesigngoalofJavaisWORA(WriteOnce
Run/ExecuteAnywhere)itmeanswriteaprogramonce
andthenrunthisprogramonmultipleoperatingsystems.
3.ThefirstpubliclyavailableversionofJava(Java1.0)
wasreleasedin1995andthecurrentofversionofJavais
JavaSE11releasedonSeptember,25th2018
11
Introduction To JAVA
Features of JAVA?
12
Introduction To JAVA
Important Features Of Java
Simple
1)Itdoesnotuseheaderfiles.
2)Eliminatedtheuseofpointerandoperator
overloading.
3)Javaiseasytolearnandfamiliarbecausejava
syntaxisjustlikec++.
4)ThereisaprovisionofAutomaticGarbage
Collection,inwhichthereisnoneedtoremove
theunreferencedobjectsexplicitly.
Introduction To JAVA
Compiled and Interpreted
Usually,acomputerlanguagecanbeeithercompiledorinterpreted.
JavaintegratesthepowerofCompiledLanguageswiththe
flexibilityofInterpretedLanguages.
Javacompiler(javac)compilesthejavasourcecodeintothe
bytecode.
JavaVirtualMachine(JVM)thenexecutesthisbytecodewhichis
executableonmanyoperatingsystemsandisportable.
13
27
Introduction To JAVA
Just In Time Compiler (JIT)
JITisamoduleinsidetheJVMwhichhelpsin
compilingcertainpartsofbytecodeintothe
machinecodeforhigherperformance.
28
Introduction To JAVA
29
Introduction To JAVA
Editions Of Java Software
JavaSE (Java Standard/Software Edition)
JavaSEismainlyusedtocreateapplicationsfor
Desktopenvironment.
ItconsistallthebasicsofJavathelanguage,
variables,primitivedatatypes,Arrays,Streams,
StringsJavaDatabaseConnectivity(JDBC)and
muchmore.
33
First Java Application
Steps To Write First Java Program
Step 1:Decalre the class
Every java application must have at least one class
definition that consists of class keyword followed
by class name.
public class FirstJavaProgram
{
}
34
First Java Application
Step 2: Declare the main() method
ToexecutetheaboveclassJVMneedoneentrypointin
theclassthatentrypointismain()methodhaving
signatureasshownbelow
publicstaticvoidmain(String[]args){}
38
First Java Application
Step 4:Save The File
Weshouldalwayssavethefilesameasthepublic
classname.
Inourprogram,thepublicclassnameis
FirstJavaProgram,that’swhyourfilenameshould
beFirstJavaProgram.java.
39
First Java Application
Step 5: Compile The Program
Wewillcompiletheprogram.Forthis,open
commandprompt(cmd)onWindowstypethe
followingcommandandhitenter.
javacFirstJavaProgram.java
Stpe6:ExecuteTheProgram
Aftercompilationthe.javafilegetstranslatedintothe
.classfile(bytecode).Nowwecanruntheprogram.To
runtheprogram,typethefollowingcommandandhit
enter:javaFirstJavaProgram
40
First JAVA Application
Java Compilation And Execution
1)IntheJavaprogramminglanguage,allsource
codeisfirstwrittenandsavewith
the.javaextension.
2)Aftercompilation,.classfilesaregenerated
byjavaccompiler.
3)A.classfilecontainbytecodethatisnot
naturaltoyourprocessor,thisbytecodeconvert
intoprocessorunderstandablecodebyJVM
41
First JAVA Application
Java Compilation and Execution
Naming Conventions in Java
Naming Conventions In Java
Identifiers
A name in the program is an identifier it may be class
name or method name, variable name or label name.
Example
Class Test{
public static void main(String[] args){
int x=10
System.out.println(x);
}
43
Naming Conventions In Java
Rules for defining Identifiers
1)Identifiersmuststartwithaletter,acurrencycharacter($),ora
connectingcharactersuchastheunderscore(_).
2)Identifierscannotstartwithanumber
3)Afterthefirstcharacter,identifierscancontainanycombination
ofletters,currencycharacters,connectingcharacters,or
numbers.
4)Inpractice,thereisnolimittothenumberofcharactersan
identifiercancontain.
5)Youcan'tuseaJavakeywordasanidentifier.
6)IdentifiersinJavaarecase-sensitive;fooandFOOaretwo
differentidentifiers.
44
Naming Conventions In Java
Coding standards for classes
Usuallyclassnameshouldbenoun.Shouldstartswith
uppercaseletterandifitcontainmultiplewordsevery
innerwordsalsoshouldstartwithcapitalletters.
Example:
String
StringBuffer
NumberFormat
CustomerInformation
45
Naming Conventions In Java
Coding standards for Interfaces
Usuallyinterfacenamedshouldbeadjective,startswith
capitallettersandifitcontainsmultiplewords,every
innerwordalsoshouldstartswithcapitalletter.
Example:
Runnable
Serializable
Clonable
Movable
Transferable
Workable
46
Naming Conventions In Java
Coding standards with methods
Valuesshouldbeeitherverbsorverb+noun
combination.
Startswithlowercaseandeveryinnerwordsstartswith
uppercase(thisconventionisalsocalledcamelcase
convention).
Example:
getName(), getMessage(), toString(), show(), display().
47
Naming Conventions In Java
Coding standards for variables
Usuallythevariablestartswithnounandeveryinner
wordshouldstartwithuppercasei.ecamelcase
convention.
Example:
name, rollNo, bandwidth, totalNumber.
48
Data types in Java
Datatype
Incomputerscience,adatatypeisanattributeofdatathattellsthe
compilerorinterpreterhowtheprogrammeraimstousethedata.
JavaDataTypes
1)PrimitiveDataTypes
2)Non-PrimitiveDataTypes
PrimitiveDataTypes
Asthenamesuggests,theprogramminglanguagepre-definesthe
primitivedatatypes.Primitivetypesarethemostbasicdatatypes
availableinJava.
Thereare8primitivedatatypesinJava:byte,char,short,int,long,
float,doubleandboolean.
Primitivedatatypeshaveaconstraintthattheycanholddataofthe
sametypeandhaveafixedsize.
51
Data types in Java
52
Data types in Java
Non-Primitive Data Types/ Referenced Data Types
1)Thetermnon-primitivedatatypemeansthatthese
typescontain“amemoryaddressofthevariable”.
2)Incontrasttoprimitivedatatypes,whicharedefinedby
Java,non-primitivedatatypesarenotdefinedorcreated
byJavabuttheyarecreatedbytheprogrammers.They
arealsocalledReferencedatatypesbecausethey
cannotstorethevalueofavariabledirectlyinmemory.
3)Non-primitivedatatypesdonotstorethevalueitself
buttheystoreareferenceoraddress(memorylocation)
ofthatvalue.
53
Data types in Java
Java Integers
It can hold whole numbers such as 196, -52, 4036 etc. Java supports four
different types of integers These are:
54
Data types in Java
55
Data types in Java
56
Floating Point Numbers
Floating Representation
57
Single precision floating point number
Singleprecisionuses32bittorepresentafloatingpointnumber.
Firstbitrepresentthesignofthenumber,negativeorpositive.
Next8bitsareusedtostoretheexponentofthenumber.This
exponentcanbesigned8-bitintegerrangingfrom-127–128of
signedinteger(0to255).
Andtheleft23bitsareusedtorepresentthefractionpartandare
calledfractionbits.
8exponentbitsprovideuswiththerangeand23bitsprovideus
withtheactualprecision.
58
Double precision floating point number
Doubleprecisionuses64bitstorepresentavalue.
Firstbitisusedforthesamepurposeasinsinglepointprecision
i.e.,representssignofthenumber.
Next11bitsareusedtodenoteexponent,whichprovideuswith
therange,andhas3morebitsthansingleprecision,soitisused
torepresentawiderrangeofvalues.
Next52bitsareusedtorepresentthefractionalpartwhichis29
bitsmorethanbinary32bitrepresentationscheme.Soithasa
greaterprecisionthansingleprecision.
59
Data types in Java
60
Floating-Point Literals in Java
Here,datatypescanonlybespecifiedindecimalformsandnot
inoctalorhexadecimalform.
Data types in Java
Java Characters
Acharacterisusedtostorea‘single’character.Asinglequote
mustsurroundacharacter.ThevalidCharactertypeischar.In
Java,acharacterisnotan8-bitquantitybutherecharacteris
representedbya16-bitUnicode.
61
Syntax char myChar= ’A’ ;
Size 2 bytes(16 bits)
Values A single character representing a digit, letter,
or symbol.
Default Value ‘\u0000’ (0)
Range \u0000’ (0) to ‘\uffff’ (65535)
Data types in Java
Char Literals in Java
These are the four types of char
Single Quote
JavaLiteralcanbespecifiedtoachardatatypeasasingle
characterwithinasinglequote.
charch='a';
Char as Integral
A char literal in Java can specify as integral literal which also
represents the Unicode value of a character.
Furthermore, an integer can specify in decimal, octal and even
hexadecimal type, but the range is 0-65535.
char ch = 062;
62
Data Types in Java
Unicode Representation
Char literals can specify in Unicode representation ‘\uxxxx’. Here
XXXX represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
Escape Sequence
Escape sequences can also specify as char literal.
63
Data types in Java
boolean
•booleandatatyperepresentsonebitofinformationas
eithertrueorfalse.i.e.thereisonlytwopossiblevalue
trueorfalse.Internally,JVMusesonebitofstorageto
representabooleanvalue.
•Itisgenerallyusedtotestaparticularconditional
statementduringtheexecutionofprogram.
•booleandatatypetakeszerobytesofmemory.
•Defaultvalueisfalse.
For example:
boolean b = false;
64
Variables in Java
Initialization of a Variable
Syntax:
variableName = value ;
Example:
payRate = 2500;
Combining the declaration and initialization, we can
write
dataType variableName = value ;
Example:
double area = 378.87 ;
66
Type Promotion in Java
Type Promotion in Java
ThereareseveraltypepromotionrulesinJavathatare
followedwhileevaluatingexpressions-
1)Allbyte,shortandcharvaluesarepromotedtoint.
2)Ifanyoperandislongthentheexpressionresultislong.
i.e.wholeexpressionispromotedtolong.
3)Ifanyoperandisafloatthentheexpressionresultis
float.i.e.wholeexpressionisautomaticallypromotedto
float.
4)Ifanyoperandisadoublethentheexpressionresultis
double.i.e.wholeexpressionispromotedtodoublein
Java.
69
Type Promotion in Java
When one of the operand is double.
int i = 30;
double d = 2.5;
double result = i * d;
When one of the operand is float.
short s = 4;
int i = 30;
float f = 6.75f;
float result = (s+i) * f;
70
Type Casting in Java
Type Casting in Java
What is Type Casting or Type Conversion
TypeConversionorTypeCastingistheprocessof
convertingavariableofonepredefinedtypeintoanother.
Ifthesedatatypesarecompatiblewitheachother,the
compilerautomaticallyconvertsthemandiftheyarenot
compatible,thentheprogrammerneedstotypecastthem
explicitly.
72
Type Casting in Java
Types of Type Conversion
1)Implicit Type Conversion
2)Explicit Type Conversion
73
Type Casting in Java
Implicit Type Conversion
ImplicitTypeConversionorAutomatictypeconversionisaprocess
ofautomaticconversionofonedatatypetoanotherbythecompiler.
ThisprocessisalsocalledWideningConversionbecausethecompiler
convertsthevalueofnarrower(smallersize)datatypeintoavalueof
abroader(largersize)datatypewithoutlossofinformation.
Theimplicitdatatypeconversionispossibleonlywhen
1)Thetwodatatypesarecompatiblewitheachother.
2)Thereisaneedtoconvertasmallerornarrowerdatatypetothe
largertypesize.
Forexample,thecompilerautomaticallyconvertsbytetoshort
becausethebyteissmaller(8bits)ornarrowerthanshort(16bits).
74
Type Casting in Java
75
Type Casting in Java
Explicit Type Conversion
TheExplicitTypeConversionisaprocessofexplicitly
convertingatypetoaspecifictype.Wealsocallit
NarrowingConversion.Thetypecastingisdonemanually
bytheprogrammer,andnotbythecompiler.Weneedto
doexplicitornarrowingtypeconversionwhenthevalue
ofabroader(highersize)datatypeneedstobeconverted
toavalueofanarrower(lowersize)datatype.
Forexample,doubledatatypeexplicitlyconvertedinto
inttype.
76
Type Casting in Java
ThefollowingisthesyntaxoftypecastinginJava
(type)expression;
Wheretypeisavaliddatatypetowhichtheconversionis
tobedone.
Forexample,ifwewanttomakesurethattheexpression
(x/y+5)evaluatestotypefloat,wewillwriteitas,
(float)(x/y+5);
77
Type Casting in Java
78
Type Casting in Java
79
Operators In Java
Operators in Java
Incomputerprogramming,anoperatorisaspecial
symbolthatisusedtoperformoperationsonthevariables
andvalues.
Theoperatorsrepresenttheoperations(specifictasks)
andtheobjects/variablesoftheoperationsareknownas
operands.
81
Operators in Java
The Bitwise AND Operator (&)
The bitwise AND operator, &, produces a 1 bit if both the
operands are also 1. A zero is produced in all the other
cases.
Example
00101010 42
&00001111 15
_________
00001010 10
94
Operators in Java
The Bitwise OR Operator
ThebitwiseORoperator,|,combinesbitssuchthatif
eitherofthebitsintheoperandsis1,thentheresultant
bitis1.
Example
00101010 42
|00001111 15
_________
00101111 47
95
Operators in Java
The Bitwise XOR Operator
ThebitwiseXORoperator,^,combinesbitssuchthatif
exactlyoneoperandis1,thentheresultis1.Otherwise,
theresultiszero.
Example
00101010 42
^00001111 15
_________
00100101 37
96
Control Statements in Java
Control Statements in Java
Thestatementsthosewhocontroltheorderofexecutionofa
programareknownascontrolstatements
Typesofcontrolstatements
1)Selection/DecisionmakingStatements
Usingthesestatements,apieceofcodewouldbeexecuted
onlyifacertaincondition(s)istrue.
2)Iterationstatements
Usingthesestatementstoiterateablockofcoderepeatedly
untiltheconditionisfalse
3)Jumpstatements
Usingthesestatementstoskipthestatementsandcome-out
fromthose.
100
Control Statements in Java
101
Control Statements in Java
The if-else control statement
Theif-elsestatementisusedtochoose&executeanyoneactionamongtwo.
Syntax
if(condition){
//groupofprogrammingstatements
}
else{
//groupofprogrammingstatements
}
Bracesintheif-elseandothercontrolstatementsareoptionalifweusedonlyone
statementforeveryaction
Iftheconditionpresentinsidetheparenthesesistrue,if-blockisexecuted.After
executionofif-block,programcontrolskipselse-blockandjumpsdirectlyto
thestatementsafterelse-block.
Iftheconditioninsidetheparenthesisisfalse,else-blockisexecutedbyskipping
if-block
102
Control Statements in Java
103
Control Statements in Java
if statement (if without else statement)
Itispossibletouseifstatementwithouttheelsestatement.
Syntax
if(condition){
//groupof
//programming
//statements
}
Iftheconditioninsideparenthesesistrue,if-blockisexecuted.
Afterexecutionofif-block,programcontrolexecutesstatements
afterit.
Iftheconditioninsidetheparenthesisisfalse,if-blockisskipped,
andstatementsafteritareexecuted.
104
Control Statements in Java
105
Control Statements in Java
Nested if statement
InJavaprogramming,itispossibletoplaceifcontrolstatementinsideanotherif-blockor
else-block.
if(condition1){//outerif-block
if(condition2){
block1
}
}
else{//outerelse-block
if(condition3){
block2
}
}
Intheaboveexample,ifcondition1becomestrue,programcontrolentersintoouterif-block.
Thenitchecksforcondition2.Ifcondition2istrue,block1isexecuted.
Afterexecutionofblock1,controlistransferreddirectlytothestatementaftertheouterelse-
block.
Ifcondition1becomesfalse,programcontrolentersintoouterelse-blockskippingouterif-
block.Thenitchecksforcondition3.Ifcondition3istrue,block2isexecuted.After
executionofblock2andouterelse-blockcontrolistransferreddirectlytostatementafter
it.
106
Control Statements in Java
107
Control Statements in Java
108
Program to find bigger number among three given number
if(a>b){//’a’ is bigger
if(a>c)//’a’ is already bigger than ‘b’ so the comparison with ‘c’ only
‘a’ is bigger
else
‘c’ is bigger
}//outer if
else{
if(b>c)//compare to ‘a’ ‘b’ is bigger control comes to here.
Comparison with ‘c’ only
‘b’ is bigger
else
‘c’ is bigger
}
a=12, b=14, c=11
Control Statements in Java
109
Program to find out the given year is leap year or not?
Logic: A centennial (divisible by 100) year is leap if it is divisible by
400, and a non-centennial year is leap if it is divisible by 4.
if(year %100!=0){
if(year%4==0)
leap year
else
not a leap year
}
else{
if(year%400==0)
leap year
else
not a leap year
}
Solutionwith if-else
--------------------------
if(year%100!=0 && year %4==0 || year%400==0)
leap year
else
not a leap year
Control Statements in Java
110
Given3intvalues,abc,returntheirsum.However,ifoneofthevalues
is13thenitdoesnotcounttowardsthesumandvaluestoitsrightdonot
count.Soforexample,ifbis13,thenbothbandcdonotcount.
publicintluckySum(inta,intb,intc){
}
Forexample,
luckySum(1,2,3)→6
luckySum(1,2,13)→3
luckySum(1,13,3)→1
luckySum(13,5,3)→0
Control Statements in Java
111
luckySum solution
public int luckySum(int a, int b, int c) {
if (a == 13)
return 0;
else if (b == 13)
return a;
else if (c == 13)
return a + b;
else
return a + b +c;
}
Control Statements in Java
112
Whenbachelor'sgettogetherforaparty,theyliketohavebeers.A
bachelorpartyissuccessfulwhenthenumberofbeersisbetween40and
60,inclusive.Unlessitistheweekend,inwhichcasethereisnoupper
boundonthenumberofbeers.Returntrueifthepartywiththegiven
valuesissuccessful,orfalseotherwise.
publicbooleanbeerParty(intbeers,booleanisWeekend){
}
beerParty(30,false)→false
beerParty(50,false)→true
beerParty(70,true)→true
beerParty(30,true)→false
Control Statements in Java
113
beerParty solution
public boolean beerParty(int beers, boolean isWeekend) {
if (isWeekend == true && beers >= 40)
return true;
if (!(isWeekend) && beers >=40 && beers<= 60)
return true;
else
return false;
}
Control Statements in Java
114
Wearehavingapartywithamountsofteaandcandy.Returntheint
outcomeofthepartyencodedas0=bad,1=good,or2=great.Apartyis
good(1)ifbothteaandcandyareatleast5rating.However,ifeithertea
orcandyisatleastdoubletheamountoftheotherone,thepartyisgreat
(2).However,inallcases,ifeitherteaorcandyislessthan5rating,the
partyisalwaysbad(0).
publicintteaParty(inttea,intcandy){
}
teaParty(6,8)→1
teaParty(3,8)→0
teaParty(20,6)→2
Control Statements in Java
115
teaParty solution
public int teaParty(int tea, int candy) {
if (tea < 5 || candy < 5)
return 0;
if ((tea >= 2 * candy) || (candy >= 2 * tea))
return 2;
else
return 1;
}
Control Statements in Java
The if-else-if ladder statement
The if-else-if ladder is a very common programming constructs in Java, which is
also called the if-else-if staircase because of its appearance. We can use many
if-else-if statements in our program.
The general form or syntax of the if-else-if ladder statement is:
if( expression1)
statement1 ;
else if(expression2)
statement2;
.
.
else
statement3;
116
Control Statements in Java
117
Control Statements in Java
The switch statement
In Java programming, the switch statement is used to make a specific selection from
multiple cases.
Syntax
switch(expression){
case constant_value_1 :
statements to be executed;
break;
case constant_value_2 :
statements to be executed;
break;
case constant_value_N :
statements to be executed;
break;
case default :
statements to be executed;
}
118
Control Statements in Java
1)Inaswitchstatement,theexpressioninsideswitch’s
left&rightparenthesisisexecutedfirst.
2)Ifanycasematchestheexpressionvalue,program
controljumpsdirectlytothatcaseandstatementsof
thatcaseareexecuted.
3)Ifexpressionvaluedoesnotmatchwithanycase,then
programcontroljumpsdirectlytothedefaultcaseand
statementsofdefaultcaseareexecuted.
119
Control Statements in Java
120
Control Statements in Java
121
Control Statements in Java
The for loop
Syntax
for(initialization;condition;update){
// programming
// statements
}
Theforloopconsistsofthreeexpressionscalled
initialization,condition&updateanditsbody
(statementsinsidecurlybraces).
122
Control Statements in Java
123
Control Statements in Java
The while loop
Sameasforloop,whileloopisusedtoexecutespecific
partoftheprogramrepeatedly.
Syntax
while(condition){
// programming
// statements
}
124
Control Statements in Java
125
Control Statements in Java
The do-while loop
Sameasforloopandwhileloop,do-whileloopisalso
usedtoexecutespecificpartoftheprogramrepeatedly.
Theonlydifferenceisthatthebodyofdo-whileloopis
executedatleastonceeveniftheconditionisfalse.
Syntax
do{
// programming
// statements
}while(condition);
126
Control Statements in Java
127
Control Statements in Java
The break statement
Thestatementthatisusedtobreak/stoptheflowofloops&switch
statementisknownasbreakstatement.
Insidetheloop,breakstatementterminatestheloopexecution
whenitisencountered.
Insideswitchstatement,breakstatementisusedtojumpoutofthe
switchstatementinstantlywhenitisencountered.
Syntax
break;
JavaProgrammingLanguagebreakStatementWorkinginfor,
whileanddo-whileloops
Afterterminatingaloopbyusingthebreakstatement,program
controlistransferredimmediatelytothestatementaftertheloop.
128
Control Statements in Java
129
Control Statements in Java
The continue statement
Thecontinuestatementforceslooptoskipstatements
writtenafterit&continuenextexecutionoftheloop.
Syntax
continue;
Note
Ifthecontinuestatementisencounteredintheforloop,
programcontroljumpsdirectlytotheupdate
expression.
Ifthecontinuestatementisencounteredinthewhile&
do-whileloops,programcontroljumpsdirectlytothe
condition.
130
Arrays In Java
Features of an Array
1)Arrayisanobjectsowecanfindthelengthofthearray
usingattribute'length'.
2)Arrayisanorderedandeachhaveanindexbeginning
from'0'forthefirstelement.
3)Arrayscanstoreprimitivesaswellasobjects.Butall
mustbeofasingletypeinonearrayinstance.
4)Justlikeothervariablessocanusedasmethod
arguments.
5)Thesizeofanarraymustbespecifiedbyanintvalue.
135
Arrays In Java
136
Arrays In Java
Array Declaration
Thedeclarationofarraystatesthetypeoftheelementthat
thearrayholdsfollowedbythesquarebracesand
identifierwhichindicatestheidentifierisarraytype.
Example
Declaringanarraywhichholdselementsofintegertype.
137
Arrays In Java
Different way of declaring an array
138
Arrays In Java
Note
139
Arrays In Java
140
Arrays In Java
Note
141
Arrays In Java
142
Arrays In Java
Initialization of an array
143
Arrays In Java
144
Arrays In Java
145
Arrays In Java
146
Arrays In Java
Accessing elements from an array by using index value
Afterthearrayiscreated,itselementscanbeaccessedby
theirindex.Theindexisanumberplacedinsidesquare
bracketswhichfollowthearrayname.
Example,
String[]names={"Jane","Thomas","Lucy","David"};
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
System.out.println(names[3]);
147
Arrays In Java
Accessing elements from an array by using for each
loop
J2SE5introducesspecialtypeofforloopcalledforeach
looptoaccesselementsofarray.Usingforeachloopyou
canaccesscompletearraysequentiallywithoutusing
indexofarray.
Example,
int[] arr = {10, 20, 30, 40};
for(int x : arr){
System.out.println(x);
}
148
Arrays In Java
Accessing elements from an array by using basic for
loop
Example,
String[] planets = { "Mercury", "Venus", "Mars", "Earth",
"Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" };
for (int i=0; i < planets.length; i++) {
System.out.println(planets[i]);
}
149
Arrays In Java
Anonymous arrays
Youcancreateanarraywithoutspecifyinganyname
sucharraysareknownasanonymousarrays.Sinceit
doesn’thavenametoreferyoucanuseitonlyoncein
yourprogram.Generally,anonymousarraysarepassedas
argumentstomethods.
You can create an anonymous array by initializing it at
the time of creation.
For example,
new int[] { 1254, 5452, 5743, 9984}; //int array
new String[] {"Java", "JavaFX", "Hadoop"}; //String
array
150
Arrays In Java
Example,
Two dimensional array:
int[][] twoDarr = new int[10][20];
Three dimensional array:
int[][][] threeDarr = new int[10][20][30];
Thetotalnumberofelementsthatcanbestoredina
multidimensionalarraycanbecalculatedbymultiplying
thesizeofallthedimensions.Forexample:
Thearrayint[][]x=newint[10][20]canstoreatotalof
(10*20)=200elements.
153
Arrays In Java
Declaration of 2D array
Data_Type[][] Array_Name;
Example : int [][] anIntegerArray;
Create Two dimensional Array in Java
In order to create a two dimensional array in Java, we
have to use the New operator as we shown below:
Data_Type[][] Array_Name = new
int[Row_Size][Column_Size];
Example : anIntegerArray = new int[3][4];
It is a 2-dimensional array, that can hold a maximum of
12 elements,
154
Arrays In Java
155
Arrays In Java
Declaration and Initialization of 2D array
Syntax
data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
For example,
int[][] arr = {{1, 2}, {3, 4}};
156
Arrays In Java
Retrieve elements from 2D arrays standard method
int[][] a={{10,20},{30,40}};//declaration and initialization
System.out.println("Two dimensional array elements are");
System.out.println(a[0][0]);
System.out.println(a[0][1]);
System.out.println(a[1][0]);
System.out.println(a[1][1]);
157
Arrays In Java
Retrieve elements from 2D array by using for loop
int[][] a={{10,20},{30,40},{50,60}};//declaration and initialization
System.out.println("Two dimensional array elements are");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++){
System.out.println(a[i][j]);
}
}
158
Arrays In Java
Dynamically passing row and column sizes
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row length of an array : ");
int row=sc.nextInt();
System.out.println("Enter column length of an array : ");
int column=sc.nextInt();
int a[][]=new int[row][column];//declaration
159
Arrays In Java
System.out.print("Enter " + row*column + " Elements to
Store in Array :\n");
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
a[i][j] = sc.nextInt();
}
}
160
Arrays In Java
System.out.print("Elements in Array are :\n");
for (int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
System.out.println("Row ["+i+"]: Column ["+j+"]
:"+a[i][j]);
}
}
161
Arrays In Java
Jagged Array in Java
Jaggedarrayisarrayofarrayssuchthatmemberarrays
canbeofdifferentsizes,i.e.,wecancreatea2-Darrays
butwithvariablenumberofcolumnsineachrow.These
typeofarraysarealsoknownasJaggedarrays.
int arr[][] = new int[2][]; // Declaring 2-D array with 2
rows
// Making the above array Jagged
arr[0] = new int[3]; // First row has 3 columns
arr[1] = new int[2]; // Second row has 2 columns
162
Arrays In Java
// Initializing array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
// Displaying the values of 2D Jagged array
System.out.println("Contents of 2D Jagged Array");
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
163
Abstraction In Java
Inobjectorientedprogrammingabstractionisa
processofprovidingfunctionalitytotheusersbyhiding
itsimplementationdetailsfromthem
Inotherwords,theuserwillhavejustthe
knowledgeofwhatanentityisdoinginsteadofits
implementation
164
Abstraction In Java
ReallifeexampleofAbstractionisATMMachine;Allare
performingoperationsontheATMmachinelikecash
withdrawal,moneytransfer,retrievemini-statement…etc.
butwecan'tknowinternaldetailsaboutATM.
165
Abstraction In Java
Advantages of Abstraction
166
Abstraction In Java
How to Achieve Abstraction in Java?
InJava,wecanachieveDataAbstractionusingAbstract
classandInterface
Interfaceallow100%abstraction(completeabstraction).
Interfaceallowyoutoabstracttheimplementation
completely
Abstractclassallow0to100%abstraction(partialto
completeabstraction)becauseabstractclasscancontain
concretemethodsthathavetheimplementationwhich
resultsinapartialabstraction
167
Abstraction In Java
InJavaprogrammingwehavetwotypesofclassesthey
are
1)Concreteclass
2)Abstractclass
Aconcreteclassisonewhichiscontainingfullydefined
methodsorimplementedmethod.
classHelloworld{
voiddisplay(){
System.out.println("GoodMorning........");
}
}
168
Abstraction In Java
Abstractclass
Aclassthatisdeclaredwithabstractkeyword,isknownasabstract
class.Anabstractclassisonewhichiscontainingsomedefined
methodandsomeundefinedmethod.Injavaprogramming
undefinedmethodsareknownasun-Implemented,orabstract
method.
Syntax
abstractclassclassName{
......
}
Example
abstractclassA{
.....
}
169
Abstraction In Java
Abstract method
Anabstractmethodisonewhichcontainsonly
declarationorprototypebutitnevercontainsbodyor
implementation.Inordertomakeanymethodasabstract
whosedeclarationismustbepredefinedbyabstract
keyword.Thedeclarationofanabstractmethodmustend
withasemicolon;
Syntax
abstractReturnTypemethodName(Listofformal
parameter);
Example
abstractvoidBike();
170
Abstraction In Java
Rules for Using Abstract Class in Java
1)Wecandeclareanabstractclassusingtheabstract
keyword.
2)Itmayhaveabstractaswellasconcrete(non-abstract)
methods.
3)Anabstractclasscanhavestaticmethods.
4)Anabstractclasscanalsohaveconstructors.
5)Itcanhavefinalmethods.Ifwedeclarethemethodas
finalinsidetheabstractclassthenthesubclasscannot
changethebodyofthemethod.
171
Abstraction In Java
Why do we need Abstract Classes in Java?
Wewanttocreateaclassthatjustdeclaresthemethodswithout
providingacompleteimplementationofeverymethod.And,we
wantthatthismethod(s)issharedbyallofitschildclasses,andall
theimplementationdetailswillbefilledbythesesubclasses.
Let’staketheexampleofabankingapplicationorsoftware.
SupposewehaveaclassBankAccountthathasamethoddeposit()
andwithdraw()andthesubclassesofitlikeSavingsAccount,
CurrentAccount,FixedDepositAccount,etc.Sincetheprocessof
depositandwithdrawaldiffersfromoneaccounttoanother,thereis
nopointtoimplementthesetwomethodsintheparentclass
BankAccount.Thisisbecauseeverychildclassmustoverridethese
methodsandprovideanimplementationofthem.
173
Abstraction In Java
174
Abstraction In Java
Interface In Java
1)InJava,aninterfaceisablueprintortemplateofaclass
usedtoachieve100%abstraction.
2)Whenyoucreateaninterface,you'redefiningacontract
forwhataclasscando,withoutsayinganythingabout
howtheclasswilldoit.
3)Therecanbeonlyabstractmethodsinaninterface.
4)Ifaclassimplementsaninterfaceanddoesnotprovide
methodbodiesforallfunctionsspecifiedintheinterface,
thentheclassmustbedeclaredabstract.
175
Abstraction In Java
Syntax to create an interface
interface interface-name{
//abstract methods
}
Example
interface Animal{
public void eat();
public void travel();
}
176
Abstraction In Java
Why we do use interface?
177
Abstraction In Java
Properties of a Java Interface
1)Aninterfaceisimplicitlyabstract.Whiledeclaringaninterface,you
donotneedtousethekeywordabstract.
2)Eachmethodofaninterfaceisimplicitlypublicandabstract,sowe
neednotusethepublicandabstractkeywordwhiledeclaringmethods
insideaninterface.
The following five method declarations are legal and identical
a)void bounce();
b)public void bounce();
c)abstract void bounce();
d)public abstract void bounce();
e)abstract public void bounce();
178
Abstraction In Java
3)All variables defined in an interface are public, static, and final.
In other words, interfaces can declare only constants, not
instance variables.
Legal interface constants declarations
a)public int x = 1; // Looks non-static and non-final, // but isn't!
b)int x = 1; // Looks default, non-final, // non-static, but isn't!
c)static int x = 1; // Doesn't show final or public
d)final int x = 1; // Doesn't show static or public
e)public static int x = 1; // Doesn't show final
f)public final int x = 1; // Doesn't show static
g)static final int x = 1 // Doesn't show public
179
Abstraction In Java
180
Abstraction In Java
4)Aninterfacecanextendoneormoreotherinterfaces.
5)Aclasscanextendonlyoneclass(nomultiple
inheritance),butitcanimplementoneormore
interfaces.
181
Abstraction In Java
182
1) class Foo { }
class Bar implements Foo { }
2) interface Baz { }
interface Fi { }
interface Fee implements Baz { }
3) class Foo { }
interface Zee implements Foo { }
4) class Foo
interface Zoo extends Foo { }
Abstraction In Java
5) interface Fi { }
interface Boo extends Fi { }
6) class Toon extends Foo, Button { }
7) class Zoom implements Fi, Baz { }
8) interface Vroom extends Fi, Baz { }
9)class Yow extends Foo implements Fi { }
183
Abstraction In Java
How interface is different from class ?
1)Youcannotinstantiateaninterface.
2)Itdoesnotcontainanyconstructors.
3)Allmethodsinaninterfaceareabstract.
4)Interfacecannotcontaininstancefields.Interfaceonly
containspublicstaticfinalvariables.
5)Interfaceiscannotextendedbyaclass;itis
implementedbyaclass.
6)Interfacecanextendmultipleinterfaces.Itmeans
interfaceexhibitthefunctionalitymultipleinheritance
184
Abstraction In Java
Implementing Interfaces in Java
Aclassimplementinganinterfaceitmeansthattheclass
agreestoperformthespecificbehaviorsoftheinterface.
Unlessaclassisdeclaredasabstract,itshouldperformall
thebehaviorsoftheinterface.
Inordertoimplementaninterface,aclassusesthe
implementskeyword.
public class Ball implements Bounceable {
public void bounce() { }
public void setBounceFactor(int bf) { }
}
185
Abstraction In Java
Marker or tagged interface
Aninterfacethathavenomemberisknownasmarkeror
taggedinterface.Forexample:Serializable,Cloneable,
Remoteetc.Theyareusedtoprovidesomeessential
informationtotheJVMsothatJVMmayperformsome
usefuloperation.
Example
//WayofwritingSerializableinterface
publicinterfaceSerializable
{
}
189
Abstraction In Java
New features added in interfaces from JDK 8 version
1)Java8allowstheinterfacestohavedefaultandstatic
methods.
WhyDefaultmethods?
ClassessuchasA,B,CandDimplementsaninterfaceXYZInterface.Ifweadd
anewmethodtotheXYZInterface,wehavetochangethecodeinallthe
classes(A,B,CandD)thatimplementsthisinterface.Here,wehaveonlyfour
classesthatimplementstheinterfacewhichwewanttochangebutimagineif
therearehundredsofclassesimplementinganinterfacethenitwouldbealmost
impossibletochangethecodeinallthoseclasses.Thisiswhyinjava8,wehave
anewconcept“defaultmethods”.Thesemethodscanbeaddedtoanyexisting
interfaceandwedonotneedtoimplementthesemethodsintheimplementation
classesmandatorily,thuswecanaddthesedefaultmethodstoexistinginterfaces
withoutbreakingthecode.
190
Abstraction In Java
Why static methods?
Staticmethodsininterfacesaresimilartothedefault
methodsexceptthatwecannotoverridethesemethodsin
theclassesthatimplementstheseinterfaces.
191
Abstraction In Java
Interface with default method
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
void existingMethod(String str);
}
192
Abstraction In Java
Interface with static method
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
}
/* This is a static method. Static method in interface is
static void anotherNewMethod(){
System.out.println("Newly added static method");
}
//Already existing public and abstract method
void existingMethod(String str);
}
193
Abstraction In Java
Default Method and Multiple Inheritance
The multiple inheritance problem can occur, when we have two interfaces with
the default methods of same signature. Lets take an example.
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
} void existingMethod(String str);
}
interface MyInterface2{
default void newMethod(){
System.out.println("Newly added default method");
}void disp(String str);
}
How to solve this issue?
To solve this problem, we can implement this method in the implementation
class
194
Abstraction In Java
Java9hasintroducedanothernewfeature,Java9SE
onwardswecanhaveprivatemethodsininterfaces.
Java9introducedprivatemethodsininterfacestoremove
theredundancybysharingthecommoncodeofmultiple
defaultmethodsthroughprivatemethods.
195
Abstraction In Java
Multiple default methods with duplicate code (java8)
interface MyInterfaceInJava8 {
default void method1() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method1");
}
default void method2() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method2");
}
}
196
Abstraction In Java
Default methods sharing common code using private methods
interface MyInterfaceInJava9 {
default void method1() {
//calling private method
printLines();
System.out.println("This is method1");
}
default void method2() {
//calling private method
printLines();
System.out.println("This is method2");
}
private void printLines() {
System.out.println("Starting method");
System.out.println("Doing someting");
}
}
197
Method Overriding
Example on method overriding
class Human{
public void eat(){//Overridden method
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){//Overriding method
System.out.println("Boy is eating");
}
}
201
Method Overriding
Rules of method overriding in Java
Argumentlist:Theargumentlistofoverridingmethod
(methodofchildclass)mustmatchtheOverridden
method(themethodofparentclass).Thedatatypesofthe
argumentsandtheirsequenceshouldexactlymatch.
202
Association In Java
1)Associationisrelationbetweentwoseparateclasses
whichestablishesthroughtheirObjects.
2)Associationcanbeone-to-one,one-to-many,many-
to-one,many-to-many.
3)InObject-Orientedprogramming,anobject
communicatestootherobjecttousefunctionalityand
servicesprovidedbythatobject.
4)CompositionandAggregationarethetwoformsof
association.
206
Association In Java
AggregationorHAS-Arelationshipbetweentwo
classes.
WhenclassAhasareferencetotheobjectofanotherclassB,class
AissaidtobeinaHAS-ArelationshipwithclassB.Throughthis
referenceofclassBinit,classAcancallandusetheneeded
featuresofclassB,withoutcopyingalltheunnecessarycodeof
classBinit.
Let'stakeanexample
classStudent{
Stringname;
Addressad;
}
Hereintheabovecode,youcansaythatStudenthas-aAddress.
207
Association In Java
Composition or IS-A relationship between two classes
AnIS-Asignifiesarelationshipbetweenthetwoclasses
thatareconnectedtoeachotherthroughinheritance.The
basisofanIS-Arelationshipis-
a)Whenaclassextendsanotherconcrete(non-abstract)
class.
b)Whenaclassextendsanabstractclass.
c)Whenaclassimplementsaninterface.
208
String Handling In Java
Creation of strings
1) Using string literal
WhilecreatingStringobjectusingstringliteral,newoperatorisnot
used.
Stringobjectscanbecreatedusingstringliteralasshownbelow:
Example
Stringstr1=“James”;
212
String Handlin In Java
213
String Handlin In Java
What is String Constant Pool?
TheStringConstantPool(SCP)isaplacewhere
objectswithstringliteralsarestored.
Itisapartoftheheapmemoryarea.
214
String Handling In Java
217
Intheaboveimage,twoStringsarecreatedusingliterali.e“Apple”
and“Mango”.Now,whenthirdStringiscreatedwiththevalue
“Apple”,insteadofcreatinganewobject,thealreadypresent
objectreferenceisreturned.
String Handling In Java
2) Using new keyword
WhenStringobjectiscreatedusingthenewkeyword,
twosamestringobjectsarecreated.Oneinheaparea
(outsideSCP)&anotherinsideStringConstantPool
(SCP).
Example
Stringstr1=newString(“James”);
218
String Handling In Java
DifferencebetweenStringliteralandNewStringobject
WhenyouusenewString("Hello"),itexplicitlycreates
anewandreferentiallydistinctinstanceofaString
object.Itisanindividualinstanceofthejava.lang.String
class.
219
String Handling In Java
Strings=“Harry";mayreuseaninstancefromthestring
constantpoolifoneisavailable(StringPoolisapoolof
StringsstoredinJavaheapmemory)otherwisecreatea
newinstance
220
String Handling In Java
String Class Methods
public char charAt(int index)
Returnsthecharacteratthespecifiedindex.Specifiedindexvalue
shouldbebetween'0'to'length()-1'bothinclusive.Itthrows
IndexOutOfBoundsExceptionifindexisinvalid/outofrange.
Stringname="JamesSmith";
charch1=name.charAt(3)
charch2=name.charAt(6);
charch3=name.charAt(9);
223
String Handlin In Java
224
String Handling In Java
public void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
This method is used to copy set of characters of the invoking string
into the specified character array.
Parameters
srcBegin − index of the first character in the string to copy.
srcEnd − index after the last character in the string to copy.
dst − the destination array.
dstBegin − the start offset in the destination array.
String s = "Its Beyond Simple";
int start = 4;
int end = 10;
char storage[] = new char[end-start];
s.getChars(start,end,storage,0);
System.out.println(storage);
225
String Handlin In Java
226
String Handling In Java
public byte[] getBytes()
ThismethodencodesthisStringintoasequenceofbytes
usingtheplatform'sdefaultcharset,storingtheresultinto
anewbytearray.
StringStr1=newString("WelcometoNareshIt");
byte[]b=Str1.getBytes();//bytearrayhavingallcharactes
withasciivalues
227
String Handling In Java
public char[] toCharArray()
Thismethodconvertsthisstringtoanewcharacterarray.
Itreturnsanewlyallocatedcharacterarray,whoselength
isthelengthofthisstringandwhosecontentsare
initializedtocontainthecharactersequencerepresented
bythisstring.
Stringstr=newString("WelcometoNacre");
char[]ch=str.toCharArray();//arraycontainstheall
charactersofthestring
228
String Handling In Java
public boolean endsWith(String suffix)
ThismethodcheckswhethertheStringendswitha
specifiedsuffix.Thismethodreturnsabooleanvalue
trueorfalse.Ifthespecifiedsuffixisfoundattheend
ofthestringthenitreturnstrueelseitreturnsfalse.
String str1 = new String("This is a test String");
boolean var1 = str1.endsWith("String");
System.out.println("str1 ends with String: "+ var1);
234
String Handling In Java
int compareTo(String str)
TheJavaStringcompareTo()methodisusedforcomparingtwo
stringslexicographically.Eachcharacterofboththestringsis
convertedintoaUnicodevalueforcomparison.Ifboththe
stringsareequalthenthismethodreturns0elseitreturns
positiveornegativevalue.Theresultispositiveifthefirststring
islexicographicallygreaterthanthesecondstringelsetheresult
wouldbenegative.
Stringstr1="Stringmethodtutorial";
Stringstr2="compareTomethodexample";
intvar1=str1.compareTo(str2);
System.out.println("str1&str2comparison:"+var1);
235
String Handling In Java
The concat() method
public String concat(String str)
Thismethodconcatenatesthestringstrattheendofthecurrent
string.Forexample–s1.concat("Hello");wouldconcatenatethe
String“Hello”attheendoftheStrings1.Thismethodcanbe
calledmultipletimesinasinglestatementlikethis
Strings1="Nacre";
s1=s1.concat("Software").concat("Service").concat("Pvt.Ltd");
237
String Handling In Java
replace() method
String replace(char oldChar, char newChar)
It replaces all the occurrences of a oldChar character with
newChar character.
For example, "pog pance".replace('p', 'd') would return
dog dance.
238
String Handling In Java
replaceAll() method
String replaceAll(String regex, String replacement)
It replaces all the substrings that fits the given regular
expression with the replacement String.
String str = new String("My .com site is facebook.com");
System.out.println(str.replaceAll("com", "net"));
Output is My.net site is facebook.net
240
String Handling In Java
intern() method
1)It is used for getting the string from the memory if it is already
present.
2)This method ensures that all the same strings share the same
memory.
3)ThismethodsearchesthememorypoolforthementionedString,
ifthestringisfoundthenitreturnsthereferenceofit,elseit
allocatesanewmemoryspaceforthestringandassigna
referencetoit.
4)Forexample,creatingastring“hello”10timesusingintern()
methodwouldensurethattherewillbeonlyoneinstanceof
“Hello”inthememoryandallthe10referencespointtothe
sameinstance.
249
String Handling In Java
//String object in heap
String str1 = new String("hello world");
//String literal in pool
String str2 = "hello world";
//String literal in pool
String str3 = "hello world";
//String object interned to literal
//It will refer to existing string literal
String str4 = str1.intern();
250
String Handling In Java
isEmpty()method
ThismethodcheckswhetheraStringisemptyornot.
Thismethodreturnstrueifthegivenstringisempty,
elseitreturnsfalse.Inotherwordsyoucansaythatthis
methodreturnstrueifthelengthofthestringis0.
public boolean isEmpty()
251
String Handling In Java
split() method
This method used for splitting a String into its substrings
based on the given delimiter or regular expression.
Wehavetwovariantsofsplit()methodinStringclass.
1.String[]split(Stringregex):Itreturnsanarrayofstringsafter
splittinganinputStringbasedonthedelimitingregular
expression.
2.String[]split(Stringregex,intlimit):ThisJavaStringsplit
methodisusedwhenwewantthesubstringstobelimited.
Theonlydifferencebetweenthismethodandabovemethodisthat
itlimitsthenumberofstringsreturnedaftersplitup.Fore.g.
split("anydelimiter",3)wouldreturnthearrayofonly3strings
evenifthedelimiterispresentinthestringmorethan3times.
253
String Handling In Java
String str = new String("28/12/2013");
String array1[]= str.split("/");
for (String temp: array1){
System.out.println(temp);
}
String array2[]= str.split("/", 2);
for (String temp: array2){
System.out.println(temp);
}
254
String Handling In Java
Difference between zero and negative limit in java string
split method
Limit zero excludes trailing empty strings, where as negative limit
includes trailing strings
String s="bbaaccaa";
String arr1[]= s.split("a", -1);
String arr2[]= s.split("a", 0);
255
String Handling In Java
Java String split with multiple delimiters (special characters)
String s = " ,ab;gh,bc;pq#kk$bb";
String[] str = s.split("[,;#$]");
Word as a regular expression in Java String split method
String str = "helloxyzhixyzbye";
String[] arr = str.split("xyz");
Splitting string based on whitespace
String str = "My name is Ram";
String[] arr = str.split(" ");
for (String s : arr)
System.out.println(s);
256
String Handling In Java
format() method
ThismethodisusedforformattingtheString.Therearesomany
thingsyoucandowiththismethod,forexampleyoucan
concatenatethestringsusingthismethodandatthesametime,
youcanformattheoutputofconcatenatedstring.
public static String format(Locale l,String format,
Object... args)
Returns a formatted string using the specified locale, format string,
and arguments.
public static String format(String format, Object... args)
Returns a formatted string using the specified format string and
arguments.
257
String Handling In Java
Java String Format Specifiers
%c –Character
%d –Integer
%s –String
%o –Octal
%x –Hexadecimal
%f –Floating number
%h –hash code of a value
258
String Handling In Java
String str = "just a string";
//concatenating string using format
String formattedString = String.format("My String is %s", str);
// %.6f is for having 6 digits in the fractional part
String formattedString2 = String.format("My String is
%.6f",12.121);
259
String Handling In Java
Left padding an integer number with 0's and converting
it into a String using Java String format() method.
int str = 88;
String formattedString = String.format("%05d", str);
System.out.println(formattedString);// 00088
261
String Handling In Java
Displaying String, int, hexadecimal, float, char, octal
value using format() method
String str1 = String.format("%d", 15); // Integer value
String str2 = String.format("%s", "BeginnersBook.com"); // String
String str3 = String.format("%f", 16.10); // Float value
String str4 = String.format("%x", 189); // Hexadecimal value
String str5 = String.format("%c", 'P'); // Char value
String str6 = String.format("%o", 189); // Octal value
262
String Handling In Java
StringBuffer Class
1)AsweknowthatStringobjectsareimmutable,soifwedoalotof
modificationstoStringobjects,wemayendupwithamemory
leak.ToovercomethisweuseStringBufferclass.
2)JavaStringBufferclassisusedtocreatemutable(modifiable)
stringobject.
3)StringBufferclassrepresentsgrowableandwritablecharacter
sequence.Itisalsothread-safei.e.multiplethreadscannotaccessit
simultaneously.
4)Everystringbufferhasacapacity.Aslongasthelengthofthe
charactersequencecontainedinthestringbufferdoesnotexceed
thecapacity,itisnotnecessarytoallocateanewinternalbuffer
array.Iftheinternalbufferoverflows,itisautomaticallymade
larger.
263
String Handling In Java
Constructors of StringBuffer class
1)StringBuffer():Createsanemptystringbufferwiththeinitial
capacityof16.
2)StringBuffer(intcapacity):Createsanemptystringbufferwith
thespecifiedcapacityaslength.
3)StringBuffer(Stringstr):Createsastringbufferinitializedto
thecontentsofthespecifiedstring.
4)StringBuffer(charSequence[]ch):Createsastringbufferthat
containsthesamecharactersasthespecifiedCharSequence.
264
String Handling In Java
Important methods of StringBuffer class
append() method
Theappend()methodconcatenatesthegivenargument(string
representation)totheendoftheinvokingStringBufferobject.
StringBufferclasshasseveraloverloadedappend()method.
StringBuffer append(String str)
StringBuffer append(int n)
StringBuffer append(Object obj)
StringBuffer strBuffer = new StringBuffer("Core");
strBuffer.append("JavaGuru");
System.out.println(strBuffer);
strBuffer.append(101);
System.out.println(strBuffer);
265
String Handling In Java
StringBuilder Class
1)StringBuilderobjectsarelikeStringobjects,exceptthattheycan
bemodified.HenceJavaStringBuilderclassisalsousedto
createmutable(modifiable)stringobject.
2)StringBuilderissameasStringBufferexceptforoneimportant
difference.StringBuilderisnotsynchronized,whichmeansitis
notthreadsafe.
3)Thisclassisdesignedforuseasadrop-inreplacementfor
StringBufferinplaceswherethestringbufferwasbeingusedby
asinglethread.
4)InstancesofStringBuilderarenotsafeforusebymultiple
threads.Ifsuchsynchronizationisrequiredthenitis
recommendedthatStringBufferbeused.
272
String Handling In Java
Constructors of StringBuilder class
StringBuilder():Constructsastringbuilderwithno
charactersinitandaninitialcapacityof16characters.
StringBuilder(intcapacity):Constructsastringbuilder
withnocharactersinitandaninitialcapacityspecified
bythecapacityargument.
StringBuilder(Stringstr):Constructsastringbuilder
initializedtothecontentsofthespecifiedstring.The
initialcapacityofthestringbuilderis16plusthelength
ofthestringargument.
273
String Handling In Java
274
275
Exception Handling In Java
Exception Handling In Java
What is an Error?
Errorsarenotexceptionsatall,butproblemsthatarise
beyondthecontroloftheuserortheprogrammer.
SomeErrorsinJavaareVirtualMachineError,
OutOfMemoryError,etc.
Considerasituation,whenaprogramattemptstoallocate
memoryfromtheJVMbutthereisnotenoughspaceto
satisfytheuserrequest.Or,whenaprogramtriestoload
aclassfilebycallingClass.forName()methodandthe
classfileiscorrupt.Suchexceptionsareknownasan
error.
277
Exception Handling In Java
What is an Exception?
AnExceptionisanunexpectedeventthatinterruptsthe
normalflowoftheprogram.Whenanexceptionoccurs
programexecutiongetsterminated.Insuchcaseswegeta
systemgeneratederrormessage.
SomecommonexamplesofExceptionsinJavaare
1)Dividebyzeroerrors
2)Tryingtoaccessthearrayelementswithaninvalid
index
3)Invalidinputdatabytheuser
278
Exception Handling In Java
Difference between error and exception
279
Error Exception
1.Impossibletorecoverfroman
error
1.Possibletorecoverfrom
exceptions
2.Errorsareoftype‘unchecked’2.Exceptionscanbeeither
‘checked’or‘unchecked’
3.Occuratruntime 3.Canoccuratcompiletimeor
runtime
4.Causedbytheapplication
runningenvironment
4.Causedbytheapplication
itself
Exception Handling In Java
What is an Exception Handling? What happen when
Exception is raised?
Todesigntheprograminsuchawaythatevenifthereisan
exception,alloperationsareperformedthenonlytheprogram
shouldbeterminatediscalledexceptionhandling
Wheneveranexceptionoccurswhileexecutingastatement,creates
anexceptionobject(containsalinenumberwheretheexception
occurred,typeofexception)andthenthenormalflowofthe
programhaltsandJREtriestofindsomeonethatcanhandlethe
raisedexception.
ExceptionHandleristheblockofcodethatcanprocessthe
exceptionobject.
280
Exception Handling In Java
Types of Exceptions
TherearetwotypesofexceptionsinJava:
1)Checkedexceptions
2)Uncheckedexceptions
CheckedExceptions
Acheckedexceptionisacompile-timeexception,thatis,aJava
compilerchecksornotifiesduringthecompilation-time.The
programmercannotsimplyignoretheseexceptionsandshouldtake
caretohandletheseexceptions.Iftheprogrammerdoesnotwritethe
codetohandlethemthentherewillbeacompilationerror.
A checked exception extends the Exception class. Some checked
Exceptions are SQLException, IOException,
ClassNotFoundException, InvocationTargetException, etc.
284
Exception Handling In Java
In Java, exception handling is done using five keywords,
1)try
2)catch
3)throw
4)throws
5)finally
Exception handling is done by transferring the execution
of a program to an appropriate exception handler when
exception occurs.
286
Exception Handling In Java
Note
1)It is illegal to use a try clause without either a catch
clause or a finally clause.
2)Any catch clauses must immediately follow the try
block. Any finally clause must immediately follow the
last catch clause (or it must immediately follow the try
block if there is no catch).
3)It is legal to omit either the catch clause or the finally
clause, but not both.
294
Exception Handling In Java
try(FileReader fr = new FileReader("file path")) {
// use the resource
} catch () {
// body of catch
}
}
296
Exception Handling In Java
try with out resource management
FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
297
Exception Handling In Java
try with resource management
try(FileReader fr = new FileReader("E://file.txt")) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by
one
} catch (IOException e) {
e.printStackTrace();
}
298
Exception Handling In Java
In Java SE 7 and later, we can now catch more than one type of exception in a
single catch block.
Each exception type that can be handled by the catch block is separated using a
vertical bar or pipe |.
Its syntax is:
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
Example
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
304
Exception Handling In Java
If the base exception class has already been specified in
the catch block, do not use child exception classes in the
same catch block. Otherwise, we will get a compilation
error.
Example
try {
int array[] = new int[10];
array[10] = 30 / 0;
} catch (Exception | ArithmeticException |
ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
305
Exception Handling In Java
throws clause
We have a method myMethod() that has statements may generate either
ArithmeticException or NullPointerException, to handle that use try-catch as
shown below:
public void myMethod(){
try {
// Statements that might throw an exception
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
suppose you have several such methods that can cause exceptions, in that case it
would be tedious to write these try-catch for each method. The code will become
unnecessary long and will be less-readable.
306
Exception Handling In Java
Anymethodthatiscapableofcausingexceptionsmust
listalltheexceptionspossibleduringitsexecution,so
thatanyonecallingthatmethodgetsapriorknowledge
aboutwhichexceptionsaretobehandled.Amethodcan
dosobyusingthethrowskeyword.
Syntax
type method_name(parameter_list) throws exception_list
{
// definition of method
}
307
Exception Handling In Java
throw clause
1)It is used for throw an exception explicitly and catch it.
2)It is used in software testing to test whether a program
is handling all the exceptions as claimed by the
programmer
3)throw clause can be used to throw our own exceptions
308
Exception Handling In Java
Explicitly handling the exception
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
309
Exception Handling In Java
User defined exceptions/Custom exceptions
Rules to design user defined Exception
1)Createapackagewithvaliduserdefinedname.
2)Createanyuserdefinedclass.
3)Makethatuserdefinedclassasderivedclassof
ExceptionorRuntimeExceptionclass.
4)Declareparametrizedconstructorwithstringvariable.
5)callsuperclassconstructorbypassingstringvariable
withinthederivedclassconstructor.
6)Savetheprogramwithpublicclassname.java
310
Exception Handling In Java
311
Exception Handling In Java
Rethrowing an exception
Theremightbesituationsinyourprogramwhereyou
wanttobothcatchanexceptioninyourcodeandalso
wantitscallerbenotifiedabouttheexception.Thisis
possiblebyrethrowingtheexceptionusingthrow
statement.
312
Exception Handling In Java
Calling method Caller method
pubic void divide() {
int x,y,z;
try {
x = 6 ;
y = 0 ;
z = x/y ;
System.out.println(x + "/"+ y +" = " +
z); }
catch(ArithmeticExceptione) {
System.out.println("Exception
Caught in Divide()");
System.out.println("Cannot
Divide by Zero in Integer Division");
throw e; // Rethrows an exception
}
}
public static void main(String[] args) {
System.out.println("Start of main()");
try {
divide();
}
catch(ArithmeticExceptione) {
System.out.println("Rethrown Exception
Caught in Main()");
System.out.println(e);
}
}
313
Exception Handling In Java
Nested try catch block in Java
When a try catch block is present in another try block
then it is called the nested try catch block.
Nested try blocks are useful when different statements of
try block throw different types of exceptions.
Iftheexceptionthrownbytheinnertryblockcannotbe
caughtbyit’scatchblock,thenthisexceptionis
propagatedtooutertryblocks.Anyoneoftheoutercatch
blockshouldhandlethisexceptionotherwiseprogram
willterminateabruptly.
314
Exception Handling In Java
class Exp{
public static void main(String... ar){
Exp ob = new Exp();
ob.method1();
}
public void method1(){
method2();
}
public void method2(){
method3();
}
public void method3(){
System.out.println(100/0);//ArithmeticException is raised/thrown by the program.
System.out.println("Hello"); //This statement will not be executed.
}
}
319
Multithreading In Java
Process Vs Thread
Anexecutingprogramiscalledaprocess.Eachprocesscanhavea
singlethreadormultiplethreads.Sothatthethreadisthesmallest
unitofaprocessthatcanrunconcurrentlywiththeotherparts
(otherthreads)ofthesameprocess.
326
Multithreading In Java
Achieve multithreading in java
Injavalanguagemultithreadingcanbeachieveintwo
differentways.
1)UsingThreadclass
2)UsingRunnableinterface
331
Multithreading In Java
Using Thread Class
1)Create any user defined class and make that one as a derived
class of Thread class.
class MyThread extends Thread{ }
2)Override run() method of Thread class (It contains the logic of
perform any operation)
3)Create an object for user-defined thread class and attached that
object to predefined thread class object.
MyThread obj=new MyThread();
Thread t=new Thread(obj);
4)Call start() method of thread class to execute the thread
t.start();
332
Multithreading In Java
333
Multithreading In Java
Using Runnable Interface
1)DefinetheclassthatimplementstheRunnableinterface
andimplementtherun()methodoftheRunnable
interfaceintheclass.
2)Createaninstanceofthedefinedclass.
3)CreateaninstanceoftheThreadclassusingtheThread
(Runnabletarget)constructor.
4)Startthethreadbyinvokingthestart()methodonyour
Threadobject.
334
Multithreading In Java
Directly calling the run() method
336
public void run(){
for(inti=1;i<=3;i++){
try{
Thread.sleep(1000);
}
catch(InterruptedExceptionie){
ie.printStackTrace();
}
System.out.println(i);
}
}
public static void main(String args[]){ Thread
th1 = new Thread(new RunMethodExample(),
"th1");
Thread th2 = new Thread(new
RunMethodExample(), "th2"); th1.run();
th2.run();
}
Multithreading In Java
Execute the thread by using start()method
337
public void run(){
for(inti=1;i<=3;i++){
try{
Thread.sleep(1000);
}
catch(InterruptedExceptionie){
ie.printStackTrace();
}
System.out.println(i);
}
public static void main(String args[]){
Thread th1 = new Thread(new
RunMethodExample(), "th1");
Thread th2 = new Thread(new
RunMethodExample(), "th2"); th1.start();
th2.start();
}
Multithreading In Java
Difference between Thread and Runnable
338
Thread Class Runnable Interface
Eachthreadcreatesauniqueobjectandgets
associatedwithitsomorememoryrequired.
Multiplethreadssharethesameobjects.
Solessmemoryisused.
InJava,multipleinheritancenotallowed
hence,afteraclassextendsThreadclass,it
cannotextendanyotherclass.
Ifaclassdefinethreadimplementingthe
Runnableinterfaceithasachanceof
extendingoneclass.
Ausermustextendthreadclassonlyifit
wantstooverridetheothermethodsin
Threadclass.
Ifyouonlywanttospecializerunmethod
thenimplementingRunnableisabetter
option.
ExtendingThreadclassintroducestight
couplingastheclasscontainscodeof
Threadclassandalsothejobassignedtothe
thread
ImplementingRunnableinterfaceintroduces
loosecouplingasthecodeofThreadis
separateformthejobofThreads.
Multithreading In Java
Thread Life Cycle
The various states of java thread
1) New
2) Runnable
3) Running
4) Waiting
5) Timed Waiting
6) Blocked
7) Terminated
339
Multithreading In Java
340
Multithreading In Java
New State
1)WheneverwecreateaninstanceofThread,Threadgets
astatecalled“New”state.
2)Inthiscase,Threadisjustcreatedbutnotstarted,in
otherwordswehaveathreadobjectbutthereisno
threadexecution.
Threadt1=newThread();
341
Multithreading In Java
Runnable State
1)Wheneverwestartthethreaditmovesfrom“New”
stateto“Runnable”state.
2)Inthiscase,threadisreadytobeexecutedbutit’sjust
waitingfortheThreadschedulertopickitfor
execution.
3)Inthisstate,anewcallstackwillbecreatedforthe
thread.
4)Belowlinetakesthethreadfrom“New”stateto“
Runnable”state.
t.start();
342
Multithreading In Java
Running State
1)This is not the standard thread state defined by Java but its used to indicate that the
thread is currently running or executing the logic.
2)Moving thread from “ Runnable ” state to “ Running ” state is entirely dependent
on Thread scheduler. Thread scheduler is the one which decides whether to move
the thread from “ Runnable ” state to “ Running ” state or put it on hold in “
Runnable ” state by giving chance to other Runnable threads.
3)Thread scheduler is operating system dependent most of the operating systems
follow Round-robin scheduling. In this case, each thread is given a fixed amount of
processor time called as “ quantum ” or “ time slice ” within which it has to
execute.
4)Any thread which has got this time slice to execute its task is said to be in “
Running ” state.
5)Once time slice expires, thread will be returned to “ Runnable ” state and another
thread will be assigned to the processor.
6)This process that operating system uses to determine which thread has to go from “
Runnable ” state to “ Running ” state is called “ Thread scheduling ”
343
Multithreading In Java
Waiting State
1)In this case,Thread will be moved from “ Running ”
state to “ Waiting ” state by calling its wait() method.
2)This can be done whenever we want currently running
thread to wait for some other thread to execute and
notify back to it to continue the execution.
3)Once the thread wait is notified , then the waited thread
will be moved to “ Runnable ” state.
344
Multithreading In Java
TerminatedState
1)ThreadwillbemovedtoTerminatedstate(alsocalled
Deadstate)whenitcompletesitsexecution
successfully.
2)Itcanalsobeterminatedforcefullybykillingit.
347
Multithreading In Java
Terminating the Thread
A thread will terminate automatically when it comes out of run() method.
To terminate the thread on our own the following steps can be used
1)Create a boolean type variable and initialize it to false
boolean stop=false;
2)Let us assume that we want to terminate the thread when the user
press<Enter>key. So, when the user press that button, make the boolean type
variable as true
stop=true;
3)Check this variable in run()method and when it is true, make the thread return
from the run() method.
public void run(){
if(stop==true)return;
}
348
Multithreading In Java
Single Tasking Using a Thread
1)Athreadcanbeemployedtoexecuteonetaskatatime.Suppose
thereare3taskstobeexecuted.Wecancreateasinglethread
andpassthese3tasksonebyonetothethreadiscalledassingle
taskingusingathread.
2)Forthispurpose,wecanwriteallthesetasksseparatelyin
separatemethods:task1(),task2(),task3().
3)Thenthesemethodsshouldbecalledfromrun()method,oneby
one.
4)Athreadexecutesonlythecodeinsidetherun()method.Itcan
neverexecuteothermethodsunlesstheyarecalledfromrun().
349
Multithreading In Java
Multi Tasking Using Threads
Inmultitasking,severaltasksareexecutedatatime.For
thispurposeweneedmorethanonethread.
Forexample,toperform2tasks,wecantake2threads
andattachthemtothe2tasks.Thenthosetasksare
simultaneouslyexecutedbytwothreads.Thisiscalled
asmultithreading
350
Multithreading In Java
6)Priorityisanintegervaluethatmustrangebetween1and10,with10being
thehighestpriority,1beingthelowestand5beingthedefault.
7)Ifyouspecifyaprioritythatisoutofrange,thenan
IllegalArgumentExceptionexceptionthrown.
8)Somethreadprioritiesarestaticmembervariablesofjava.lang.Threadclass.
9)TheseincludeMIN_PRIORITY, NORM_PRIORITY, and
MAX_PRIORITYrepresentingvalues1,5and10respectively.
10)ThepriorityofthemainthreadisThread.NORM_PRIORITY,i.e.,5.
NOTE:Generallyhigherprioritythreadscanbeexpectedtobegivenpreference
bythethreadscheduleroverlowerprioritythreads.However,the
implementationofthreadschdulingisleftuptotheJVMimplementation.
363
Multithreading In Java
364
Multithreading In Java
The Methods to Prevent a Thread from Execution
Wecanprevent(stop)aThreadexecutionbyusingthe
followingmethods.
1)yield();
2)join();
3)sleep();
365
Multithreading In Java
Note
setDaemon()methodcanonlybecalledbeforestarting
thethread.Thismethodwouldthrow
IllegalThreadStateExceptionifyoucallthismethod
afterThread.start()method.
376
Multithreading In Java
Inter Thread Communication
Polling Problem
Theprocessoftestingaconditionrepeatedlytillitbecomestrueis
knownaspolling.
Example
Supposethattheproducerhastowaituntiltheconsumerisfinished
beforeitgeneratesmoredata.Inapollingsystem,theconsumer
wouldwastemanyCPUcycleswhileitwaitsfortheproducerto
produce.Oncetheproducerhasfinished,itwouldstartpolling,
wastingmoreCPUcycleswaitingfortheconsumertofinish,and
soon.
377
Multithreading In Java
Thesolutionforpollingproblemisinter-threadcommunication
Inter-threadcommunication
Inter-threadcommunicationisaprocessinwhichathreadis
pausedrunninginitscriticalregionandanotherthreadisallowed
toenter(orlock)inthesamecriticalregiontobeexecuted.i.e.
synchronizedthreadscommunicatewitheachother.
Forinter-threadcommunicationjavaprovidesthreemethodsthey
arewait(), notify() and notifyAll().
Allthesemethodsbelongtoobjectclassasfinalsothatallclasses
havethem.Theymustbeusedwithinasynchronizedblockonly.
378
Multithreading In Java
ThreadGroup in Java
1)AThreadGrouprepresentsasetofthreads.Sowecansuspend,
resumeorinterruptgroupofthreadsbyasinglemethodcall.
2)Athreadgroupcanalsoincludetheotherthreadgroup.The
threadgroupcreatesatreeinwhicheverythreadgroupexcept
theinitialthreadgrouphasaparent.
3)Athreadisallowedtoaccessinformationaboutitsownthread
group,butitcannotaccesstheinformationaboutitsthread
group'sparentthreadgrouporanyotherthreadgroups.
4)Javathreadgroupisimplementedbyjava.lang.ThreadGroup
class.
380
Multithreading In Java
381
Multithreading In Java
Constructors of ThreadGroup class
ThreadGroup(String name)
creates a thread group with given name.
ThreadGroup base = new ThreadGroup("Base");
ThreadGroup(ThreadGroup parent, String name)
creates a thread group with given parent group and
name.
ThreadGroup group1 = new ThreadGroup(base,
"Group1");
382
Multithreading In Java
Important methods of ThreadGroup class
activeCount():returnsanestimateofthenumberofactivethreadsin
thethreadgroupanditssubgroups.
destroy():destroysthethreadgroupandallofitssubgroups.
enumerate(Thread[]list):copiesintothespecifiedarrayeveryactive
threadinthisthreadgroupanditssubgroups.
getMaxPriority():returnsthemaximumpriorityofthethreadgroup.
interrupt():interruptsallthreadsinthethreadgroup.
isDaemon():testsifthethreadgroupisadaemonthreadgroup.
setMaxPriority(intpriority):setsthemaximumpriorityofthe
group.
383
Multithreading In Java
Thread Pool
1)Intermsofperformance,creatinganewthreadisanexpensive
operationbecauseitrequirestheoperatingsystemallocates
resourcesneedforthethread.
2)Insteadofcreatingnewthreadswhennewtasksarrive,athread
poolkeepsanumberofidlethreadsthatarereadyforexecuting
tasksasneeded.Afterathreadcompletesexecutionofatask,it
doesnotdie.Insteaditremainsidleinthepoolwaitingtobe
chosenforexecutingnewtasks.
3)Youcanlimitadefinitenumberofconcurrentthreadsinthe
pool,whichisusefultopreventoverload.Ifallthreadsarebusily
executingtasks,newtasksareplacedinaqueue,waitingfora
threadbecomesavailable.
384
Multithreading In Java
What is an Executor?
AnExecutorisanobjectthatisresponsibleforthreadsmanagementand
executionofRunnabletaskssubmittedfromtheclientcode.Itdecouplesthe
detailsofthreadcreation,scheduling,etcfromthetasksubmissionsoyoucan
focusondevelopingthetask’sbusinesslogicwithoutcaringaboutthethread
managementdetails.
Thatmeans,ratherthancreatingathreadtoexecuteatasklikethis:
Threadt=newThread(newRunnableTask());
t.start();
Yousubmittaskstoanexecutorlikethis:
Executorexecutor=anExecutorImplementation;
executor.execute(newRunnableTask1());
executor.execute(newRunnableTask2());
386
Different Ways Object Creation In Java
1)Using new operator
Employee obj=new Employee();
2)Using factory methods
NumberFormat obj=NumberFormat.getNumberInstance();
3)Using newInstance() method
Class c=Class.forName(“Employee”);
Empoyee obj=(Employee)c.newInstance();
4)By cloning an already available object
Employee obj1=new Employee();
Employee obj2=(Employee)obj1.clone();
438
Object Class In Java
Object Class
1)Thereisaclasswiththename‘Object’Ijava.lang
packagewhichisthesuperclassofallclassesinJava
2)EveryclassinJavaisadirectorindirectsubclassof
theObjectclass
3)TheObjectclassdefinesthemethodstocompare
objects,toconvertanobjectintoString,etc.
440
Object Class
Methods of Object class
441
Method Description
equals()Compares the references of two objects return true when they are
equal otherwise return false
toString()Returns a string representation of an object
getClass()It gives an object that contains the name of a class to which an
object belongs
hashCode()Returns hashcodenumber of an object
notify()Sends a notification to a thread which is waiting for an object
notifyAll()Sends a notification forall waiting threads for the object
wait() Causes a thread to wait till a notification is received from a notify()
or notifyAll() methods
Exception Propagation
•The currently executing method is at the top of the call
stack, which in this example is method3(). Let's say
while executing method3(), an exception is
raised/thrown. Now this exception is thrown down to
the next method in the call stack, i.e. method2(), which
in turn throws the exception down to next method in the
call stack, i.e. method1(). The process continues until
the exception is thrown to the method at the bottom of
the call stack, i.e. main() method.
446
Catch multiple exceptions
•In Java 7 it was made possible to catch multiple
different exceptions in the same catch block.
try {
// execute code that may throw 1 of the 3 exceptions
below.
} catch(SQLExceptione) {
e.printStackTrace();
} catch(IOExceptione) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
452
Catch multiple exceptions
try {
// execute code that may throw 1 of the 3 exceptions
below.
} catch(SQLException | IOException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
453
Rethrowing the
exception
Rethrowing The Exeption
•Theremightbesituationsinyourprogramwhereyou
wanttobothcatchanexceptioninyourcodeandalso
wantitscallerbenotifiedabouttheexception.
•Thisispossiblebyrethrowingtheexceptionusing
throwstatement.
455
Interthread Communication
Polling Problem
Theprocessoftestingaconditionrepeatedlytillitbecomestrueis
knownaspolling.
Example
Supposethattheproducerhastowaituntiltheconsumerisfinished
beforeitgeneratesmoredata.Inapollingsystem,theconsumer
wouldwastemanyCPUcycleswhileitwaitsfortheproducerto
produce.Oncetheproducerhasfinished,itwouldstartpolling,
wastingmoreCPUcycleswaitingfortheconsumertofinish,and
soon.
460
Inter-thread communication
Thesolutionforpollingproblemisinter-threadcommunication
Inter-threadcommunication
Inter-threadcommunicationisaprocessinwhichathreadis
pausedrunninginitscriticalregionandanotherthreadisallowed
toenter(orlock)inthesamecriticalregiontobeexecuted.i.e.
synchronizedthreadscommunicatewitheachother.
Forinter-threadcommunicationjavaprovidesthreemethodsthey
arewait(), notify() and notifyAll().
Allthesemethodsbelongtoobjectclassasfinalsothatallclasses
havethem.Theymustbeusedwithinasynchronizedblockonly.
461
Object Oriented Programming
Advantages of Abstraction
482
Object Oriented Programming
How to Achieve Abstraction in Java?
InJava,wecanachieveDataAbstractionusingAbstract
classandInterface
Interfaceallow100%abstraction(completeabstraction).
Interfaceallowyoutoabstracttheimplementation
completely
Abstractclassallow0to100%abstraction(partialto
completeabstraction)becauseabstractclasscancontain
concretemethodsthathavetheimplementationwhich
resultsinapartialabstraction
483
Object Oriented Programming
What is an Encapsulation?
1)WecandefineitasEncapsulationisthewrappingupofdataand
functions(methodsthatoperateonthedata)intoasingleunit
(calledclass).
2)Thereisaprohibitionfordirectaccesstothedata.Functions
(thatcombinewiththedata)aretheonlywaytoaccessdata.
ThesefunctionsarethememberfunctionsormethodsinJava.It
basicallycreatesashieldduetowhichthecodeordatacannotbe
accessedoutsidetheshield.
3)InJavaclassbindthedatawithitsassociatedmethodsoclassis
anexampleofencapsulation
484
Object Oriented Programming
485
Object Oriented Programming
Achieving Encapsulation in Java
In order to achieve encapsulation in Java, we have to
1)declare the variables of a class as private, so that they cannot be
accessed directly from outside the class.
2)provide setter and getter methods that are declared as public, to
view and change the values of the variables.
486
Wrapper Classes
Number class
Number is an abstract class whose sub classes are Byte,
Short,Integer,Long,Float and Double
So the methods of Number class are commonly available in all
these classes
Methods of Number class
byte byteValue()
Converts the calling object into byte value
short shortValue()
Converts the calling object into short value
int intValue()
Converts the calling object into int value
501
Wrapper Classes
Character Class
The character class wraps a value of the primitive type char in an object.
Character class has only one constructer which accepts primitive data type
Character obj=new Character('A');
Important methods of Character class
char charvalue( ):used to convert character object into character primitive
character obj=new character ('A');
char ch=objcharValue();
intcompare To (character obj):useful to compare two character objects
intx =obj1.compare (obj2);
if obj1==obj2,returns 0
if obj1<obj2,returns negative value
if obj1>obj2,returns positive value
String toString( ):converts character object into string object
503
Wrapper Classes
static booleanisSpaceChar(char ch)
returns true if chis represents a white space
static booleanisLetterorDigit(char ch)
returns true if cheither a letter or digit
static char toUpperCase(char ch)
converts chinto uppercase
static char toLowerCase(char ch)
converts chinto lowercase
505
Wrapper Classes
Byte Class
The byte class wraps a value of primitive type 'byte‘ in an object.
Constructors
1)Byte(byte num):
create byte object as
Byte obj=new Byte(120);
2)Byte(String str):
create Byte object by converting a string that contains a byte
number
Byte obj=new Byte("120");
506
Wrapper Classes
Important methods of Byte class
int compareTo(Byte b)
useful to compare the contents of Byte class objects.
int x=obj1.comareTo(obj2);
obj1==obj2 returns 0
obj1<obj2 returns negative value
obj1>obj2 returns positive value
boolean equals(object obj)
compares the Byte object with any other object obj.If both have
same content then it returns true otherwise false.
static byte parseByte(String str)
returns the primitive byte number contained in the string str.
507
Wrapper Classes
String toString()
converts Byte object into string object and returns that string object
static Byte valueOf(String str)
converts string str that contains some byte number into Byte class
object
static Byte valueOf(byte b)
converts the primitive byte b into Byte object.
508
Wrapper Classes
Short Class
Short class wraps a value of primitive data type 'short' in its object.
Constructors
Short(short num)
Takes short number as its parameter and convert it into Short class
object.
short s=14007;
Short obj=new Short(s);
Short(String str)
Useful to construct the short class object by passing string str to it
as
String str="2756";
Short obj=new Short(str);
509
Wrapper Classes
Important methods of Short class
int compareTo(Short obj)
Compare the numeric value of two short class objects and return 0,-ve
value or +ve value.
boolean equals(Object o)
Compares the Short object with any other object o.if both have the same
content then it returns true otherwise false.
static short parseShort(String str)
returns short equivalent of the string str.
String toString()
returns a string form of the Short object.
static Short valueof(String str)
Converts a string str that contains some short number into Short class
object and returns that object.
510
Wrapper Classes
Integer Class
The integer class wraps a value of the primitive int number as its
parameter and converts it into integer class object
Constructors
Integer(int num): creates integer object
Integer obj= new Integer(123000);
here, we are converting a primitive int value into integer object.
This is called 'boxing’
Integer(String str):create an Integer object by converting a string
that contains as int number
Integer obj = new Integer("198663");
511
Wrapper Classes
Important methods of Integer class
int compareTo(Integer obj)
compares the numerical value of two integer class objects and returns
0,+ve value ,or -ve value
boolean equals(object obj)
compare the inter object with any other object if both have the same
content,then it returns true otherwise false.
static int parseInt(String str)
returns int equivalent of the string str.
String toString()
returns a string form of the integer object.
static Integer valueOf(String str)
convert a string str that contains some int number into integer class object
and returns that object.
512
Wrapper Classes
static String toBinaryString(int i)
converts decimal integer number i into binary umber system and returns
that binary number as a string
static String toHexString(int i)
converts decimal integer number i into hexadecimal number system and
returns that hexdecimal number as a string
static String toOctalString(int i)
converts decimal integer number i into octal number system and returns
that octal number as a string
int intValue()
converts integer object into primitive int type value. This is called
'unboxing'.
513
Wrapper Classes
Long Class
The Long contains a primitive long type data
Constructors
Long(long num)
Long object can be created
Long obj=new Long(1230044);
Long(String str)
Create Long object by converting a string that contains a long number
Strung str=“1230044”;
Long obj=new Long(str);
514
Wrapper Classes
Important methods of Long class
int compareTo(Long obj)
Compares the numeric value of two Long class objects and return 0, -ve
value, or +ve value
boolean equals(Object obj)
Compares the Long object with any other object obj. If both have same
content, then it returns true otherwise false
static long parseLong(String str)
Return long equivalent of the string str
String toString()
Converts Long object into String Object
static Long valueOf(String str)
Converts a string str that contains some long number into Long object
515
Wrapper Classes
Math Class
TheclassMathcontainsmethodsforperformingbasicnumeric
operations,suchastheelementaryexponential,squarerootetc..
AllthemethodsofMathclassarestatic
ImportantmethodsofMathclass
staticdoublesin(doublearg)
returnthesinevalueofthearg
Math.sin(0.5);//0.4794255
staticdoublecos(doublearg)
returnthecosinevalueofthearg
Math.cos(0.5);//0.87758256189
staticdoubletan(doublearg)
returnthetangetvalueofthearg
Math.tan(0.5);//0.54630248
516
Wrapper Classes
static double log(double arg)
return the natural logarithm value of the arg
Math.log(0.5);//-0.69314718055
static double log10(double arg)
return the base10 algorithm value of the arg
Math.log10(0.5);//-0.30102999566
static double pow(double x, double n)
return the x to the power of the n value
Math.pow(5,3);//125.0
static double sqrt(double arg)
return the square root of the arg
Math.sqrt(25);//5.0
517
Wrapper Classes
static double toRadians(double angle)
converts the given value in degree into radians.
Math.toRadians(180);//3.141592653
static double to Degree(double angle)
converts angle in radians into degree.
Math.toDegree(3.14159);//179.9998479
520
Wrapper Classes
Double class
The Double class wraps a value of the primitive type double in an object.
The double class object contains a double type field that stores a
primitive double number
Constructors
Double (double num)
Double object can be created
double d=12.1223;
Double obj=new Double(d);
Double (String str)
This constructor is useful to create a Double object by converting a string
that contains a double number
String str=“12.1223”;
Double obj=new Double(str);
521
Wrapper Classes
Important methods of Double class
int compareTo(Double obj)
Compares the numeric value of two Double class objects and return 0, -
ve value, or +ve value
boolean equals(Object obj)
Compares the Double object with any other object obj. If both have same
content, then it returns true otherwise false
static double parseDouble(String str)
Return double equivalent of the string str
String toString()
Converts Double object into String Object
static Double valueOf(String str)
Converts a string str that contains some double number into Double
object
522
Wrapper Classes
Float class
The Float class wraps a value of the primitive type float in an object. The
Float class object contains a float type field that stores a primitive float
number
Constructors
Float (float num)
Float object can be created
float f=12.122f;
Float obj=new Float(f);
Float (String str)
This constructor is useful to create a Float object by converting a string
that contains a float number
String str=“12.122f”;
Float obj=new Float(str);
523
Wrapper Classes
Important methods of Float class
int compareTo(Float obj)
Compares the numeric value of two Float class objects and return 0, -ve
value, or +ve value
boolean equals(Object obj)
Compares the Float object with any other object obj. If both have same
content, then it returns true otherwise false
static float parseFloat(String str)
Return float equivalent of the string str
String toString()
Converts Float object into String Object
static Float valueOf(String str)
Converts a string str that contains some float number into Float object
524
Wrapper Classes
Boolean class
The Boolean class wraps a value of the primitive type boolean in an
object. The Boolean class object contains a boolean type field that
stores a primitive boolean
Constructors
Boolean (boolean value)
Boolean object can be created
Boolean obj=new Boolean(true);
Boolean (String str)
This constructor is useful to create a Boolean object by converting a
string that contains a boolean value
String str=“false”;
Boolean obj=new Boolean(str);
525
Wrapper Classes
Important methods of Boolean class
int compareTo(Boolean obj)
Compares the value of two Boolean class objects and return 0, -ve value,
or +ve value
boolean equals(Object obj)
Compares the Boolean object with any other object obj. If both have
same content, then it returns true otherwise false
static boolean parseBoolean(String str)
Return boolean equivalent of the string str
String toString()
Converts Boolean object into String Object
static Boolean valueOf(String str)
Converts a string str that contains some boolean value into Boolean
object
526