Anda di halaman 1dari 45

Durga Software Solutions - Core Java by Durga Sir

LanguageFundamentals:(session1)

AGENDAforlanguagefundamentals

Identifiers ReservedWords DataTypes Literals

Arrays TypesofVariables Varargmethods Mainmethod

Commandlinearguments Javacodingstandards

Identifiers:Aclassname,amethodname,avariablenameoralabelname.Anameinjava
programiscalledidentifierwhichcanbeusedforidentificationpurpose.
Ex:classTest
{publicstaticvoidmain(String[]args)
{intx=10}}
RulesfordefiningJavaidentifiers:
BOnlyallowedcharactersinjavaidentifiersareatoz,AtoZ,09$and_.Ifweuseanyother
character,wellgetcompiletimeerror.
Ex:total_number,total#invalid
Identifierscantstartwithadigit.
total123valid,123totalinvalid
Javaidentifiersarecasesensitive.Ofcourse,Javalanguageitselfistreatedascasesensitive
programminglanguage
IntNumber=10
IntNUMber=10
IntnuMBER=10//wecandifferentiatewithrespecttocase.
Thereisnolengthlimitforjavaidentifiers.Butitisnotrecommendedtotaketoolengthy
identifiers.RememberexampleperformedbySatyasir
Reservedkeywordscannotbeusedasidentifiers.Ex.intif=20//invalid
Predefinedclassnamesandpredefinedinterfacenamescanbeusedasidentifiernames
Ex:classTest Ex:classTest
{ {
publicstaticvoidmain(String[]args) publicstaticvoidmain(String[]args)
{ {
intString=888 intRunnable=999
System.out.println(String) System.out.println(Runnable)
}} }}
Allpredefinedjavaclassnamesandinterfacenames,wecanuseasidentifiers.Eventhoughitis
valid,butitisnotagoodprogrammingpracticebecause,itreducesreadability
Test:Whichofthefollowingarevalidjavaidentifiers.
total_number,total#,123total,total123,Ca$h,_$_$_$,all@hands,java2share,Integer,Int,int
Valid:total_number,total123,ca$h,_$_$_$,java2share,Integer,Int

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

ReservedWords:InJava,somewordsarereservedtorepresentsomemeaningorfunctionality.
Suchtypeofwordsarecalledreservedwords.InJava,thereare53reservedwords.


Keywordsfordatatypes
byte short int long float double boolean char
Keywordsforflowcontrol
if else switch case default while do for break continue return
Keywordsformodifiers
public private protected static final abstract

synchronized native strictfp transient volatile default


KeywordsforExceptionHandling
try catch throw throws finally assert
Classrelatedkeywords
class interface extends implements package import
Objectrelatedkeywords
new instanceof super this

Voidreturntypekeyword:inJava,returntypeismandatory.Ifamethodwontreturnanything,
thenwehavetodeclarethatmethodwithvoidreturntype.ButinClanguage,returntypeis
optionalanddefaultreturntypeisint.
Goto:UsageofgotocreatedseveralproblemsinoldlanguagesandhenceSunpeoplebanned
thiskeywordinJava.
Const:Usefinalinsteadofconst.
Gotoandconstareunusedkeywordsandifwetrytouse,wewillgetcompiletimeerror.
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

ReservedLiterals:trueandfalsearevaluesforbooleandatatypes.Nullisthedefaultvaluefor
objectreference.
Enumkeyword:Wecanuseenumtodefineagroupofnamedconstants.
Enummonth Enumbeer
{Jan,feb,...dec} {Kf,kc,rc,fo}
Conclusions:
1 All53reservedwordsinJavacontainsonlylowercasealphabetsymbols.
2. InJava,wehaveonlynewkeywordandthereisnodeletekeywordbecause,destruction
ofuselessobjectsistheresponsibilityofgarbagecollector.
3. ThefollowingarenewkeywordsinJava.
strictfp,assert,enum(1.5ver)
strictfpbutnotStrictfp
instanceofbutnotInstanceof
extendsbutnotExtends
importbutnotimports
constbutnotConstant
Test:WhichofthefollowinglistcontainsonlyJavareservedwords?
1. new,delete//deleteisnotapartofjava
2. goto,constant//constantisinvalidconst
3. break,continue,return,exit//exitisamethod
4. final,finally,finalize//finalizeisnotthere
5. throw,throws,thrown//thrownisincorrect
6. notify,notifyAll
7. implements,extends,imports//importsisnotthere
8. sizeof,instanceof//sizeof
9. instanceOf,StrictFp//strictfpandinstanceof
10. byte,short,Int//Intisinvalid
11. Noneoftheabove.
Ans:11(noneoftheabove)
Test:whichofthefollowingarejavareservedwords?
1. public
2. static
3. void
4. main
5. string
6. args
7. Noneoftheabove
Ans:public,static,void

memorizeallthekeywords
happylearning
LanguageFundamentals:(session2)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir


Datatypes:Stronglytypedprogramminglanguage(typecheckingisveryimportant).InJava,
everyvariableandeveryexpressionhassometype.Eachandeverydatatypeisclearlydefined.
Everyassignmentshouldbecheckedbycompilerfortypecompatibility.Becauseofabove
reasons,wecanconcludeJavalanguageisstronglytypedprogramminglanguage.
Test:J avaispureobjectorientedprogramminglanguage?
Javaisnotconsideredaspureobjectorientedprogramminglanguagebecause,severaloop
featuresarenotsatisfiedbyJava.(likeoperatoroverloading,andmultipleinheritanceetc).
Moreover,weredependingonprimitivedatatypeswhicharenonobjects.Whencomparedwith
oldlanguages,yeswecansayJavaisobjectoriented.But,ifwetakeJavaaloneinto
consideration,

PrimitiveDatatypes:

ExceptBooleanandChar,remainingdatatypesareconsideredassigneddatatypesbecausewe
canrepresentboththepositiveandnegativenumbers.
Charx=a(meaningless)
Booleany=false(meaningless)
Byte:
1. Sizeis1byte(8bits)
2. Maxvalue:+127
3. MinValue:128
4. Range:128to+127

Signbit 26 25 24 23 22 21 20
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

msb 64 32 16 8 4 2 1

Themostsignificantbitactsassignbit.0meanspositivenumber1meansnegativenumber.
Positivenumberswillberepresenteddirectlyinthememorywhereasnegativenumberswillbe
representedin2scomplementform.
Test:
1. ifideclarebyteb=128,whatcompiletimeerrordoiget?
A. Possiblelossofprecisionfound:int,requiredbyte.
2. Byteb=10.5
A. possiblelossofprecision.Found:double.Requiredbyte.
3. Byteb=true
A. incompatibletypes.found:Booleanrequired:byte
4. Byteb=durga
A. incompatibletypefound:java.lang.String,required:byte.

Byteisthebestchoiceifwewanttohandledataintermsofstreamseitherfromthefileorfrom
thenetwork(filesupportedformornetworksupportedformisbyte)

Short:ThisisthemostrarelyuseddatatypeinJava.
1. Sizeis2byte(16bits)
2. Maxvalue:+32767
3. MinValue:32768
4. Range:32768to+32767

msb 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20


16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

Test:
1. ifideclareshortb=32768,whatcompiletimeerrordoiget?
A. Possiblelossofprecisionfound:int,requiredshort.
2. short=10.5
A. possiblelossofprecision.Found:double.Requiredshort.
3. Shortb=true
A. incompatibletypes.found:Booleanrequired:short
4. Shortb=durga
A. incompatibletypefound:String,required:short.
Shortdatatypeisbestsuitablefor16bitprocessorslike8085.But,theseprocessorsare
completelyoutdatedandhencecorrespondingshortdatatypesisalsooutdateddatatype.

