Академический Документы
Профессиональный Документы
Культура Документы
Java1.5(codenamedTiger)
Java1.6(Mustang)
Java1.7(Dolphin)
GenericsforCollections
Pluggable
annotation
processing
Stringinswitchstatement
VarargsThevarragsallows
themethodtoacceptzeroor
muliplearguments.
Commonannotations
voiddisplay(String...s)
@Resources
TrywithresourcesWhenatryblockisend,itwill
closeorreleaseyouropenedfileautomatically.Finally
isnolongerrequired.Ex.try(BufferedReaderbr=new
BufferedReader(newFileReader("C:\\testing.txt"))){
..
}catch(Exceptione){
}
Therecanbeonlyonevariable
argumentinthemethod.
Variableargument(varargs)
mustbethelastargument.
@Resource
@PreDestory
@PostConstruct
Rolebased
annotationslike
@DeclareRoles
@RolesAllowed
@PermitAll
@DenyAll
Instrumentationthisclass
providesservicesto
instrumentaljavaprogramming
language.Ex.Profiling,
coverageanalyzers,event
loggersandmonitoringagents.
Scriptinglanguage
supportsupports
allscripting
languageslike
javascript,php
script,beanshell
scriptetc..
Diamondoperator(referexamplebelow)
Alsojavaprovides
aScriptingAPI
Foreachloop(Enhancedfor
loop)
JDBC4.0API
autoloadingofJDBC
drivers,streaming
APIs..
Improvedconcurrencylibraries
Staticimport
NativePKI,JAVA
GSS,Kerberosand
LDAPsupport
Platformchangesupportfordynamiclanguages
Autoboxing/unboxing
Integratedweb
services
Multipleexceptionhandlingseparateexceptionsusing
|
ScannerAsimpletextscanner
whichcanparseprimitivetypes
andstringsusingregular
expressions
Instrumentation
premainmethod
usingJava
instrumentation,we
canaccessaclass
thatisloadedby
theJava
classloaderfrom
theJVMandmodify
itsbytecodeby
insertingour
customcode,all
thesedoneat
runtime(modifyjava
codeatruntime)
JavaniopackageNIOweredesignedtoprovideaccess
tothelowlevelI/Ooperationsofmodernoperating
systems
Formatting
Ex:
Buffersfordataofprimitivetypes
Charactersetencodersanddecoders
ApatternmatchingfacilitybasedonPerl
Channels,anewprimitiveI/Oabstraction
Afileinterfacethatsupportslocks
AutomaticnullhandlingusingNullsafenavigation
operator?
Ex.Obj?.getMtd()
WillsimplyreturnNULLifnullobj
Typesafeenums
Binaryliteralsandunderscoresinliterals
Annotation(Metadata)
Typeinterfaceforgenericinstancecreation
Covariantreturntypereturn
typemayvaryinthesame
directionasthesubclass
Underscoreinnumericliterals
classA{
j=1234_5678;
Aget(){returnthis;}
Forex.toholdcreditcardnumbersetc.,
Ex.intj;
classBextendsA{
Bget({returnthis;}
StringBuilder
Java1.5
1.Generics
GenericsisoneofthemostusefulfeaturesaddedinJava5.Itaddscompiletimetypesafetytothe
CollectionsFrameworkandeliminatesthenecessityfortypecasting.
ExampletoshowthebenefitsofGenerics:
importjava.util.*;
publicclassGenericsTest
{
publicstaticvoidmain(String[]args)
{
List<String>names=newArrayList<String>();
names.add("Ram");
names.add("Peter");
names.add("Khan");
names.add("Singh");
names.add(newDate());
//Compilererror
for(inti=0;i<names.size();i++){
//Noneedoftypecasting(String)
Stringname=names.get(i);
System.out.println("Name="+name);
}
}
}
Nestingofgenericsisalsopossible:
Map<Integer,List<String>>mapStudents=newHashMap<Integer,List<String>>();
List<String>countries=newArrayList<String>();
countries.add("Switzerland");
countries.add("France");
countries.add("Germany");
countries.add("Italy");
countries.add("India");
AbovecodesnippetfirstcreatesanobjectofArrayListtypeStringandthenaddonebyonecountries
init.NowchecktheDoubleBraceInitializationofthesamecode:
List<String>countries=newArrayList<String>(){{
add("India");
add("Switzerland");
add("Italy");
add("France");
add("Germany");
}};
2.EnhancedforLoop(foreachloop)
EnhancedforloopisalsoreferredasforEachLoopandisspecificallydesignedtoiteratethrough
arraysandcollections.LetscheckthebenefitsofenhancedforloopwiththeearlierGenericsexample
program.
importjava.util.*;
publicclassForEachTest
{
publicstaticvoidmain(String[]args)
{
List<String>names=newArrayList<String>();
names.add("Ram");
names.add("Peter");
names.add("Khan");
names.add("Singh");
for(Stringname:names){
System.out.println("Name="+name);
}
}
}
Here,wecansimplyiteratethroughthelistnamesandretrieveeachelementintovariablename.
Afterthat,wecandowhateverwewantwiththatvariableasusual.Enhancedforloopavoidstheneed
forusingtemporaryindexvariableandsimplifiestheprocessofiteratingoverarraysandcollections.
3.Autoboxing/Unboxing
TheAutoboxingfeatureeliminatestheneedforconversionbetweenprimitivedatatypessuchasint,
floatetc.andtheirrespectivewrapperclasses(Asthenamesays,awrapperclasswraps(encloses)
aroundadatatypeandgivesitanobjectappearance)Integer,Float,etc.
WhatisAutoboxinginJava?
Theimplicitautomaticconversionofprimitivevaluesintocorrespondingwrapperclassobjectsisknown
asAutoboxing.AutoboxingExamples:
(1)
Integerage=31;//Autoboxing:31=>Integer.valueOf(31)
TheabovestatementcreatesanewIntegerobjectwithvalue31andassignstoIntegerreference
variableage.
(2)
List<Double>weights=newArrayList<Double>();
weights.add(64.5);//Autoboxing:64.5=>Double.valueOf(64.5)
weights.add(73.2);//Autoboxing:73.2=>Double.valueOf(73.2)
Here,twoDoubleobjectswillbecreatedwithvalues64.5&73.2andthoseobjectswouldbeaddedto
thelistweights.
WhatisUnboxing(Autounboxing)inJava?
Theimplicitautomaticconversionofwrapperclassobjectstoprimitivevaluesiscalled
Unboxing.UnboxingExamples:
(3)if(age>25){//Unboxing:age=>age.intValue()
//dosomething
}
SinceageisanIntegerobjectandwecantperformrelationaloperations(<,>,<=,>=)onobjects,
firstagewillbeconvertedtointusingintValue()methodofIntegerclass.Lateritwillbe
comparedwith25using>relationaloperator.
(4)doubletotalWeight=weights.get(0)+weights.get(1);
//137.7
//Unboxing:weights.get(0).doubleValue()
//+weights.get(1).doubleValue()
Likeinexample(3),wecantperformarithmeticoperations(+,,*,/,%)onobjects,hencethetwo
DoubleobjectswillbeconvertedtodoubleprimitivevaluesusingdoubleValue()method.Now,with
noissues,thosetwodoublevalueswillbeaddedandthesumwouldbeassignedtototalWeight.
4.TypesafeEnums
JavaEnumistypelikeclassandinterfaceandcanbeusedtodefineasetofEnumconstants.Enum
constantsareimplicitlystaticandfinalandyoucannotchangetheirvalueoncecreated.EnuminJava
providestypesafetyandcanbeusedinsideswitchstatementlikeintvariables.Followingarethe
advantagesofusingEnums:
Enumsaretypesafe
EnumsareSerializableandComparablebydefault
ProgrammersdoesntrequiretodoextraworkofimplementingtoString(),equals()and
hashCode().Enumsprovideimplementationofthesebydefault.
ProgrammerscanuseEnumsinswitchcasestatements.
Enumsarepermittedtoimplementtointerfaces.
Enumscannotbeinstantiatedastheconstructorisprivate.Whenanystaticvariableis
referencedwiththeenumname,thenanenuminstanceiscreated.
Enumsarefinalbydefaultandhenceyoucannotextendthem
Enumsextendthejava.lang.Enumclassimplicitly,soyourenumtypescannotextendanother
class.
Methods:name,valueOfandtoString
//Printingallconstantsofanenum.
for(Dayday:Day.values())
System.out.println(day.name());
EnumwithValuesExample:
publicenumDay{
SUNDAY(1),
MONDAY(2),
TUESDAY(3),
WEDNESDAY(4),
THURSDAY(5),
FRIDAY(6),
SATURDAY(7)
}
inorderforthisapproachtofunctionproperly,aprivatemembervariableandaprivateconstructor
mustbedefined,asshownbelow
privateintvalue;
privateDay(intvalue){
this.value=value;
}
Inordertoretrievethevalueofeachconstantoftheenum,youcandefineapublicmethodinsidethe
enum:
publicintgetValue(){
returnthis.value;
}
Anotherissueisthatthevaluedisplayedwouldbeanumberwhichisnotinformative.Byseeingthat
numberwedonotknowwhichenumvalueitisreferringto,moreoverwedonotevenknowthatitisan
enumbecauseofthenumber.Youcanunderstandthisbetterbyseeingtheaboveoutput.
Nowconsiderthefollowingtypesafeenumexampleprogram:
publicclassNewEnumTest
{
publicenumDay{
SUNDAY,MONDAY,TUESDAY,WEDNESDAY,
THURSDAY,FRIDAY,SATURDAY
}
voidprintAppointment(Dayday){
System.out.println("Pleasecomeon"+day);
}
publicstaticvoidmain(String[]args)
{
newNewEnumTest().printAppointment(Day.TUESDAY);
}
}
Output:PleasecomeonTUESDAY
Switchcaseexample:
Dayd;
d=Day.MONDAY;
switch(d)
{
caseMONDAY:
default:System.out.println("Whatdayisit?");;
}
whenanenumcontainfieldsandmethods,thedefinitionoffieldsandmethodsmustalwayscomeafter
thelistofconstantsintheenum.Additionally,thelistofconstantsmustbeterminatedbya
semicolon;
Youcallanenummethodviaareferencetooneoftheconstantvariables.
ScannersinJava5
Java.util.Scannerclassinjava5ismainlyusedfortokenizingdataandfindingstuff.Although,
Scannersinjava5doesntprovidelocationinformationorsearchandreplacefunctionality,itcanbe
usedtosourcedatabyapplyingregularexpressionstofindouthowmanyinstancesofanexpression
existsinsourcedata.
Tokenizing
Tokenizingistheprocessoftakingbigpiecesofsourcedata,breakingthemintopiecesandstoring
thepiecesintovariables.Besidesscannersinjava5,tokenizingfunctionalityisprovidedbyString
(withthehelpofsplit()method).
ForthepurposeofTokenizing,sourcedatacomprisesoftokensanddelimiters.Tokensaretheactual
piecesofdata,anddelimitersaretheexpressionsthatseparatetokensfromeachother.
ForExample:
Source:123,23,india,delhi
Ifwesaythatourdelimiterisacomma,thenourfourtokenswouldbe
123
23
india
delhi
TokenizingwithScanner
Letslookatitusinganexample.Scannersdefaultdelimiteriswhitespace.Scannermethods:
1.
hasNextXxx()teststhevalueofthenexttokenbutdonotactuallygetthetoken.Forexample,
hasNextDouble()checksifthenexttokenisofdoubledatatype.
2.
3.
nextXxx()returnsthenexttoken
useDelimeter()allowsyoutosetthedelimitertobeanyvalidregularexpression.
Java1.7
DiamondoperatorPurposeofthediamondoperatoristosimplifyinstantiationofgenericclasses.For
example,insteadof
List<Integer>p=newArrayList<Integer>();withthediamondoperatorwecanwriteonly
List<Integer>p=newArrayList<>();
Java1.8
1.
FunctionalInterfacesaninterfacewithjustoneabstractmethod.WeuseAnonymousinner
classestoinstantiateobjectsoffunctionalinterface.WithLambdaexpressions,thiscanbe
simplified.
2.
LambdaExpressionsreducesthecodewhereeverpossible.Alambdaexpressionisananonymous
function.Simplyput,itsamethodwithoutadeclaration,i.e.,accessmodifier,returnvalue
declaration,andname.
(arg1,arg2...)>{body}
(type1arg1,type2arg2...)>{body}
3. NewJVMJavascriptengineisintroduced
4. Newdate/timeapis
5. forEach()methodinIterableinterface
6. defaultandstaticmethodsinInterfaces
7. JavaStreamAPIforBulkDataOperationsonCollections
8. CollectionAPIimprovements
9. ConcurrencyAPIimprovements
10. JavaIOimprovements
11. MiscellaneousCoreAPIimprovements
CoreJava
Javaisaplatformindependent,ooprogramminglanguage.Featuresofjava:
SimpleObjectOrientedPlatformindependentSecuredRobustArchitectureneutral
PortableDynamicInterpretedHighPerformanceMultithreadedDistributed
Setpathinjava(pointingtojdk\bin)
1.
Temporaryusingcmdprompt
2.Permanentsetinenvironmentvariables
JDK,JREandJVM(all3areplatformdependent,butjavaisplatformindependent)
JavaVirtualMachine:anabstractmachinethatprovidesruntimeenvironmenttoexecutebytecode.
TheJVMperformsfollowingmaintasks:
Loadscode,Verifiescode,Executescode,Providesruntimeenvironment
JVMprovidesdefinitionsforthe:
Memoryarea,Classfileformat,Registerset,Garbagecollectedheap,Fatalerrorreportingetc.
JavaRuntimeEnvironment:implementationofJVMthatphysicallyexists.Setofruntime(rt.jar)
librariesandotherfilesPLUStheJVM.(JVM+rt.jar&otherfiles)
JavaDevelopmentKit:JRE+developmenttoolslikejava,javac
OOPsConcepts:
Objectsinstanceofaclassthathasstate,behaviorandidentityisknownasanobject.State
variables.Behaviorthroughmethods.Anonymoussimplymeansnameless.Anobjectthathavenoreference
isknownasanonymousobject.Waystocreateobject:
Bynewkeyword
BynewInstance()method//java.lang.reflect.Constructor.newInstance()and
java.lang.Class.newInstance()
//getconstructorthattakesaStringasargument
Constructorconstructor=MyObject.class.getConstructor(String.class);
MyObjectmyObject=(MyObject)
constructor.newInstance("constructorarg1");
Byclone()method
Byfactorymethodetc.
Classesisatemplatethatdescribesthedataandbehaviorassociatedwithinstancesofthatclass.
Collectionofobjectsiscalledclass.Itisalogicalentity.
AbstractionHidinginternaldetailsandshowingfunctionalityisknownasabstraction
EncapsulationBinding(orwrapping)codeanddatatogetherintoasingleunitisknownas
encapsulation.
InheritanceWhenoneobjectacquiresallthepropertiesandbehavioursofparentobjecti.e.knownas
inheritance.Itprovidescodereusability.Itisusedtoachieveruntimepolymorphism.
Polymorphismonenamewithmultipleforms.Overloadingandoverriding
Variable&Datatypes:
boolean false
1bit
char
'\u0000' 2byte
byte
0
1byte
short
0
2byte
int
0
4byte
long
0L
8byte
float
0.0f
4byte
double 0.0d
8byte
Variablenamegiventoreservedmemorylocation.3typesofvariables:
1.
LocalvariableAvariablethatisdeclaredinsidethemethod/blockofcodeiscalledlocal
/automaticvariable.Nodefaultvalue.Shouldbeinitializedwithavalue.Nomodifiercanbe
appliedexceptfinal.
2.
InstancevariableAvariablethatisdeclaredinsidetheclassbutoutsidethemethodiscalled
instancevariable.Itisnotdeclaredasstatic.Instancevariabledoesn'tgetmemoryatcompile
time.Itgetsmemoryatruntimewhenobject(instance)iscreated.Thatiswhy,itisknownas
instancevariable.Getsadefaultvalue.
3.
Static(Class)variableclasslevelvariabledeclaredwithstatickeyword.Itcannotbelocal.
Getsdefaultvalues.
TheStack/Framessectionofmemorycontainsmethods,localvariables,referencevariablesandresultsof
intermediateoperations.(Oneperthread)
TheHeapsectioncontainsObjects,arraysandinstance/staticvariables(OneperJVMinstance).Shared
memory.
Constructor:Constructorisaspecialtypeofmethodthatisusedtoinitializetheobject
Statickeyword:usedwithvariables,methods,blocksandnestedclass.Thestatickeywordbelongsto
theclassthaninstanceoftheclass.
1.
Staticvariablegetsmemoryonlyonceinclassareaatthetimeofclassloading.Local
variablescannotbestatic.Localvariablescanonlybefinal.
2. StaticmethodIfyouapplystatickeywordwithanymethod,itisknownasstaticmethod
Astaticmethodbelongstotheclassratherthanobjectofaclass.
Astaticmethodcanbeinvokedwithouttheneedforcreatinganinstanceofaclass.
Staticmethodcanaccessstaticdatamemberandcanchangethevalueofit.Nonstaticvariablesand
methodscanbeaccessedfromastaticmethodonlywiththeirobject.Howeveranonstaticmethodcan
accessbothstaticandnonstaticvariables.
Staticblockusedtoinitializethestaticdatamemberandisexecutedbeforemainmethodatthetime
ofclassloading.Ex:static{System.out.println("staticblockisinvoked");}
thiskeywordthisisareferencevariablethatreferstothecurrentobject.
1.
2.
thiskeywordcanbeusedtorefercurrentclassinstancevariable.//this.id=id;
3.
thiskeywordcanbeusedtoinvokecurrentclassmethod(implicitly).//this.mtd()isequivalent
tocallingmtd(),compilerwillautomaticallyprefixthis
4.
5.
thiscanbepassedasanargumentinthemethodcall.//mtd(this)
6.
7.
thiskeywordcanalsobeusedtoreturnthecurrentclassinstance.//returnthis;
8.
this()usedinoverloadedconstructorinordertocallnoargconstructor//mustbethefirst
statement
thiscanbepassedasargumentintheconstructorcall.//A();B(Aobj){this.obj=obj}
thisisafinalvariableinJavaandyoucannotassignvaluetothis.thiswillresultin
compilationerror
thiskeywordcannotbeusedinstaticcontexti.e.insidestaticmethodsorstaticinitializer
block.ifusethisinsidestaticcontextyouwillgetcompilationerror
Superkeyword:superisareferencevariablethatisusedtoreferimmediateparentclassobject.
1.
2.
3.
superisusedtoreferimmediateparentclassinstancevariable.//super.i
1.
2.
3.
4.
Finalvariablevariablecannotbereassignedwithsomeothervalue
super()isusedtoinvokeimmediateparentclassconstructor.//super(),shouldbefirstline
superisusedtoinvokeimmediateparentclassmethod.//super.mtd()
InstanceInitializerblock:InstanceInitializerblockisusedtoinitializetheinstancedatamember.
Itrunseachtimewhenobjectoftheclassiscreated.Ex.{speed=100;}
Instanceintializerblockisinvokedatthetimeofobjectcreation.Thejavacompilercopiesthe
instanceinitializerblockintheconstructorafterthefirststatementsuper().Example:
classBike{
intspeed;
Bike(){
System.out.println("constructorisinvoked");
}
{speed=100;}
publicstaticvoidmain(Stringargs[]){
Bikeb1=newBike();
}}
Finalkeyword:Thefinalkeywordinjavaisusedtorestricttheuser.
Finalmethodmethodcannotbeoverridden
Finalclassclasscannotbesubclassed
FinalParameterIfyoudeclareanyparameterasfinal,youcannotchangethevalueofitin
themethod
**Constructorcanneverbefinalastheycantbeinherited.
BlankoruninitializedfinalvariableAfinalvariablethatisnotinitializedatthetimeof
declaration.Canbeinitializedonlyintheconstructor.
classBike{
finalintspeedlimit;//blankfinalvariable
Bike(){
speedlimit=70;
System.out.println(speedlimit);
}}
StaticBlankfinalvariableAstaticfinalvariablethatisnotinitializedatthetimeofdeclaration
isknownasstaticblankfinalvariable.Itcanbeinitializedonlyinstaticblock.
Overloading:Ifaclasshavemultiplemethodsbysamenamebutdifferentparameters,itisknownas
MethodOverloading.Youcanoverloadamethodbychangingthenumberofargsordatatypeofargs.
Static,finalandprivatemethodscanbeoverloaded.
**Methodoverloadingisnotpossiblebychangingthereturntypealone
***Generallyaparameteriswhatappearsinthedefinitionofthemethod.Anargumentisthevalue
passedtothemethodduringruntime
voidsum(intx,longy){}
obj.sum(20,20)//methodoverloadingwithtypepromotion
voidsum(intx,inty){}
voidsum(longx,longy){}
obj.sum(20,20)//intversioniscalled
voidsum(intx,longy){}
voidsum(longx,inty){}
obj.sum(20,20)//CompilerError.Ambiguity..Dontknowwhichversiontocall!!
//Onetypeisnotdepromotedimplicitlyforexampledoublecannotbedepromotedtoanytype
implicitly.
Overriding:RuntimePolymorphism.Staticmethodscannotbeoverridden.
Ifsubclass(childclass)hasthesamemethodasdeclaredintheparentclass,itisknownasmethod
overriding.
1.
2.
3.
methodmusthavesamenameasintheparentclass
methodmusthavesameparameterasintheparentclass.
mustbeISArelationship(inheritance).
Rulesformethodoverriding:
Theargumentlistshouldbeexactlythesameasthatoftheoverriddenmethod.
Thereturntypeshouldbethesameorasubtypeofthereturntypedeclaredintheoriginal
overriddenmethodinthesuperclass.ReturntypecanbecovariantfromJava5.
Theaccesslevelcannotbemorerestrictivethantheoverriddenmethod'saccesslevel.For
example:ifthesuperclassmethodisdeclaredpublicthentheoverriddingmethodinthesub
classcannotbeeitherprivateorprotected.
Private,finalandstaticmethodscannotbeoverridden.
Anoverridingmethodcanthrowanyuncheckedexceptions,regardlessofwhethertheoverridden
methodthrowsexceptionsornot.Howevertheoverridingmethodshouldnotthrowchecked
exceptionsthatareneworbroaderthantheonesdeclaredbytheoverriddenmethod.The
overridingmethodcanthrownarrowerorfewercheckedexceptionsthantheoverriddenmethod.
Constructorscannotbeoverridden.Superkeywordcanbeusedtoinvokethesuperclassversionof
overriddenmethod.
AbstractionwaystoachieveabstractionAbstractclass(0to100%)andInterface(100%)
AbstractclassAnabstractclasscanhavedatamember,abstractmethod,methodbody,constructorand
evenmain()method.Anabstractclass,inthecontextofJava,isasuperclassthatcannotbe
instantiatedandisusedtostateordefinegeneralcharacteristics.Anobjectcannotbeformedfroma
Javaabstractclass;tryingtoinstantiateanabstractclassonlyproducesacompilererror.The
abstractclassisdeclaredusingthekeywordabstract.
Ifthereisanyabstractmethodinaclass,thatclassmustbeabstract.Ifyouareextendingany
abstractclassthathaveabstractmethod,youmusteitherprovidetheimplementationofthemethodor
makethisclassabstract.
Howwouldyoucallamethodinabstractclass?makethemethodstatic
Interfacehasstaticfinalconstantsandabstractmethods.Thejavacompileraddspublicandabstract
keywordsbeforetheinterfacemethodandpublic,staticandfinalkeywordsbeforedatamembers.
MarkerorTaggedorNullInterfaceAninterfacethathavenomemberisknownasmarkerortagged
interface.Forexample:Serializable,Cloneable,Remoteetc.Theyareusedtoprovidesomeessential
informationtotheJVMsothatJVMmayperformsomeusefuloperation.
Accessmodifierspublic,private,default(onlytothepackage),protected(alsotosubclassesin
differentpackage).
Nonaccessmodifiers
1.
2.
3.
Static
4.
5.
NativeAnativemethodisamethodthatisimplementedinalanguageotherthanJava.
Abstract
SynchronizedSynchronizationisaprocessofcontrollingtheaccessofsharedresourcesbythe
multiplethreadsinsuchamannerthatonlyonethreadcanaccessoneresourceatatime
Volatilevolatileisusedtoindicatethatavariable'svaluewillbemodifiedbydifferent
threads.Volatilekeywordisusedasanindicatortojavacompilerandthreadthatdonotcache
thevalueofthisvariableandalwaysreaditfrommainmemory.
6.
TransientTransientvariablecantbeserialized.Forexampleifavariableisdeclaredas
transientinaSerializableclassandtheclassiswrittentoanObjectStream,thevalueofthe
variablecantbewrittentothestreaminsteadwhentheclassisretrievedfromthe
ObjectStreamthevalueofthevariablebecomesnull.
Objectclass
TheObjectclassprovidesmanymethods.Theyareasfollows:
Method
Description
returnstheClassclassobjectofthisobject.TheClass
publicfinalClassgetClass()
classcanfurtherbeusedtogetthemetadataofthis
class.
publicinthashCode()
returnsthehashcodenumberforthisobject.
publicbooleanequals(Objectobj)
comparesthegivenobjecttothisobject.
protectedObjectclone()throws
createsandreturnstheexactcopy(clone)ofthis
CloneNotSupportedException
object.
publicStringtoString()
returnsthestringrepresentationofthisobject.
wakesupsinglethread,waitingonthisobject's
publicfinalvoidnotify()
monitor.
wakesupallthethreads,waitingonthisobject's
publicfinalvoidnotifyAll()
monitor.
causesthecurrentthreadtowaitforthespecified
publicfinalvoidwait(longtimeout)throws
milliseconds,untilanotherthreadnotifies(invokes
InterruptedException
notify()ornotifyAll()method).
causesthecurrentthreadtowaitforthespecified
publicfinalvoidwait(longtimeout,intnanos)throws
milisecondsandnanoseconds,untilanotherthread
InterruptedException
notifies(invokesnotify()ornotifyAll()method).
causesthecurrentthreadtowait,untilanotherthread
publicfinalvoidwait()throwsInterruptedException
notifies(invokesnotify()ornotifyAll()method).
isinvokedbythegarbagecollectorbeforeobjectis
protectedvoidfinalize()throwsThrowable
beinggarbagecollected.
Equals(),hashCode(),toStringExample:
publicinthashCode()
{
inthash=3;
hash=19*hash+(this.lastName!=null?this.lastName.hashCode():0);
hash=19*hash+(this.firstName!=null?this.firstName.hashCode():0);
hash=19*hash+(this.empName!=null?this.empName.hashCode():0);
hash=19*hash+(this.gender!=null?this.gender.hashCode():0);
returnhash;
}
publicStringtoString()
{
return"TraditionalEmployee;
}
publicbooleanequals(Objectobj)
{
if(obj==null)
{
returnfalse;
}
if(getClass()!=obj.getClass())
{
returnfalse;
}
finalTraditionalEmployeeother=(TraditionalEmployee)obj;
if((this.lastName==null)?(other.lastName!=null):!this.lastName.equals(other.lastName))
{
returnfalse;
}
if((this.firstName==null)?(other.firstName!=null):!
this.firstName.equals(other.firstName))
{
returnfalse;
}
if((this.employerName==null)?(other.employerName!=null):!
this.employerName.equals(other.employerName))
{
returnfalse;
}
if(this.gender!=other.gender)
{
returnfalse;
}
returntrue;
}
Objectcloningthroughclone()orcloneableinterface
Arrayarrayisacollectionofsimilartypeofelementsthathavecontiguousmemorylocation
dataType[]arrayRefVar;(or)
dataType[]arrayRefVar;(or)
dataTypearrayRefVar[];
InitializationarrayRefVar=newdatatype[size];
inta[]={33,3,4,5};//declaration,instantiationandinitialization
inta[]={33,3,4,5};
min(a);//passingarrayinthemethod
//declaringandinitializing2Darray
intarr[][]={{1,2,3},{2,4,5},{4,4,5}};
StrictfpThestrictfpkeywordensuresthatyouwillgetthesameresultoneveryplatformifyou
performoperationsinthefloatingpointvariable.
strictfpclassA{}//strictfpappliedonclass
strictfpinterfaceM{}//strictfpappliedoninterface
classA{
voidm(){}//strictfpappliedonmethod
}
Javadocenterinthecmdpromptjavadoc<sourcepath>/home/docs/<javafile>Example.java
Serializationpurposeofjavaserializationistowritethestateofanobjectintoastream,sothat
itcanbetransportedacrossanetworkandthatobjectcanberecreatedagainatthereceivingendof
thenetwork.
Deserializationistheprocessofgettingtheobjectbackfromthefiletoitsoriginalform.
Serializationisusuallyusedwhentheneedarisestosendyourdataovernetworkorstoredinfiles.
Bydatawemeanobjectsandnottext.
NowtheproblemisyourNetworkinfrastructureandyourHarddiskarehardwarecomponentsthat
understandbitsandbytesbutnotJAVAobjects.SerializationisthetranslationofyourJavaobject's
values/statestobytestosenditovernetworkorsaveit.Herearesomeusesofserialization:
Topersistdataforfutureuse.
Tosenddatatoaremotecomputerusingsuchclient/serverJavatechnologiesasRMIorsocket
programming.
Toexchangedatabetweenappletsandservlets.
TostoreusersessioninWebapplications.
Tosendobjectsbetweentheserversinacluster
Streamsthatcontainmethodsforserializinganddeserializinganobjectare:
ObjectOutputStream:ObjectOutputStreamclasscanbefoundinjava.iopackagethatwritesprimitivedata
typesofJavaobjectstoanOutputStream.
publicfinalvoidwriteObject(Objectx)throwsIOException
ObjectInputStream:AnObjectInputStreamdeserializeoriginaldataandobjectspreviouslywrittenusing
anObjectOutputStream.ObjectInputStreamisusedtorecoverthoseobjectspreviouslyserialized.
publicfinalObjectreadObject()throwsIOException,ClassNotFoundException
ExampleofSerialization:
classEmployeeimplementsSerializable{
}
publicclassSerializabledemo{
publicstaticvoidmain(Stringargs[])
Employeee=newEmployee();
FileOutputStreamfileOut=newFileOutputStream(targetfilename.ser);
ObjectOutputStreamoutput=newObjectOutputStream(fileOut);
output.writeObject(e);
output.close();
fileOutput.close();
}
publicclassDeserializeDemo{
publicstaticvoidmain(String[]args)
{
Employeee=null;
FileInputStreamfileIn=newFileInputStream("/tmp/employee.ser");
ObjectInputStreamin=newObjectInputStream(fileIn);
e=(Employee)in.readObject();
in.close();
fileIn.close();
System.out.println("Name:"+e.name);
System.out.println("Address:"+e.address);
}
Stringimmutableobjectsthatholdsequenceofcharacters.Storedinheap
Howtomakeaclassimmutable?
1.
2.
3.
4.
Dontprovidesettermethodsmethodsthatmodifyfieldsorobjectsreferredtobyfields.
Makeallfieldsfinalandprivate
Dontallowsubclassestooverridemethodsmaketheclassfinal
SpecialattentionwhenhavingmutableinstancevariablesIdentifymutable&immutable
variablesandreturnnewobjectswithcopiedcontentforallmutableobjects.Immutable
variablescanbereturnedsafelywithoutextraeffort
WaystocreateStringobjects:
Case1:BelowcodecausesJVMtoverifyifthereisalreadyastringabc(samecharsequence).
Ifsuchstringexist,JVMsimplyassignthereferenceofexistingobjecttovariablestr,
otherwiseanewobjectabcwillbecreatedanditsreferencewillbeassignedtovariable
str.//createsoneStringobjectandonereferencevariable
Strings="abc";
Case2:Createstwoobjects,andonereferencevariable,Oneobjectinpoolandonein
nonpool(heap)memory
Strings=newString("abc");
Stringcomparison
1.
2.
3.
Byequals()methodcomparesvalues
By==operatorcomparesreferencesandnotvalues
BycompareTo()methodcomparesvaluesandreturnsanint
s1==s2:0
s1>s2:positivevalue
s1<s2:negativevalue
Stringconcat(+orconcat())
Strings=50+30+"Sachin"+40+40;//80Sachin4040
Method
1)publicbooleanequals(ObjectanObject)
2)publicbooleanequalsIgnoreCase(String
another)
3)publicStringconcat(Stringstr)
4)publicintcompareTo(Stringstr)
5)publicintcompareToIgnoreCase(String
str)
Description
Comparesthisstringtothespecifiedobject.
ComparesthisStringtoanotherString,ignoringcase.
Concatenatesthespecifiedstringtotheendofthis
string.
Comparestwostringsandreturnsint
Comparestwostrings,ignoringcasedifferences.
Returnsanewstringthatisasubstringofthis
string.
Returnsanewstringthatisasubstringofthis
7)publicStringsubstring(int
string.Indexstartsat0beginningindexinclusive&
beginIndex,intendIndex)
endindexexclusive
ConvertsallofthecharactersinthisStringtoupper
8)publicStringtoUpperCase()
case
ConvertsallofthecharactersinthisStringtolower
9)publicStringtoLowerCase()
case.
Returnsacopyofthestring,withleadingandtrailing
10)publicStringtrim()
whitespaceomitted.
11)publicbooleanstartsWith(Stringprefix) Testsifthisstringstartswiththespecifiedprefix.
12)publicbooleanendsWith(Stringsuffix)
Testsifthisstringendswiththespecifiedsuffix.
Returnsthecharvalueatthespecifiedindex.Index
13)publiccharcharAt(intindex)
startsat0.
14)publicintlength()
Returnsthelengthofthisstring.
Returnsthestringfromthepoolifitexist,otherwise
15)publicStringintern()
fromnonpool
16)publicbyte[]getBytes()
Convertsstringintobytearray.
17)publicchar[]toCharArray()
Convertsstringintochararray.
18)publicstaticStringvalueOf(inti)
convertstheintintoString.
19)publicstaticStringvalueOf(longi)
convertsthelongintoString.
20)publicstaticStringvalueOf(floati)
convertsthefloatintoString.
21)publicstaticStringvalueOf(doublei)
convertsthedoubleintoString.
22)publicstaticStringvalueOf(booleani) convertsthebooleanintoString.
23)publicstaticStringvalueOf(chari)
convertsthecharintoString.
24)publicstaticStringvalueOf(char[]i)
convertsthechararrayintoString.
25)publicstaticStringvalueOf(Objectobj) convertstheObjectintoString.
26)publicvoidreplaceAll(String
ChangesthefirstStringwithsecondString.
firstString,StringsecondString)
Splitthestringbasedondelimiter
27)String[]split(regex,limit)
StringBufferStringBufferclassisusedtocreatemutable(modifiable)string.TheStringBufferclass
issameasStringexceptitismutableandSynchronised.
6)publicStringsubstring(intbeginIndex)
1.
publicsynchronizedStringBufferappend(Strings):isusedtoappendthespecifiedstringwith
thisstring.Theappend()methodisoverloadedlikeappend(char),append(boolean),append(int),
append(float),append(double)etc.
2.
publicsynchronizedStringBufferinsert(intoffset,Strings):isusedtoinsertthespecified
stringwiththisstringatthespecifiedposition.Theinsert()methodisoverloadedlike
insert(int,char),insert(int,boolean),insert(int,int),insert(int,float),insert(int,
double)etc.
3.
publicsynchronizedStringBufferreplace(intstartIndex,intendIndex,Stringstr):isusedto
replacethestringfromspecifiedstartIndexandendIndex.
4.
publicsynchronizedStringBufferdelete(intstartIndex,intendIndex):isusedtodeletethe
stringfromspecifiedstartIndexandendIndex.
5.
6.
7.
publicsynchronizedStringBufferreverse():isusedtoreversethestring.
publicintcapacity():isusedtoreturnthecurrentcapacity.
publicvoidensureCapacity(intminimumCapacity):isusedtoensurethecapacityatleastequal
tothegivenminimum.
8. publiccharcharAt(intindex):isusedtoreturnthecharacteratthespecifiedposition.
9. publicintlength():isusedtoreturnthelengthofthestringi.e.totalnumberofcharacters.
10. publicStringsubstring(intbeginIndex):isusedtoreturnthesubstringfromthespecified
beginIndex.
11. publicStringsubstring(intbeginIndex,intendIndex):isusedtoreturnthesubstringfromthe
specifiedbeginIndexandendIndex.
StringBuilderStringBuilderclassisusedtocreatemutable(modifiable)string.TheStringBuilder
classissameasStringBufferclassexceptthatitisnonsynchronized.
StringTokenizerbreaksastringintotokens.
Publicmethod
Description
booleanhasMoreTokens()
checksifthereismoretokensavailable.
returnsthenexttokenfromtheStringTokenizer
StringnextToken()
object.
StringnextToken(String
returnsthenexttokenbasedonthedelimeter.
delim)
booleanhasMoreElements()
sameashasMoreTokens()method.
ObjectnextElement()
sameasnextToken()butitsreturntypeisObject.
intcountTokens()
returnsthetotalnumberoftokens.
Exceptionhandling:
Anexceptionisanevent,whichoccursduringtheexecutionofaprogram,thatdisruptsthenormalflow
oftheprogram'sinstructions.
1.
CheckedExceptionTheclassesthatextendThrowableclassexceptRuntimeExceptionandErrorare
knownascheckedexceptionse.g.IOException,SQLException,CNF,FNFetc.Checkedexceptionsare
checkedatcompiletime.
2.
UncheckedExceptionTheclassesthatextendRuntimeExceptionareknownasuncheckedexceptions
e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExceptionetc.Unchecked
exceptionsarenotcheckedatcompiletimerathertheyarecheckedatruntime.
3.
ErrorErrorisirrecoverablee.g.OutOfMemoryError,VirtualMachineError,AssertionErroretc.
inta[]=newint[5];
a[10]=50;//ArrayIndexOutOfBoundsException
Strings="abc";
inti=Integer.parseInt(s);//NumberFormatException
Strings=null;
System.out.println(s.length());//NullPointerException
inta=50/0;//ArithmeticException
TryEnclosethecodethatmightthrowanexceptionintryblock.Mustbefollowedbyeithercatchor
finallyblock.
CatchCatchblockisusedtohandletheException.Allcatchblocksmustbeorderedfrommost
specifictomostgeneral
Finallyfinallyblockcanbeusedtoput"cleanup"codesuchasclosingafile,closingconnection
etc.
**Thefinallyblockwillnotbeexecutedifprogramexits(eitherbycallingSystem.exit()orbycausing
afatalerrorthatcausestheprocesstoabort).
Throwusedtoexplicitlythrowanexception,eitherchecked,uncheckedorcustomexception.
ExceptionpropogationBydefaultUncheckedExceptionsareforwardedincallingchain(propagated)
Bydefault,CheckedExceptionsarenotforwardedincallingchain(notpropagated)
Throwsdeclaresanexception.Checkedexceptioncanbepropogatedonlywiththrowskeyword.
Whichexceptionshouldbedeclared?checkedexceptiononly,because:
uncheckedException:underyourcontrolsocorrectyourcode.
error:beyondyourcontrole.g.youareunabletodoanythingifthereoccurs
VirtualMachineErrororStackOverflowError
Nested/InnerClasses:logicallygroupedclasses&requireslesscodetowrite
1.
Nonstaticnestedclass(innerclass)
MemberinnerclassAclassthatisdeclaredinsideaclassbutoutsideamethodisknownas
memberinnerclass.Canbeinvokedwithinandoutsidetheclass.
Invocationwithintheclass
Outsidetheclass
classOuter{
classOuter{
classInner{
classInner{
voidmsg()
{system.out.println(hi)
voidmsg()
{system.out.println(hi)
}}}
publicvoiddisplay(){
InnerinObj=newInner();}
classOtherClass{
publicstaticvoidmain(Stringargs[]){
publicstaticvoidmain(Stringargs[]){
OuteroutObj=newOuter();
Outerobj=newOuter();
outObj.display();//output:hi
Outer.Innerin=obj.newInner();
in.msg();
}
Anonymousinnerclassaclassthathasnoname.Canbeaclass,abstractclassor
interface.
classiscreatedbutitsnameisdecidedbythecompiler.
abstractclassEmployee{
abstractvoidempType();
}
classCompany{
publicstaticvoidmain(Stringargs[]){
Employeee=newEmployee(){
voidempType(){System.out.println(Parttime);}};
e.empType();
}
MethodlocalinnerclassAclassthatiscreatedinsideamethodisknownaslocalinner
class.Ifyouwanttoinvokethemethodsoflocalinnerclass,youmustinstantiatethis
classinsidethemethod.
Rules:Localvariablecan'tbeprivate,publicorprotected.
Localinnerclasscannotbeinvokedfromoutsidethemethod.
Localinnerclasscannotaccessnonfinallocalvariable.
classCompany{
voiddisplayDept(){
classDepartment{
voiddeptDisplay(){
System.out.println(ITDept);}
}
Departmentdept=newDepartment();
Dept.deptDisplay();
}
}
NOTE:Anonymousinnerclassesandlocalclassescanaccessvariablesinthesurroundingscopeonlyif
thevariablesarefinal
2.
StaticnestedclassAstaticclassthatiscreatedinsideaclassisknownasstaticnestedclass.
Itcannotaccessthenonstaticmembers.
Itcanaccessstaticdatamembersofouterclassincludingprivate.
staticnestedclasscannotaccessnonstatic(instance)datamemberormethod.
classOuter{
staticintdata=10;
staticclassInner{
voidmsg(){system.out.println(hi+data)
}
publicvoidmain(Stringargs[]){
Outer.Innerobj=newOuter.Inner();
obj.msg();//output:hi10}
}
Twoclasseshavebeenaddedtojava.utilinsupportofenums:EnumSet(ahighperformanceSet
implementationforenums;allmembersofanenumsetmustbeofthesameenumtype)andEnumMap(a
highperformanceMapimplementationforusewithenumkeys).
IterableInterfacejava.langpackage.Implementingthisinterfaceallowsobjecttouseforeach
ComparableInterfacejava.langpackage.usedtoordertheobjectsofuserdefinedclass,wrapperor
stringclass.ProvidesonlyonemethodcompareTo(obj)andcomparisonismadeonasinglemember
variableonly.
ComparatorInterfacejava.utilpackage.usedtoordertheobjectsofuserdefinedclassandprovides
methodcompare(obj1,obj2)andcomparisoncanbemadeonanydatamember.
Interviewquestions:
System.out.println
Systemfinalclassinjavalangpackagewhichconsistsofonlystaticfieldsandmethods.
outastaticfieldinSystemclassoftypePrintStream
printlnamethodinPrintStreamclass
Implicitcastingeg.inttolong.
Explicitcastingeg.intI=(int)long
upcasting
downcastingcastingfromageneraltoamorespecifictype,castingdownthehierarchy
Phantommemoryisfalsememory.Memorythatdoesnotexistinreality.
HowdoureverseaString?
Strings="helloadithya";
System.out.println(newStringBuffer(s).reverse());//ayhtidaolleh
Reversethewords
Strings="adithyaismylittlehero";
String[]str=s.split("");
System.out.println(str.length);//5
for(inti=str.length1;i>=0;i){
System.out.print(str[i]+"");//herolittlemyisadithya
}
Palindrome
Strings="adithya";
Strings2=(newStringBuffer(s).reverse()).toString();
if(s.equals(s2)){
System.out.println("palindrome");
}else{
System.out.println("notpalindrome");
}
//inallabove3examplesuseStringBuilderinsteadofStringBuffer
Waystoiteratealist
for(inti=0;i<arrayList.size();i++)
{
System.out.println(arrayList.get(i));//accesswithget()method
}
Iteratorit=arrayList.iterator();//iterator
while(it.hasNext())
{
System.out.println(it.next());
}
for(Strings:arrayList)//useforeachloop
{
System.out.println(s);
}
waystoiterateahashmap
//initializeaMap
Map<String,String>map=newHashMap<String,String>();
map.put("1","Jan");
map.put("2","Feb");
map.put("3","Mar");
//Map>Set>Iterator>Map.Entry>troublesome
Iteratoriterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.EntrymapEntry=(Map.Entry)iterator.next();
System.out.println("Thekeyis:"+mapEntry.getKey()
+",valueis:"+mapEntry.getValue());
}
//moreelegantway
for(Map.Entry<String,String>entry:map.entrySet()){
System.out.println("Key:"+entry.getKey()+"Value:"
+entry.getValue());
}
//weiredway,butworksanyway
for(Objectkey:map.keySet()){
System.out.println("Key:"+key.toString()+"Value:"
+map.get(key));
}
equals()andhashCode()contract:
equals()methodisusedtodeterminetheequalityoftwoobjects.
hashCode()methodisusedinhashtablestodeterminetheequalityofkeys.
WheneveritisinvokedonthesameobjectthehashCode()mustconsistentlyreturnthesameinteger.
Iftwoobjectsareequalaccordingtotheequals(Object)method,thencallingthehashCodemethod
oneachofthetwoobjectsmustproducethesameintegerresult.
Itisnotrequiredthatiftwoobjectsareunequalaccordingtotheequals(java.lang.Object)
method,thencallingthehashCodemethodoneachofthetwoobjectsmustproducedistinctinteger
results.
ClassNotFoundException&NoClassDefErrorbotherrorsoccurwhenaclassisnotfound.
CNFisanexceptionthatoccurswhenusingreflection&theclassisnotfound.Eg:Class.forName(),
Class.load()
NCDLinkageError.Whenaclassisavailableatcompiletime,butthesameismissingduring
runtime.
JavasupportsonlyPassbyValue.
GarbagecollectionJVMintermittentlyrunsanalgorithmcalledmarkandsweepwhichkeepstrackof
whichobjectsarealiveandwhicharenotaremarkedforreclaim.System.gc()andRuntime.gc()suggest
forGCandnotforcesforGC.System.exit()willstopGC.
GarbageCollectionreferstoremovingofobjectswhicharenolongerinuse.Itisawellknownfact
thatirrespectiveoftheirscopeobjects,Javastoresobjectsinheap.Thus,ifwekeeponcreating
objectswithoutclearingtheheap,ourcomputersmightrunoutofheapspaceandwegetOutofMemory
error.GarbageCollectioninJavaisamechanismwhichiscontrolledandexecutedbytheJavaVirtual
Machine(JVM)toreleasetheheapspaceoccupiedbytheobjectswhicharenomoreinuse.TheJVM
executesthisprocesswiththehelpofademonthreadcalledtheGarbageCollector.Thegarbage
collectorthreadfirstinvokesthefinalizemethodoftheobject.Thisperformsthecleanupactivityon
thesaidobject.AsadeveloperwecannotforcetheJVMtorunthegarbagecollectorthread.Though
therearemethodse.gRuntime.gc()orSystem.gc(),butnoneoftheseassurestheexecutionofgarbage
collectorthread.ThesemethodsareusedtosendgarbagecollectionrequeststotheJVM.Itisupto
theJavaVirtualmachinewhenitwillinitiatethegarbagecollectionprocess.
ForthesakeofGarbageCollectioninJava,Heapmemoryisdividedintothreeparts:
YoungGeneration
TenuredorOldGeneration
PermanentGeneration
YoungGenerationisfurtherdividedintothreepartsknownnamelyEdenspace,Survivor1andSurvivor2
space.AliveobjectresidesinEdenspaceandafteraMinorGarbagecollectioniftheobjectisstill
liveitismovedintosurvivor1andsubsequentlytosurvivor2.FinallyaftertheMajorGarbage
collectiontheobjectismovedtoOldortenuredgeneration.TherearefollowingtypesofGarbage
Collector:
SerialCollector
ThroughputCollector
ParallelOldGenerationCollector
ConcurrentLowPauseCollector
IncrementalLowPauseCollector
ThereisnomanualwayofdoinggarbagecollectioninJava.System.runFinalization()and
Runtime.getRuntime.runFinalization()methodisusedtorunfinalizersforalltheeligibleobjectsfor
GC.
protectedvoid
finalize