Int:ThemostcommonlyuseddatatypeinJavaisint.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

1. Sizeis4byte(32bits)
2. Maxvalue:231 1
3. MinValue:231
4. Range:231to231
1{2147483648to2147483647}

msb 230 229 228 227 226 225 224 223 222 221 220 219 218 217 216

215 214 213 212 211 210 29 28 27 26 25 24 23 22 21 20

Test:
1. ifideclareintb=2147483648,whatcompiletimeerrordoiget?
A. Integernumbertoolarge.//alert:theerrorisnotPLP
2. intb=2147483648L
A. possiblelossofprecision.Found:long.Requiredint
3. intx=true
A. incompatibletypes.found:Booleanrequired:int
4. intb=durga
A. incompatibletypefound:String,required:int.






















LanguageFundamentals:(session3)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

LongDatatype:Sometimesintmaynotbeenoughtoholdbigvalues.Then,weshouldgofor
longtype.
Ex.1:Theamountofdistancetravelledbylightin1000days.Toholdthisvalue,intmaynotbe
enough.Weshouldgoforlongdatatype.
Ex.longl=126000*60*60*24*1000miles
Ex.2:Thenumberofcharacterspresentinabigfilemayexceedintrange.Hence,thereturntype
ofthelengthmethodislongbutnotint.
Longl=f.length()
1. Sizeis8byte(64bits)
2. Range:263to263
1


Note:Alltheabovedatatypes(byte,short,int,long)aremeantforrepresentingintegralvalues.If
wewanttorepresentfloatingpointvalues,thenweshouldgoforfloatingpointdatatypes.


Ifwewant5to6decimalplacesofaccuracy,thenweshouldgoforfloat.Ifwewant14to15
decimalplacesofaccuracy,thenweshouldgofordouble.
Floatfollowssingleprecision.Doublefollowsdoubleprecision.

BooleanDataType:

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

InJava,thesizeofbooleanisnotapplicable.(VirtualMachinedependant)
Range:Notapplicable(butallowedvaluesaretrue/false)

Booleanb=true
//validdeclaration
Booleanb=0//invaliddeclarationcompilerthrowserrorincompatibletypefound:intrequired:
boolean
Booleanb=True//cannotfindsymbolVariableTrue.
Booleanb=True//incompatibletypejava.lang.string.Requiredboolean.

intx=0 while(1)
if(x) {System.out.println(Hello)}
{System.out.println(Hello)} /*ThesearevalidinCandC++Butnot
Else{System.out.println(hi)} acceptableinjava*/

Error:incompatibletypes.Found:int,required:boolean
CharDataType:OldlanguageslikeC/C++areASCIIcodebasedandthenumberofdifferent
allowedASCIIcodecharactersare<=256.Torepresentthese256characters,8bitsareenough.
Hence,thesizeofcharinoldlanguagesis1byte.ButJavaisunicodebasedandthenumberof
differentunicodecharactersaregreaterthan256andlessthanorequalto65536.Torepresent
thesemanycharacters8bitsmaynotenoughcompulsoryweshouldgofor16bits.Hencethe
sizeofcharinJavais2bytes.
Size:2Byte
Range:0to65535
SummaryofJavaPrimitivedatatypes:
DataType Size Range WrapperClass DefaultValue

byte 1byte 27to27


1 Byte 0

short 2bytes 215to215


1 Short 0

int 4bytes 231to231


1 Integer 0

long 8bytes 263to263


1 long 0

float 4bytes 3.4e38to3.4e38 float 0.0

double 8bytes 1.7e308to1.7e308 double 0.0

boolean NA NAbutallowed boolean False


valuesaretrue/false

char 2bytes 0to65535 Character 0(represents


spacecharacter)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

NOTE:NULLISADEFAULTVALUEFOROBJECTREFERENCE.NULLISNOT
APPLICABLEFORTHEPRIMITIVEDATATYPESSO,DONTASSIGNNULLTO
PRIMITIVEDATATYPESEVENTOBOOLEAN.IFWEUSEFORPRIMITIVE,WEWILLGET
COMPILETIMEERROR.
CHARCH=NULL//COMPILETIMEERROR:INCOMPATIBLETYPEFOUNDNULLTYPE
REQUIREDCHAR

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

LanguageFundamentals:(session4)

Literals:Aconstantvaluewhichcanbeassignedtothevariableiscalledaliteral.
Ex:intx=10
int x = 10

Datatype/keyword Nameof Assignmentoperator Constantvalue/literal


variable/identifier
Intisdatatype/keyword,xisthenameofvariableoridentifierandconstantvalueorliteralis10
HowmanywayscanwespecifyIntegralliterals?
ForIntegraldatatypesintshortbytelong,wecanspecifyliteralvalueinthefollowingways.
a) Decimalliterals:intx=10(alloweddigits09)
b) Octalform:intx=010(numberprefixedwith0,itsoctal)(alloweddigits07)
c) Hexadecimal:intx=0X10(prefixedwith0Xzerox)(alloweddigits09,af)forextra
digits,wecanuseeitherofthecase.Casesensitiveisnotruledhere.Thisisoneofvery
fewareaswhereJavaisnotcasesensitive.
Theseareonlypossiblewaystospecifyliteralvaluesforintegraldatatypes
Test:Whichofthefollowingdeclarationsarevalid?
1. intx=10
2. intx=0786//compilerraisesanerror.Integernumbertoolarge.Why?Cosittreatsas
octal.Octalalloweddigitsare0to7
3. Intx=0777//valid.Octalalloweddigitsarefrom0to7
4. Intx=0XFACE//validhexadecimal
5. Intx=0XBEEF//validhexadecimal
6. Intx=0XBEER//invalidhexadecimal
Ans:1,3,4,5,

ClassTest
{
publicstaticvoidmain(String[]args)
{
intx=10
inty=010
intz=0X10//Programmerhasthefreedomtochooseineitherdecimaloroctalorhexadecimal.
System.out.println(x+...+y+...+z)//JVMreturnsallthevaluesindecimalform.
}
}
Output:
10...8...16

Bydefault,everyintegralliteralisofinttype.But,wecanspecifyexplicitlyaslongtypebysuffixed
withlorL
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Ex:
Intx=10
Longl=10l
Intx=10l//compilerthrowsanerror.Possiblelossofprecision.Foundlong,requiredint.
Longl=10
Bydefault,everyintegralliteralisofinttype.Thereisnodirectwaytospecifybyteandshort
literalsexplicitly.But,indirectly,wecanspecify.
Byteb=10
Byteb=127
Byteb=128//error:possiblelossofprecision.Foundint,requiredbyte.
Shorts=32767
Shorts=32768//plpfoundint,requiredshort

Thereisnodirectwaytospecifybyteandshortliteralsexplicitly.Butindirectlywecanspecify.
Wheneverweareassigningintegralliteraltothebytevariableandifthevaluewithintherangeof
bytethenthecompilertreatsitautomaticallyasbyteliteral.Similarlyshortliteralalso.

Floatingpointliterals:
Bydefault,everyfloatingpointliteralisofdoubletype.Andhence,wecantassigndirectlytothe
floatvariable.But,wecanspecifyfloatingpointliteralasfloattypebysuffixedwithforF
floatf=123.456//CE:PLPfounddouble,requiredfloat
floatf=123.456F//valid
Doubled=123.456//valid
WecanspecifyexplicitlyfloatingpointliteralasdoubletypebysuffixedwithdorD.Ofcourse,this
conventionisnotrequired.
Doubled=122.34456D//notrequired
Floatf=231.456D//CE:PLPfounddouble,requiredfloat.
Test:
Doubled=123.456//valid
Doubled=0123.456//treatedasdecimalonly.Butnotoctalliteral.
Doubled=0X123.456//CEmalformedfloatingpointliteral.
Wecanspecifyfloatingpointliteralsonlyindecimalformandwecantspecifyinoctaland
hexadecimalforms.

Doubled=0786//CE:integernumbertoolarge
Doubled=0XFACE//valid
Wecanassignintegralliteraldirectlytofloatingpointvariablesandthatintegralliteralcanbe
specifiedeitherindecimaloroctalorhexadecimalforms.
Ex:doubled=0786//CEintegernumbertoolarge
Doubled=0XFACE//valid
Doubled=0786.0//valid
Doubled=0XFace.0//malformed
Doubled=10
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Doubled=0777
Wecantassignfloatingpointliteralstointegraltypes.
Doubled=10
Intx=10.0//plpfounddouble,requiredint

Wecanspecifyfloatingpointliteraleveninexponentialform(scientificnotation)
Doubled=1.2e3
sop(d)1200.0
Floatf=1.2e3//PLPfounddouble,requiredfloat
Floatf=1.2e3F
BooleanLiterals:Theonlyallowedvaluesforbooleandatatypearetrue/false.
Booleanb=true
Booleanb=0incompatibletypesfoundintrequiredboolean
Booleanb=Truecannotfindsymbolvariabletruelocationclasstest
Booleanb=Trueincompatibletypesfoundjava.lang.stringrequiredboolean.

Intx=0 while(1)
if(x)//incompatibletypes. {
{ System.out.println(Hello)
System.out.println(Hello) }
} /*ThesearevalidinCandC++Butnot
else acceptableinjava*/
{
System.out.println(hi)
}

Error:incompatibletypes.Found:int,required:boolean

LanguageFundamentals:(session5)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

CharacterLiterals:
Wecanspecifycharliteralsassinglecharacterwithinsinglequotes
charch=a
Charch=a//CEcannotfindsymbolSymbol:variablea,location:classtest
Charch=a//CEincompatibletypesfound:java.lang.stringrequiredclass
Charch=ab//CEunclosedcharliteral.Unclosedcharliteral.Notastatement.

Wecanspecifycharliteralasintegralliteralwhichrepresentsunicodevalueofthecharacterand
thatintegralcanbespecifiedeitherindecimaloroctalorhexadecimalforms.Butallowedrangeis
0to65535.
Ex:charch=97
SOP(ch)//a
Charch=0XFace
Charch=0777
Charch=65535
Charch=65536//PLPfoundint,requiredchar.
www.unicode.org//wecangetcharvalues..
Wecanrepresentcharliteralinunicoderepresentationwhichisnothingbut\uXXXX4digit
hexadecimalnumber.
Ex:charch=\u0061
sop(ch)//a
Everyescapecharacterisavalidcharliteral.
Ex:charch=\n\
Charch=\t
Charch=\m//invalid
Escapecharacteranddescription
\n Newline

\t Horizontaltab

\r Carriagereturn

\b Backspace

\f Formfeed

\ Singlequote

\ Doublequote

\\ Backslash

Whichofthefollowingarevalid?
Charch=65536//invalid

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Charch=0XBeer//invalid
Charch=\uface//invalidsinglequotes
Charch=\ubeef//valid
Charch=\m//invalid
Charch=\iface//invalid
StringLiteral:Anysequenceofcharacterswithindoublequotesistreatedasstringliteral.
Ex:Strings=durga
2enhancements
Binaryliterals:Forintegraldatatypesuntil1.6version,wecanspecifyliteralvalueinthe
followingways.
Decimalform,octal,hexadecimal.Butfrom1.7versiononwards,wecanspecifyliteralvalueeven
inbinaryformalso.Alloweddigitsare0and1.Literalvalueshouldbeprefixedwith0bor0B.
Ex.intx=0b1111
sop(x)//valueis15.
Usageof_symbolinnumericliterals:From1.7versiononwards,wecanuseunderscore
symbolbetweendigitsofnumericliteral.
Ex:doubled=1234567.890
Canbewrittenas
Doubled=123_4_567.8_9_0
Themainadvantageofthisapproachis,readabilityofthecodewillbeimproved.Atthetimeof
compilation,theseunderscoresymbolswillberemovedautomatically.Hence,aftercompilation,
theabovelineswillbecomedoubled=1234567.890
Ex:doubed=1__3__44__55_66_8.57
Wecanusemorethan1underscorealsobetweenthedigits.
Doubled=_1_23_456_4.789//invalid
Doubled=1_3_345_6._7_8_9//invalid
Doubled=1_3_4_.567_//invalid
Wecanuseunderscoreonlybetweenthedigits.Ifweareusinganywhere,weregoingtoget
compiletimeerror


8bytelongvaluewecanassignto4bytefloatvariablebecause,botharefollowingdifferent
memoryrepresentationsinternally.
Floatf=10LSoP(f)//10.0
LanguageFundamentals:(session6)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Arrays
1. Introduction
2. ArrayDeclaration
3. ArrayCreation
4. ArrayInitialization
5. ArrayDeclarationCreationandInitializationinasingleline
6. Lengthvslength()
7. Anonymousarrays
8. Arrayelementassignments
9. Arrayvariableassignments

Introduction:Anarrayisanindexedcollectionoffixednumberofhomogeneousdataelements.
Themainadvantageofarraysis,wecanrepresenthugenumberofvaluesbyusingsingle
variablesothatreadabilityofthecodewillbeimproved.But,themaindisadvantageofarraysis
theyarefixedinsize.I.e.,oncewecreateanarray,thereisnochanceofincreasingordecreasing
thesizebasedonourrequirement.Hence,tousearraysconcept,compulsoryweshouldknow
thesizeinadvancewhichmaynotbepossiblealways.
Arraydeclaration:
Onedimensionalarraydeclaration:
int[]x//recommendedbecausenameisclearlyseparatedfromtype.
Int[]x
Intx[]

Atthetimeofdeclaration,wecantspecifythesize.Otherwise,wewillgetcompiletimeerror.
Int[6]x//invaliddontspecifythesizeatdeclarationpoint
int[]x
Twodimensionalarray:
int[][]x
Int[][]x
Intx[][]
int[][]x
Int[]x[]
Int[]x[]

Test:
Whichofthefollowingarevalid?
Int[]a,ba,b1
Int[]a[],b//a2b1
Int[]a[],b[]//a2b2
Int[][]a,b//a2b2
Int[][]a,b[]//a2b3

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Int[][]a,[]b//CEIfwewanttospecifydimensionbeforethevariable,thefacilityisapplicableonly
forfirstvariableinadeclaration.Ifwearetryingtoapplyforremainingvariables,wewillget
compiletimeerror.
Int[][]a,[]b,[]cvalidforabutinvalidforbandc.

3dimensionalarraydeclaration:
Int[][][]a
Int[][][]a
Inta[][][]
Int[][][]a
int[]a[][]
Int[][]a[]
Int[][][]a
Int[][]a[]
int[]a[][]

ArrayCreation:Everyarrayinjavaisanobjectonly.Hencewecancreatearraysbyusingnew
operator.
Ex:int[]a=newint[3]
Foreveryarraytype,correspondingclassesareavailableandtheseclassesarepartofJava
languageandnotavailabletotheprogrammerlevel.
Ex:int[]a=newint[3]
System.out.println(a.getclass().getName())//[ithisistheclassnameofarrayinJava.

ArrayType Correspondingclassname

int[] [I

int[][] [[I

double[] [D

short[] [S

byte[] [B

boolean[] [Z
Atthetimeofarraycreation,compulsoryweshouldspecifythesize.Otherwise,wewillget
compiletimeerror.
Int[]x=newint[]//invalidcompilergiveserror.
Int[]x=newint[6]//valid
Int[]x=newint[0]//Itislegaltohaveanarraywithsize0inJava.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Int[]x=newint[3]//Nocompiletimeerror.Because,JVMneedsonlyanintegervalue.ButIfwe
aretryingtospecifyarraysizewithsomenegativeintvalue,thenwewillgetruntimeexception
sayingNegativeArraySizeException
Tospecifyarraysize,thealloweddatatypesare,byte,short,charandint.Ifwearetryingto
specifyanyothertype,thenwewillgetcompiletimeerror.
Int[]x=newint[10]
Int[]x=newint[a]
Byteb=20
Int[]x=newint[b]
Shorts=30
Int[]x=newint[s]
Int[]x=newint[10L]//CompilererrorPLPfound:longrequired:int.

Note:ThemaximumarraysizeallowedinJavais:2147483647(rangeofint)whichisthe
maximumvalueofintdatatype.
Int[]x=newint[2147483647]
Int[]x=newint[2147483648]//CEIntegernumbertoolarge.
Eveninthefirstcase,wemaygetruntimeexceptionifsufficientheapmemorynotavailable.

TwoDimensionalArrayCreation
InJava,twodimensionalarrayisnotimplementedbyusingmatrixstylerepresentation.SUN
peoplefollowedarrayofarraysapproachformultidimensionalarraycreation.Themain
advantageofthisapproachisimprovedmemoryutilization.
Traditionalmatrixstyle:
Students1 30 12 5 16

Students2 30

Students3 28

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Students4 45 56

InJava,arrayofarraysapproachcanbeusedtoimprovememoryutilization.
Ex:


MemorystructureandcorrespondingJavacode.Wehavetospecifybasesizeandtherestcanbe
specifiedinlaterstatements.

Ex.2:

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir


Tocreateanarraywithvariablesizes:
Int[][][]x=newint[2][][]
X[0]=newint[3][]
X[0][0]=newint[1]
X[0][1]=newint[2]
x[0][2]=newint[3]
X[1]=newint[2][2]
Test:Whichofthefollowingarraydeclarationsarevalid?
1. Int[]a=newint[]//invalidbasesizeisnotspecified
2. int[]a=newint[3]//valid
3. Int[][]a=newint[][]//invalidbasesizenotspecified
4. Int[][]a=newint[3][]//valid
5. Int[][]a=newint[][4]//invalidinvalidbasesize
6. Int[][]a=newint[3][4]//valid
7. Int[][][]a=newint[3][4][5]//valid
8. Int[][][]a=newint[3][4][]//valid
9. Int[][][]a=newint[3][][5]//invalid
10. Int[][][]a=newint[][4][5]//invalid
Ans:2,4,6,7,8,
Arrayinitialization:

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Oncewecreateanarray,everyelementbydefaultinitializedwithdefaultvalues.
Ex:int[]x=newint[3]
System.out.println(x)Output:[I@3e25a5(classnameandHashcharcode)
System.out.println(x[0])//outputis0becauseeveryelementbydefaultinitializedwith0.
Note:Wheneverwearetryingtoprintanyreferencevariable,internallytostringmethodwillbe
calledwhichisimplementedtoreturnthestringinthefollowingform.
classname@Hashcodeinhexadecimalform.


int[][]x=newint[2][3]
System.out.println(x)[[I@3e265892
System.out.println(x[0])[i@19821f
System.out.println(x[0][0])0

Example3:
Int[][]x=newint[2][]
System.out.println(x)//Output[[I@3e25a5
System.out.println(x[0])//Null
System.out.println(x[0][0])//Exception.Nullpointerexception.


Note:Ifwearetryingtoperformanyoperationonnull,thenwewillgetruntimeexceptionsaying
nullpointerexception.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Oncewecreateanarray,everyarrayelementbydefaultinitializedwithdefaultvalues.Thedefault
valueis0.Ifwearenotsatisfiedwithdefaultvalues,thenwecanoverridethesevalueswithour
customizedvalues.

Int[]x=newint[6]
X[0]=10
X[1]=20
X[2]=30
X[3]=40
X[4]=50
X[5]=60
X[6]=70//RE:arrayindexoutofboundsexception
X[7]=80//RE:ArrayIndexOutOfBoundsException
X[2.8]=90CE:PLP,founddouble,requiredint
Note:Ifwearetryingtoaccessarrayelementwithoutofrangeindex(eitherpositivevalueor
negativeintvalue)thenwewillgetruntimeexceptionsayingArrayIndexOutOfBoundsException.

Arraydeclarationcreationandinitializationinasingleline:
Wecandeclare,createandinitializeanarrayinasingleline(shortcutrepresentation)
Int[]x
x=newint[3]
X[0]=10
X[1]=20
X[2]=30
Allthiscodecanbewritteninsinglelineas
Int[]x={10,20,30}
Char[]s={a,e,i,o,u}
String[]S={hello,world,!!!}

Wecanextendthisshortcutformultidimensionalarraysalso.
Int[][]x={{10,20},{30,40,50}}
Int[][][]x={{{10,20,30},{40,50,60}},{{70,80},{90,100,110}}}
System.out.println(x[0][1][2])//60
System.out.println(x[1][0][1])//80
System.out.println(x[2][0][0])//RE:AIOOBE
System.out.println(x[1][2][0])//RE:AIOOBE
System.out.println(x[1][1][1])100
System.out.println(x[2][1][1])REAIOOBE

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir


Ifwewanttousethisshortcut,compulsoryweshouldperformallactivitiesinasingleline.Ifwe
aretryingtodivideintomultiplelines,thenwewillgetcompiletimeerror.
Ex:
int[]x={10,20,30}
Int[]x
x={10,20,30}//CEillegalstartofexpression

LengthVsLength():
Length:Lengthisafinalvariableapplicableforarrays.Lengthvariablerepresentsthesizeofthe
array.
Ex:int[]x=newint[6]
System.out.println(x.length())CE:cannotfindsymbol.Symbol:methodlength()locationclassint[]
System.out.println(x.length)//output6
Lengthmethodisafinalmethodapplicableforstringobjects.Lengthmethodreturnsnumberof
characterspresentinthestring.
Ex:Strings=durga
System.out.println(s.length)CE:Cannotfindsymbol.Symbol:variablelengthlocation:Class
Java.string
System.out.println(s.length())//output5
Note:Lengthvariableisapplicableforarraysbutnotforstringobjects.Whereas,lengthmethod
applicableforstringobjectsbutnotforarrays.
Ex:String[]S={A,AA,AAA}
System.out.println(s.length)//3
System.out.println(s.length())//Cannotfindsymbolmethodlengthlocationclassstring
System.out.println(s[0].length)//Cannotfindsymbolvariablelengthlocationclass.java.l.string
System.out.println(s[0].length)//1

InMultidimensionalarrays,lengthvariablerepresentsonlybasesizebutnottotalsize.
Ex:int[][]x=newint[6][3]
System.out.println(x.length)//6
System.out.println(x[0].length)//output3
Thereisnodirectwaytofindtotallengthofmultidimensionalarray.Butindirectly,wecanfindas
follows.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

X[0].length+x[1].length+X[2].length+x[3].length+X[4].length+x[5].length

AnonymousArrays:Sometimeswecandeclareanarraywithoutaname.Suchtypeof
namelessarraysarecalledanonymousarrays.
Themainpurposeofanonymousarraysisjustforinstantuse(onetimeusage).
Wecancreateanonymousarrayasfollows:
Newint[]{10,20,30,40}//Wecannotspecifythesizewhilecreatinganonymousarrays.
Whilecreatinganonymousarrays,wecantspecifythesize.Otherwise,wewillgetcompiletime
error.
Newin[3]{10,20,30}//invalid
Newint[]{10,20,30}itselfisvalid.
Wecancreatemultidimensionalanonymousarraysalso.
Newint[][]{{10,20},{30,40,50}}
Basedonourrequirement,wecangivethenameforanonymousarray.Thenitisnolonger
anonymous.
Int[]x=newint[]{20,30,40}
Example:
ClassTest
{
Publicstaticvoidmain(String[]args)
{
Sum(newint[]{10,20,30,40})
}
Publicstaticvoidsum(int[]x)
{
Inttotal=0
For(intX1:x)
{
Total=total+1
}
System.out.println(Thesumis:+total)
}
}
Intheaboveexample,justtocallsomemethod,werequiredanarray.But,aftercompletingsome
methodcall,wearenotusingthatarrayanymore.Hence,forthisonetimerequirement,
anonymousarrayisthebestchoice.

ArrayElementAssignments:
Case1:Inthecaseofprimitivetypearrays,asarrayelementswecanprovideanytypewhich
canbeimplicitlypromotedtodeclaredtype.
Int[]x=newint[5]
X[0]=10
X[1]=a
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Byteb=20
X[2]=b
Shorts=10
X[3]=s
X[4]=10LCEPLPfound:longrequired:int

Ex.2:Inthecaseoffloattypearrays,thealloweddatatypesarebyte,short,char,intlongand
float.

Case2:Inthecaseofobjecttypearrays,asarrayelements,wecanprovideeitherdeclaredtype
objectsoritschildclassobjects.
Ex:object[]a=newObject[10]
A[0]=newObject()
A[1]=newString(durga)
A[2]=newInteger(10)//Thisexampleisperfectlyvalid

AbstractClasstypearrays:
Thisexampleiswrong.Becausecompileracceptsonlynumerictypes[BSILFD]
Ex:Number[]n=newNumber[10]
N[0]=newInteger(10)
N[1]=newDouble(10.5)
N[2]=newString(durga)//incompatibletypesfoundJ.L.stringrequiredJLnumber

Case3:Forinterfacetypearrays,asarrayelements,itsimplementationclassobjectsare
allowed.
Ex:Runnable[]r=newRunnable[10]
R[0]=newThread[]
R[1]=newstring(durga)//CEincompatibletypesfound:JLstring,requiredJLrunnable.

ArrayType Allowedelementtypes

Primitivearrays Arraytypewhichcanbeimplicitlypromotedto
declaredtype

Objecttypearrays Eitherdeclaredtypeoritschildclassobjects

Abstractclasstypearrays Itschildclassobjectsareallowed

Interfacetypearrays Itsimplementationclassobjectsareallowed

ArrayVariableassignments:
Case1:Elementlevelpromotionsarenotapplicableatarraylevel.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Ex:charelementcanbepromotedtointtype.Whereas,chararraycannotbepromotedtoint
array.
Ex:int[]x={10,20,30,40}
Char[]ch={a,b,c,d}
Int[]b=x
Int[]c=ch//incompatibletypes.Foundchar[]requiredintclasschar[][cintclass[i

Q.Whichofthefollowingpromotionswillbeperformedautomatically?
1. CharTOInt
2. Char[]toint[]//invalid
3. Inttodouble
4. Int[]todouble[]//invalid
5. Floattoint//invalid
6. Float[]toint[]//invalid
7. Stringtoobject
8. String[]toobject[]
Butinthecaseofobjecttypearrays,childclasstypearraycanbepromotedtoparentclasstype
array.
StringtoObjectandstring[]toobject[]

Strings={a,b,c}
Object[]a=s
Thisisperfectlyvalid..Becausethechildclasstypearraycanbepromotedtoparentclasstype
array.

Case2:
Int[]a={10,20,30,40,50,60}
Int[]b={70,80}
A=b
B=a

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Wheneverweareassigningonearraytoanotherarray,internalelementswontbecopied.Just
referencevariableswillbereassigned.
int[][]a=newint[3][]
A[0]=newint[4][3]

Wheneverweareassigningonearraytoanotherarray,thedimensionsmustbematched.E
Ex:intheplaceofonedimensionalintarray,weshouldprovide1dimensionalarrayonly.Ifweare
tryingtoprovideanyotherdimension,thenwewillgetcompiletimeerror
Int[][]a=newint[3][]
A[0]=newint[4][5]CEincompatibletypesfoundint[][]requiredint[]
A[0]=10//CEincompatibletypesfound.Intrequiredint[]
A[0]=newint[2]
Wheneverweareassigningonearraytoanotherarray,bothdimensionsandtypesmustbe
matchedbut,sizesarenotrequiredtomatch.

Ex.1:
ClassTest
{
PSVM(String[]args)
{forint(i=0i<=args.lengthi++)
{SOP(args[i])
}}
Outputs:
Javatestabc
abc(RE:AIOOBE)
Javatestab
ab(RE:AIOOBE)
Javatest
REAIOOBE

Ex:2
ClassTest
{
Publicstaticvoidmain(string[]args)
{
String[]argh={x,y,z}
Args=argh
For(Strings:args)
{
System.out.println(s)
}}}
Outputs:
Javatestabcoutput:xyz
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

JavatestABOutputsxyz
JavaTestoutputsxyz

Example3
1. Int[][]a=newint[4][3]
2. A[0]=newint[4]
3. A[1]=newint[2]
4. A=newint[3][2]
HOwmanyobjectsarecreated?
11objectsgotcreated
Howmanyobjectsareeligibleforgarbagecollection?
7objectseligibleforgarbagecollection1,2,3statements

TypesofVariables
Division1:Basedontypeofvaluerepresentedbyavariable,allvariablesaredividedintotwo
types.
1.Primitivevariables:canbeusedtorepresentprimitivevalues.Intx=10
2.ReferenceVariables:canbeusedtoreferobjectsex.Students=newstudent()
Sispointingtoobject.

Division2:Basedonpositionofdeclarationandbehavior,allvariablesaredividedintothreetypes.
1. Instancevariables,
2. Staticvariables
3. Localvariables.
Instancevariables:
Ifthevalueofavariableisvariedfromobjecttoobject,suchtypeofvariablesarecalledInstance
Variables.
Foreveryobject,aseparatecopyofvariableswillbecreated.Instancevariablesshouldbe
declaredwithintheclassdirectlybutoutsideofanymethodorblockorconstructor.Instance
variablewillbecreatedatthetimeofobjectcreationanddestroyedatthetimeofobject
destruction.Hencethescopeofinstancevariableisexactlysameasthescopeofobject.
Instancevariableswillbestoredintheheapmemoryasthepartofobject.
Wecantaccessinstancevariablesdirectlyfromstaticarea.Butwecanaccessbyusingobject
reference.But,wecanaccessinstancevariablesdirectlyfrominstancearea.
Ex:
ClassTest
{
Intx=0
Publicstaticvoidmain(String[]args)
{
System.out.println(x)CENonstaticvariablexcannotbereferencedfromstaticcontext
Testt=newTest()
System.out.println(t.x)//10
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

}
Publicvoidm1()
{
super(x)
}}
Forinstancevariables,JVMwillalwaysprovidedefaultvaluesandwerenotrequiredtoperform
initializationexplicitly.
Ex:
publicclassSun{
intx
doubled
booleanb
Strings
publicstaticvoidmain(String[]args){
Testt1=newTest()
System.out.println(t1.x)//0
System.out.println(t1.d)//0.0
System.out.println(t1.b)//false
System.out.println(t1.s)//Null

}}
Instancevariablesarealsoknownasattributesorobjectlevelvariables.

Staticvariables:Ifthevalueofavariableisnotvariedfromobjecttoobject,thenitisnot
recommendedtodeclarevariableasinstancevariable.Wehavetodeclaresuchtypeofvariables
atclasslevelbyusingstaticmodifier.Inthecaseofinstancevariables,foreveryobjectaseparate
copywillbecreated.But,inthecaseofstaticvariables,asinglecopywillbecreatedattheclass
levelandsharedbyeveryobjectoftheclass.Staticvariablesshouldbedeclaredwithintheclass
directlybutoutsideofanymethodorblockorconstructor.
Staticvariableswillbecreatedatthetimeofclassloadinganddestroyedatthetimeofclass
unloading.Hencescopeofstaticvariableisexactlysameasscopeof.classfile.

JavaTest
1. StartJava
2. Createandstartmainthread
3. Locatetest.classfile
4. Loadtest.classstaticvariablescreatio
5. Executemain()method
6. Unloadtest.classstaticvariablesdestruction
7. Terminatemainthread
8. ShutdownJVM

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Staticvariableswillbestoredinmethodarea.WEcanaccessstaticvariableseitherbyobject
referenceorbyclassname.Butrecommendedtouseclassname.Withinthesameclassitisnot
requiredtouseclassnameandwecanaccessdirectly.

ClassTest
{
Staticintx=10
PSVM(string[]args)
{
TestA=newTest()
SOP(t.x)
SOP(test.x)
SOP(x)
}}
WEcanaccessstaticvariablesdirectlyfrombothinstanceandstaticareas.
Ex:
Classtest
{
Staticintx=10
PSVM(string[]args)
{
SOP(x)
}
Publicvoidmain()
{SOP(X)
}}

Forstaticvariables,JVMwillprovidedefaultvaluesandwerenotrequiredtoperforminitialization
explicitly.
ClassTest
{
Staticintx
Staticdoubled
Staticstrings
PSVM(String[]args)
{
SOP(x)
SOP(d)
Sop(s)
}}
Staticvariablesarealsoknownasclasslevelvariablesorfields.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

ClassTest
{
Staticintx=10//staticvariablegetscreatedwhenclassisloaded
Inty=20//createdatthetimeofobjectcreation
PSVM(String[]args)
{
Testt1=newTest()//t1>(y=20)//sinceinstancevariableinitializedatobjectcreation
T1.x=888t1>888
T1.y=999//t1>(y=20)999
TestT2=newTest()
SOP(t2.x+....+t2.y)//t2.xischangedto888andt2.yisreferredto20.
}
}

LocalVariables:
Sometimes,tomeettemporaryrequirementsoftheprogrammer,wecandeclarevariablesinside
amethodorblockorconstructor.Suchtypeofvariablesarecalledlocalvariablesortemporary
variablesorstackvariablesorautomaticvariables.Localvariableswillbestoredinsidestack
memory.
Thelocalvariablewillbecreatedwhileexecutingtheblockinwhichwedeclaredit.Onceblock
executioncompletes,automaticallylocalvariablewillbedestroyed.Thescopeoflocalvariableis
theblockinwhichwedeclaredit.

Ex:ClassTest
{
PSVM(String[]args)
{inti=0
For(intj=0j<2j++)
{
I=i+j
}
System.out.println(i,j)//CECannotfindsymbolvariableJlocationClasstest.
}
}

Ex:
ClassTest
{
PSVM(String[]args)
{
Try{intj=INteger.parseInt(ten)
}
Catch(NumberformatExceptione)
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

{
j=10CECannotfindsymbolvariableJlocationClasstest.
}
System.out.println(J)//CECannotfindsymbolvariableJlocationClasstest.
}}
Forlocalvariables,JVMwontprovidedefaultvalues.Compulsoryweshouldperforminitialization
explicitlybeforeusingthatvariable.Thatis,ifwearenotusing,thenitisnotrequiredtoperform
initialization.

ClassTest ClassTest
{ {
PSVM(String[]args) PSVM(String[]args)
{ {
Intx Intx
SOP(Hello)}} SOP(x)}}
Output:Hello. CE:Variablexmightnothavebeeninitialized.

ClassTest ClassTest
{ {
PSVM(string[]args) PSVM(String[]args)
{ {intx
Intx If(args.length>0)
If(args.length>0) {
{ x=10
X=0 }
}SOP(X) Else{x=20}
}}CEVariablexmightnothavebeen SOP(x)
initialized JavaTestAb
OUtputis:10
Note:Itisnotrecommendedtoperforminitializationforlocalvariablesinsidelogicalblocks
becausethereisnoguaranteefortheexecutionoftheseblocksalwaysatruntime.
Note:Itishighlyrecommendedtoperforminitializationforlocalvariablesatthetimeofdeclaration
atleastwithdefaultvalues.
TheonlyapplicablemodifierforlocalvariablesisfinalBymistakeifwearetryingtoapplyany
othermodifier,thenwewillgetcompiletimeerror.
Ex:ClassTest
{
Publicstaticvoidmain(String[]args)
{
Publicintx=10//CEIllegalstartofexpression.
Privateintx=10//CEIllegalstartofexpression.
Protectedintx=10//CEIllegalstartofexpression.
Staticintx=10//CEIllegalstartofexpression.
Transientintx=10//CEIllegalstartofexpression.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Volatileintx=10//CEIllegalstartofexpression.
Finalintx=10//onlythisstatementisvalid.
}}
Note:IfwearenotdeclaringwithanymodifierthenbydefaultitisDefaultbutthisruleis
applicableonlyforinstanceandstaticvariablesbutnotforlocalvariables.
Conclusions:ForinstanceandstaticvariablesJVMwillprovidedefaultvaluesandwearenot
requiredtoperforminitializationexplicitly.Butforlocalvariables,JVMwontprovidedefaultvalues
compulsoryweshouldperforminitializationexplicitlybeforeusingthatvariable
Instanceandstaticvariablescanbeaccessedbymultiplethreadssimultaneously.Andhence
thesearenotthreadsafe.But,inthecaseoflocalvariables,foreverythreadaseparatecopywill
becreatedandhencelocalvariablesarethreadsafe.

TypeofVariable Isthreadsafeornot

Instancevariable No

StaticVariable No

LocalVariable YES
EveryVariableinJavashouldbeeitherinstanceorstaticorlocal.
Everyvariableinjavashouldbeeitherprimitiveorreference.Hencevariouspossible
combinationsofvariablesinJavaare

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Uninitializedarrays:

ClassTest
{
Int[]x
PSVM(String[]args)
{
TestT=newTest()
SOPLN(t.x)//null
SOPLN(t.x[0])//NPE
}}
Instancelevel
Int[]x
SOPLN(obj.x)null
SOPLN(obj.x[0])//npe

Staticlevel
Staticint[]x
Sop(x)//null
SOP(x]0])//reNPE
Staticint[]x=newint[x]
SOP(x)[i@934289
SOP(x[0])0

LocalLevel:
Int[]x
SOP(x)
SOP(x[0])ceVariablexmightnothavebeeninitialized
Int[]x=newint[3]
SOP(x)[I@1234970
Sop(x[0]0
Oncewecreateanarrayeveryarrayelementbydefaultinitializedwithdefaultvaluesirrespective
ofwhetheritisinstanceorstaticorlocalarray.

Varargmethods:(Variablenumberofargumentmethods)
Newconceptwhichcamein1.5versionofJava.
Until1.4version,wecantdeclareamethodwithvariablenumberofarguments.Ifthereisa
changeinnumberofargumentscompulsoryweshouldgofornewmethod.Itincreaseslengthof
thecodeandreducesreadability.ToovercomethisproblemsomeSUNpeopleintroducedvararg
methodsin1.5version.Accordingtothiswecandeclareamethodwhichcantakevariable
numberofarguments.Suchtypeofmethodsarecalledvarargmethods.
m1(intx)
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Wecandeclareavarargmethodasfollows.Wecancallthismethodbypassinganynumberof
intvaluesincluding0number.
m1()
m1(10)
m1(10,20,30)
m1(10,20,30,40)

Ex:ClassTest
{
Publicstaticvoidm1(intx)
{
SOP(Varargmethods)
}
Publicstaticvoidmain(String[]args)
{
m1()
m1(10)
m1(10,20,30)
m1(10,20,30,40)
}}Inallthesecasestheoutputweregoingtogetvarargmethodsfor4times.
Internally,varargparameterwillbeconvertedintoonedimensionalarray.Hencewithinthevar
argmethodwecandifferentiatevaluesbyusingindex.

Ex:classTest
{
PSVM(String[]args)
{
sum()
Sum(10,02)
sum(10,20,30)
sum(10,20,30,40)
}
Publicstaticvoidsum(int...x)
}
Inttotal=0
For(intx1:x)
{
Total=total+x1
}
Sop(thesum:+total)
}}

Case1:whichofthefollowingarevalidvarargmethoddeclarations
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

m1(intx)//valid
m1(int...x)//valid
m1(int...x)//valid
m1(intx)//invlid
m1(int...x)//invalid3dotsarebestfriends
m1(int.x..)//invalid

Case2:wecanmixvarargparameterswithnormalparameters
m1(intx,inty)
m1(strings,double...y)

Case3:Ifwemixnormalparameterwithvarargparameterthenvarargparametershouldbelast
parameter.
m1(double...d1,Strings)//invalid
m1(charch,Strings)//valid

Case4:insidevarargmethodwecantakeonlyonevarargparameterandwecanttakemore
thanvarargparameter.
m1(intx,doubled)//invalid
Insideaclass,wecantdeclarevarargmethodandcorrespondingonedimensionalarraymethod
simultaneously.Otherwise,wewillgetcompiletimeerror.
Ex:
ClassTest
{
PSVM(intx)
{
SOPLN(int..)
}
psvm(int[]x)
{
sopln(int[])
}
}CE:cannotdeclarebothm1(int[]x)andm1(intx)intest.

Example:
ClassTest
{
Publicstaticvoidm1(intx)
{
SOP(Varargmethods)
}
Publicstaticvoidm1(intx)
{
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

SoP(Generalmethod)
}
Publicstaticvoidmain(String[]args)
{
m1()//varargmethod
m1(10,20)//varargmethod
m1(30)//generalmethod19yrsexperience:)generalmethodhaspriority
}}
//varargmethodhasleastpriorityanditssimilartodefaultasinswitchcase.
Ingeneral,varargmethodwillgetleastpriorityi.eifnoothermatched,thenonlyvarargmethod
willgetthechance.Itisexactlysameasdefaultcaseinsideswitch.

Equivalencebetweenvarargparameterandonedimensionalarray.
Case1:Whereveronedimensionalarraypresent,wecanreplacewithvarargparameter.
Intm1(int[]x)replacedwithm1(int...x)
Example:
main(String[]args)canbereplacedwithmain(String...args)
Case2
Wherevervarargparameterpresent,wecantreplacewithonedimensionalarray
m1(intx)replacedwithm1(int[]x)//invalid

Note:m1(int...x)wecancallthismethodbypassingagroupofintvaluesandxwillbecomeone
dimensionalarray.
m1(int[]...x)wecancallthismethodbypassingagroupofonedimensionalintarrayandxwill
becometwodimensionalintarray.

Test:
ClassTest
{
PSVM(String[]args)
{
Int[]a={10,20,30}
Int[]b={40,50,60}
m1(a,b)
}
Publicstaticvoidm1(int[]...x)
{
For(int[]x1:x)
{sopln(x1(0)
}}//output10,40

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Mainmethod
Whetherclasscontainsmainmethodornot,andwhethermainmethodisdeclaredaccordingto
requirementornot,thesethingswontbecheckedbycompiler.Atruntime,JVMisresponsibleto
checkthesethings.IfJVMisunabletofindmainmethod,thenwewillgetruntimeexception
sayingNosuchmethodError:main.
ClassTest
{

}
JavaTest.Java
JavaTest
RE:Nosuchmethoderrormain.

AtruntimeJVMalwayssearchesforthemainmethodwiththefollowingprototype.
public static void main (String[]args)

TocallbyJVM Withoutexisting main()method Thisisthename Commandline


fromanywhere. objectalsoJVM cannotreturn whichis arguments
C:D:or hastocallthis anythingtoJVM configuredinside
wherever method JVM
Theabovesyntaxisverystrictandifweperformanychangethen,wewillgetruntimeexception
sayingnosuchmethoderror:main
Eventhoughabovesyntaxisverystrict,thefollowingchangesareacceptable.
1. Insteadofpublicstatic,wecantakestaticpublic.Ietheorderofmodifiersisnotimportant
2. Wecandeclarestringarrayinanyacceptableform.
main(string[]args)
main(String[]args)
Main(Stringargs[])
3.Insteadofargs,wecantakeanyvalidjavaidentifier
main(String[]durga)
4.Wecanreplacestringarraywithvarargparameter
main(Stringargs)
5.Wecandeclaremainmethodwiththefollowingmodifiers.Finalsynchronizedandstrictfp
ClassTest{
Publicstaticvoidmainfinalsynchronizedstrictfp(String...args)
{
SOP(HELLO)
}}
Ext:WHichofthefollowingmainmethoddeclarationsarevalid?
1. Publicstaticvoidmain(Stringargs)//invalid
2. PublicstaticvoidMain(String[]args)//invalid
3. Publicvoidmain(String[]args)//invalid
4. Publicstaticintmain(String[]args)//invalid
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

5. Finalsynchronizedstrictfppublicvoidmain(String[]args)//missingstatic
6. Finalsynchronizedstrictfppublicstaticvoidmain(String[]args)//valid
7. Publicstaticvoidmain(String...args)//valid
Ans:6,7

Inwhichoftheabovecaseswewillgetcompiletimeerror?
Wewontgetcompiletimeerroranywherebut,excceptlasttwocases,inremainingwewillget
runtimeexceptionsayingNOsuchMethodError:main.
Case1:Overloadingofthemainmethodispossiblebut,JVMwillalwayscallstringarrayargument
mainmethodonly.Theotheroverloadedmethodwehavetocallexplicitlylikenormalmethodcall.
ClassTest
{PSVM(String[]args)
{SOP(stringarray)
}
PSVM(int[]args)
{SOP(intarray)}//overloadedmethods

Case2:INheritanceconceptapplicableformainmethod.Hencewhileexecutingchildclass,ifa
childdoesntcontainmainmethod,thenparentclassmainmethodwillbeexecuted.
ClassP
{PSVM(String[]args)
}}
ClassCextendsP
{


ThisistheconceptofinhertianceinJava.

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Case3:
ClassP
{PSVM(String[]args)
}}
ClassCextendsP
{
PSVM(Stringargs[])//Thisconceptismethodhidingbutnotmethodoverriding.
{SOP(Helloworld)
}
}


Itseemsoverridingconceptapplicableformainmethodbutitisnotoverridinganditismethod
hiding.Note:Formainmethod,inheritanceandoverloadingconceptsareapplicable.But,over
ridingconceptisnotapplicable.Insteadofoverriding,methodhidingconceptisapplicable.
1.7versionEnhancementswithrespecttomainmethod:
Until1.6version,iftheclassdoesntcontainmainmethod,thenwewillgetruntimeexception
sayingNoSUCHmethoderror:main.But,from1.7versiononwards,insteadofNosuchmethoderror,
wewillgetmoreelaboratederrorinformation.
Ex:ClassTest{
}

1.6version 1.7v

JavacTest.Java JavacTest.Java
JavaTest JavaTest

RE:nosuchmethoderror:main Error:MainmethodnotfoundinclassTest.
Pleasedeclaremainmethodas
Publicstaticvoidmain(String[]args)

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

ClassTest
{
Static
{
System.out.println(Staticblock)
}}

1.6version 1.7v

JavacTest.Java JavacTest.Java
JavaTest JavaTest

OP:Staticblock Error:MainmethodnotfoundinclassTest.
RE:nosuchmethoderror:main Pleasedeclaremainmethodas
Publicstaticvoidmain(String[]args)
From1.7versiononwards,mainmethodismandatorytostartprogramexecution.Hence,even
thoughclasscontainsstaticblock,itwontbeexecutediftheclassdoesntcontainmainmethod.

Ex.2
ClassTest
{
Static
{
SOPLN(Staticblock)
System.exit(0)
}}

1.6version 1.7v

JavacTest.Java JavacTest.Java
JavaTest JavaTest

OP:Staticblock Error:MainmethodnotfoundinclassTest.
Pleasedeclaremainmethodas
Publicstaticvoidmain(String[]args)
From1.7versiononwards,mainmethodismandatorytorunprogramexecution.
ClassTest
{
Static
{
System.out.println(Staticblock)}
Publicstaticvoidmain(String[]args)
{

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

SOPLN(mainmethod)
}}

Test:Withoutwritingmainmethodisitpossibletoprintsomestatementstotheconsole?
YesByusingstaticblockuntiltheversionof1.6.Thisruleisapplicableuntil1.6version.Butfrom
1.7versiononwardsitisimpossibletoprintsomestatementstotheconsole.

Commandlinearguments:
Theargumentswhicharepassingfromcommandpromptarecalledcommandlinearguments.
WiththesecommandlineargumentsJVMwillcreateanarrayandbypassingthatarrayas
argumentJVMwillcallmainmethod
Ex:

java test a b c

args[0] args[1] args[2]

args.length=3

ClassTest
{
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

PSVM(String[]args)
{
Intn=Integer.parseInt(args[0])

Themainobjectiveofcommandlineargumentsis,wecancustomizebehaviorofthemain
method.
Case1:
ClassTest
{
PSVM(String[]args)
{
For(inti=0i<=args.lengthi++)
{SOPLN(args[i])
}}}
Output:arrayindexoutofboundsexception,
Ifwereplacelessthanorequaltowithlessthan,thenwewontgetanyruntimeexception.

Ex:classTst
{
PSVM(String[]args)
{
String[]argh={X,y,z}
Args=argh
For(Strings:args)
{sop(s)
}}}
Output:xyz,xy,

Case3:
ClassTest
{pSVM(STring[]args)
{
SOP(args[0]+args[1])
}}
Withinmainmethod,commandlineargumentsareavailableinstringform.Sothesumoftwo
commandlineargumentswillbehaveasconcatenation.

Case4:
ClassTest
{pSVM(STring[]args)
{
SOP(args[0])
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

}}
JavaTestNoteBook
Usually,spaceitselfistheseparatorbetweencommandlinearguments.Ifourcommandline
argumentitselfcontainsspace,thenwehavetoenclosethatcommandlineargumentwithin
doublequotes.

JavaCodingstandards:Wheneverwearewritingjavacodeitishighlyrecommendedtofollow
codingstandards.Wheneverwearewritinganycomponent,itsnameshouldreflectthepurpose
ofthatcomponent(functionality)Themainadvantageofthisapproachisreadabilityand
maintainabilityofthecodewillbeimproved.
Ex:

ClassA Packagecom.durgasoft.scjp
Publicintm1(intx,inty) Publicclasscalculator
{returnx+y {
} Publicstaticintadd(intnumber1,intnumber2)
//novicestandard {
Returnnumber1+number2
}
}
CodingstandardsforClasses:Usuallyclassnamesarenouns.Shouldstartwithuppercase
characterandifitcontainsmultiplewordseveryinnerwordshouldstartwithuppercasecharacter.
Ex:String,StringBuffer,Account,Dog
Codingstandardsforinterfaces:Usuallyinterfacenamesareadjectives.Shouldstartwith
uppercasecharacterandifitcontainsmultiplewords,everyinnerwordshouldstartwithupper
casecharacter.
Ex:Runnable,Seializable,Comparable,RandomAccessetc.,
CodingstandardsforMethods:Usually,methodnamesareeitherverbsorverbnoun
combinations.Shouldstartwithlowercasealphabetsymbolandifitcontainsmultiplewords,then
everyinnerwordshouldstartwithuppercasecharacter(camelcaseconvention)
Ex:print(),sleep(),run()eat(),start(),getName(),setSalary()etc.,
CodingstandardsforVariables:U suallyvariablenamesarenouns.Shouldstartwithlower
casealphabetsymbolandifitcontainsmultiplewords,theneveryinnerwordshouldstartwith
uppercasecharacter(camelcaseconvention)
Ex:name,age,salary,mobileNumber,etc.,
CodingstandardsforConstants:Usuallyconstantnamesarenouns.Shouldcontainonly
uppercasecharactersandifitcontainsmultiplewords,thenthesewordsareseparatedwith
_symbol.
Ex:MAX_VALUE,MIN_VALUE,MAX_PRIORITY,PIetc.,
NOte:Usually,wecandeclareconstantswithpublicstaticandfinalmodifiers.
JavaBeanCodingStandards:Ajavabeanisasimplejavaclasswithprivatepropertiesand
publicgetterandsettermethods.
PublicclassstudetnBean
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

PrivateStringname
PublicvoidsetName(STringname)
{
this.name=name
}
PublicstringgetName()
{
Returnname
}}
Classnameendswithbeanisnotofficialconventionfromsun
SyntaxforSetterMethod:
Itshouldbepublicmethod
Thereturntypeshouldbevoid
Methodnameshouldbeprefixedwithset
Itshouldtakesomeargument.I.eitshouldnotbenoargumentmethod.
PublicvoidsetName(Stringname)

SyntaxforGetterMethod:
Itshouldbepublicmethod
Thereturnshouldnotbevoid
Methodnameshouldbeprefixedwithget
Noargumentsarerequiredtopass
PublicStringgetName()
**FOrbooleanpropertiesgettermethodnamecanbeprefixedwitheithergetoris.But
recommendedtouseis.

Privatebooleanempty
PublicbooleangetEmpty()
{returnempty
}
PublicbooleanisEmpty()
{returnempty}

Codingstandardsforlisteners:
Case1:Toregisteralistener,methodnameshouldbeprefixedwitha dd
PublicvoidaddMyactionListener(MACtionlistenerl)
Publicvoidregistermyactionlistener(myactionlistenerl)//invlaid
Publicvoidaddmyacctionlistener(actionlisterel).//invalid

Case2:Tounregisteralistener
Publicvoidremovemyactionlistener(myactionlistenerl)
Publicvoidunregistermyactionlistener(myactionlistenerl)//invalid
Publicvoidmyactionlistener(actionlistenerl)//invalid
70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes
understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.

Durga Software Solutions - Core Java by Durga Sir

Publicvoiddeletemyactionlistener(myactionlistenerl)//invalid
Methodnameshouldbeprefixedwithremove.

Languagefundamentalscompleted:)

=====================================================================

70%ofJobbasedinterviewsfromCoreJava KnowledgeofCoreJavadecidesyourJOB StronginCoreJavamakes


understandingofanyJavabasedtechnologyveryeasy CoreJavaactsasthebaseforentireJavaplatformWhileworkingwith
anyjavabasedadvancedTechnologies( likeStruts,spring,Hibernate),ProgrammershavetowritecodeusingCoreJavaonly.