Вы находитесь на странице: 1из 44

Tips to clear SCJP exam Tips to clear SCJP exam 1) Give yourself atleast 3 months for preparation 2) Study

at least one boo preffered!"#$ 3) Try %ritin& the pro&rams %ith experiments ') $e very clear about overloadin& and overridin& rules () Give 1)*2) SCJP moc exams+ Some are available on this blo& at! SCJP ,oc exam archive -) $e clever in ommitin& options .) /very 0uestion %ill have 2 fixed options 1Compilation error and exception at runtime) 2) 3oo carefully to find ho% many choices are to be mar ed 4) Go on to solve 0uestions that have less to read and easy to ans%er as by the end of SCJP exam you %ill be &ettin& exhausted and loosin& patience 1)) 5irst &uess %hich concept is bein& tested and then brin& out all the facts about that concept from the bac of your mind+ 11) There is an option to ,ar the 0uestion so that before closin& the test you can easily find %hich 0uestion you %ant to revie%+ 5or each 0uestion you have doubt6 chec the chec box labeled ,ar at the top left corner+ 7appy SCJP Crac in&+ 3eave your comments about this post+ You might also like: 7o% to Send 7TTP P8ST 9e0uest in Java Java :erbose 8ptions for 9unnin& Pro&rams 9/ST ;eb Service <ntervie% =uestions 7o% to <terate >rray3ist in Struts2 what are the differences between HashMap and Hashtable 7ashtable and 7ashmap are different in the sense that 7ash,ap is unsynchroni?ed but 7ashtable is synchroni?ed %hich means that once an operation is bein& performed on the 7ashtable6 no other method@thread can perform an operation on the same 7ashtable+ $ut this second operation may be performed on the 7ash,ap+ The positive point of not havin& synchroni?ation is that the operations are faster but the do%nside is that someone else may update the same 7ash,ap as you are updatin&+ The second difference is that 7ash,ap permits nulls as eys as %ell as values but 7ashtable doesnAt+ This means that every ey and value in 7ashtable must be non null+ <f

%e loo at 7ash,ap6 there can be one ey as null as the eys are uni0ue and hence no t%o eys as null+ $ut values for multiple eys can be null in case of 7ash,ap+ e0uals method on arrays The e0uals method is not overloaded for arrays %hich means that! intBCa D ne% intBCE1FGintBCb D ne% intBCE1FGSystem+out+println1a+e0uals1b))G %ill return false because it %ill be the e0uals1) method 8bHect class that %ill be called and %e no% that this version of e0uals1) method chec s for the obHect references and not the values hence false+ How man! choices to choose in SCJP exam

"f !ou are wondering as to how to find out which choices are correct in a #uestion ha$ing multiple choices as answer% The exam will pro$ide !ou the information on how man! choice to choose for each #uestion% &$en if it is one choice' it will be mentioned% The text will go like: Choose ( correct options% )e end b! pro$iding a sample #uestion: )hich of the following are a part of Collections a* +eflection b* Set c* HashMap d* Cell Choose ( correct options ,nd !ou will answer: b and c
)hat is ConcurrentModification&xception Concurrent,odification/xception is thro%n %hen you remove the elements of a Collection usin& its method instead of the one provided by the <terator interface+ ;hen iteratin& usin& the <terator6 if it is found that the collection has been modified usin& some other method than the one provided by the <terator interface6 this exception is thro%n+ $ut the J>:> >P< says that this behaviour is not &auranteed+ what is reflection ,P"

$esides creatin& obHects of a class and callin& constructors@methods on that obHect6 accessin& the properties@variables of the class6 theres is somethin& else %hich can be done %ith the classes+ The reflection is a reflection of a class as seen by the J:,+ The J:, %ill see a class as havin& some methods6constructors6instance variables etc+ The mother of reflection >P< is the Class class+ 5or every class that is present in a pro&ram or provided by SIJ as part of Hava >P<6 there exists an instance of Class class for that class+ This may sound stran&e6 but lets ta e and example+ Say < have created a class named foo in the proHect as! public class foo E foo1) EF KKKKKK KKKKKK F Jo% i create bar class to &ive a feelin& of the reflection >P<+ public class barE foo f1 D Class+forJame1LfooL)G @@created the foo obHect F Please note that the class bar is declared as public and hence is obviously in some other proHect@pac a&e+ ;e never imported the foo class to create an obHect of it+ That %as possible because of the reflection >P< and the Class class+ The bottomline of all this discussion is that a instance of the Class class reflects an! class% Jo% %e modify the bar class as sho%n belo%! import fooG @@modify as per your proHect settin&s+ public class barE foo f1 D Class+forJame1LfooL)G @@created the foo obHect Class c1 D foo+classG Hava+lan&+reflect+ConstructorBC const1 D c1+&etConstructors1)G System+out+println1const1B)C+&etJame1))G F 7ere %e &et the instance of the Class class correspondin& to the foo class and then &et an array of its constructors by invo in& the method &etConstructors1) on it and then display the name of the first constructore present in the foo class+ < hope this has made thin&s more clear and no% you can bro%se the Hava+lan&+reflect pac a&e to no% more about %hat can be done %ith the reflection >P<+ $ut there is a %ord of caution %ith usin& the reflection >P< because all this happens at runtime6 the performance may be effected because of over usin& the reflection >P<+ -uestion regarding main method in SCJP exam

The main methos is invo ed by the J:, and it doesnMt create any instance of the class before callin& the main method+ This mandates the main method to be static and it has to be public so that it is visible outside of its pac a&e to the J:, and it should not return any value %hich means that the return type of the main method should be specified as void+ Thus a valid si&nature of the main method %hich can be called by the J:, is! public static void main1Strin&BC ar&s) ar&s represent the Strin& array %hich contains the command line ar&uments+ The exam %ill have 0uestion %hich has some loopin&@conditional structure %ith a different main method+ > number of options %ill be &iven li e compilation fails6 some dummy output6 exception at runtime etc+ $ut the point to note is that if you omit static from the above method6 it doesnMt become an invalid method to J:, but it becomes Hust another method+ <t is not the main %ord that &ives the po%er of startin& point to a method6 but itMs a list of specification %hich a method has to conform before it can be the startin& point+ >ll the follo%in& si&natures are non*starters in a class! public void main1Strin&BC ar&s) public static int main1Strin&BC ar&s) private static void main1Strin&BC ar&s) public static void main1231Strin&BC ar&s) public static void main1Strin& ar&s) >nd follo%in& are some starters public static void main1Strin& ar&sBC) static public void main1Strin&BC ar&s) public static void main1Strin&BC str) <f a class does not have starter main method then an error as JoSuch,ethod/rror is thro%n by J:, Jo% comin& to that exam 0uestion6 the correct ans%er in case there is no starter main method in the class is either NThe code %ill not runO or NJone of theseO %hichever is present but mar NThe code %ill not runO if it present in the options+ )hat is .na$ailable&xception The Inavailable/xception is thro%n by the servlet container %hen the servlet is not active+ The destroy1) method is not called because the servlet is considered not bein& instatiated+ <n such a case and after %aitin& for some time6 a ne% instance is created by the container+

SingleThreadModel implementation <f a servlet implements the Sin&leThread,odel interface6 then the servlet container may create multiple instances of the servlet so as to handle heavy re0uest load+ 7ere6 all re0uest %ill still be seriali?ed to a sin&le instance only+ This is event true for a distibutable application+ < mean that if the application is distributable and its servlets implement Sin&leThread,odel interface then also the above described behaviour may happen internaly+ The only difference %ill be that there %ill be multiple instances of servlet per :,+ Jote! ,ultiple :,As run on each machines in case of distributable application+ You might also like: ,y 3ist of Top 2) Java 9elated $oo s 7o% to <terate >rray3ist in Struts2 Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication /ink)ithin

Conditional 0&T re#uests P1ST&2 3Y S,42&&P /,3&/S: C142"T"14,/ 0&T +&-.&STS' HTTPS&+5/&T 6 C1MM&4TS > conditional &et operation is one %here the G/T re0uest is issued only after some condition is met+ The &et3ast,odified1) method of 7ttpServlet &ets a resource only if it has been modified since a specified time+ This means that the server %ill not send the response to a G/T re0uest if the criterion of modification is not met+ You might also like: Java :erbose 8ptions for 9unnin& Pro&rams ,y 3ist of Top 2) Java 9elated $oo s 9/ST ;eb Service <ntervie% =uestions Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication /ink)ithin

)eb Ser$er and Ser$let Container P1ST&2 3Y S,42&&P /,3&/S: S&+5/&T C14T,"4&+' )&3 S&+5&+ 6 C1MM&4TS The servlet container %or s %ith a %eb@application server+ The servlet container reco&ni?es re0uests of particular format and sends the response bac after processin&+ The %eb server intercepts the 7TTP re0uests from client and for%ards to the servlet container+ The servlet container can be implemented in three %ays 1) $uilt into %eb server 2) $uilt as an add*on component of %eb server 3) $uilt as a separate process+ You might also like: Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication ,y 3ist of Top 2) Java 9elated $oo s Java :erbose 8ptions for 9unnin& Pro&rams Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat /ink)ithin

order of execution of static and non7static blocks P1ST&2 3Y S,42&&P 14 ,.0 8' (669 /,3&/S: 1+2&+ 1: &;&C.T"14 1: ST,T"C ,42 4147ST,T"C 3/1C<S' ST,T"C ,42 414 ST,T"C 3/1C<S "4 J,5, 8 C1MM&4T The static bloc in a class is executed every time the class is loaded and not every time an instance is created+ The static bloc s are executed before executin& instance bloc s+ The subclass instance bloc s are executed after executin& the superclass instance bloc s+ The subclass static bloc s are executed after executin& the superclass static bloc s+ Chec the above facts usin& the follo%in& pro&ram!

class 5oo E E System+out+println1LfooL)G F static E System+out+println1L5oo staticL)G F F public class $ar extends 5ooE E System+out+println1L$arL)G F static E System+out+println1L$ar staticL)G F public static void main1Strin&BC ar&s) E $ar b1 D ne% $ar1)G $ar b2 D ne% $ar1)G F F You might also like: Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 7o% to Send 7TTP P8ST 9e0uest in Java ,y 3ist of Top 2) Java 9elated $oo s /ink)ithin

c!clic inheritance P1ST&2 3Y S,42&&P /,3&/S: CYC/"C "4H&+"T,4C&' "4H&+"T,4C& "4 J,5, 6 C1MM&4TS The compiler chec s for cyclic inheritance li e a class extendin& another class and the second class extendin& the first class+ e+&+

Class 5oo extends $arEF Class $ar extends 5ooEF results in compiler error+ You might also like: Java :erbose 8ptions for 9unnin& Pro&rams ,y 3ist of Top 2) Java 9elated $oo s Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication /ink)ithin

inheritance in =a$a P1ST&2 3Y S,42&&P 14 J./ >6' (669 /,3&/S: "4H&+"T,4C& "4 J,5, 6 C1MM&4TS "nheritance in Ja$a means extension and code reuse as in term of ob=ect orientation with some difference in implementation% The class which pro$ides the general functionalit! is known as superclass' base class or parent of its children and the class which inherits this class is known as subclass' deri$ed class or child of base class% ,n example of inheritance can be a $ehicle and the car classes% )hile a car is a $ehicle but a $ehicle ma! or ma! not be car and ma! be a truck?bus% The Car class will inherit the $ehicle class which can pro$ide the basic properties of a $ehicle which is sure to be present in the car like appl!3rake' accelerate etc% The Car class will add more properties specific to a car% ,s a $ehicle will alwa!s be concrete hence the 5ehicle class should be abstract which means that a new instance of 5ehicle class can@t be created using the new operator% Coming back to inheritance' creation of 5ehicle class makes it eas! to code as there is no need to implement each method which a 5ehicle is supposed to implement%

21M parsing P1ST&2 3Y S,42&&P /,3&/S: 21M ,P"' P,+S"40 ;M/ 21C.M&4TS 6 C1MM&4TS 5unction to &et document by P8, parser public static synchroni?ed Pocument load1Strin& filename6 Strin& filePath) thro%s /xception E Pocument docG Pocument$uilder5actory factory D Pocument$uilder5actory+ne%<nstance1)G Pocument$uilder builder D factory+ne%Pocument$uilder1)G Strin& full5ilePath D filePath R filenameG 5ile file D ne% 5ile1full5ilePath)G 5ile<nputStream fis D ne% 5ile<nputStream1file)G <nputSource is D ne% <nputSource1fis)G doc D builder+parse1is)G fis+close1)G is D nullG fis D nullG file D nullG return docG F The document returned by this function can be used to extract more data by usin& the methods li e &et/lements$yTa&Jame+ Jode3ist node3ist D doc+&et/lements$yTa&Jame1L<temL)G /ven ne% nodes can be added to the document and attributes can be added@modified+ You might also like: Java :erbose 8ptions for 9unnin& Pro&rams 7o% to Send 7TTP P8ST 9e0uest in Java 9/ST ;eb Service <ntervie% =uestions Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat /ink)ithin

S,; Parsing P1ST&2 3Y S,42&&P /,3&/S: P,+S"40 ;M/ 21C.M&4TS' S,; ,P" 6 C1MM&4TS S>Q parser can be created usin& either the xerces or J2S/ >P<+ $oth have a class named S>QParser+ 8n callin& the parse method of S>QParser6 the document is parsed and some events are raised parser+parse1ne% <nputSource1reader))G The events are catched by a Pefault7andler or its subclass+ The event methods are start/lement6 end/lement6 startPocument6 endPocument

)h! are thread related methods present in 1b=ect class P1ST&2 3Y S,42&&P 14 J./ 89' (669 /,3&/S: J,5,' 41T":YA*' 41T"0Y,//A*' TH+&,2S' ),"TA* 6 C1MM&4TS The threadin& methods are defined in 8bHect class because these methods are related to obHect loc s and any obHect can act as a loc and hence these methods are defined in the 8bHect class+ These methods are %ait1)6 notify1) and notify>ll1)+ These methods are final and return nothin&+ >ll of them must be called from a synchroni?ed bloc or method and the thread callin& them should pocess the loc on the obHect+ ;hile callin& %ait1) method6 the thread to release the loc on 8bHect on %hich %ait1) method is called and on callin& the notify1)@notify>ll1) ma es the other capture the loc +

Histor! of J(&& P1ST&2 3Y S,42&&P 14 J./ 8B' (669 /,3&/S: J(&&' J,5, 6 C1MM&4TS Java has been versioned since its inception+ <t has up&raded to Java ( %hich means Java 1+( version compiler but it %as the version 1+2 %hich chan&ed the %orld in dramatic chan&es+ The impact so hu&e that J2// 1vi? J// 1+2) %as envisioned+

,bstract classes in Ja$a P1ST&2 3Y S,42&&P 14 J./ 8C' (669 /,3&/S: ,3ST+,CT C/,SS&S' J,5,' SCJP' SCJP 8%D 6 C1MM&4TS >n abstract class is li e a normal class %ith the difference that it contains at least one abstract method or it extends another abstract class+ Thus the t%o conditions under %hich a class is and must be declared as abstract are! 8* "t extends another abstract class (* "t declares an abstract method% The above implies that at some point the hierarchy of abstract classes6 one class must have declares an abstract method+ So letMs discuss an abstract method+ >n abstract method loo s li e! abstract void foo(); The difference bet%een this and a normal method is that the abstract methods donMt have method body+ This means to compiler that the current class is not meanin&ful in the real %orld scenario and some other class %hich %ill be extendin& this class %ill provide complete definition of the abstract method+ <n a %ay6 this enforces that all subclasses of an abstract classes have to define the method body for abstract method+ >n abstract class definition loo s li e! abstract class Myfoo { abstract void foo(); } or it can be abstract class Myfoo {} or abstract class Myfoo { abstract void foo(); void anotherfoo() { System.out.println(I am not a abstract method); } The above example sho%s that an abstract class can have some implemented methods in addition to abstract methods+ Jo% %hat about the belo% code!

abstract class My notherfoo e!tends Myfoo { void "ron#$oo { System.out.println(%his is "ron#); } } The compiler %ill be more than happy in the above case because of the mar er abstract before the class+ 7ad the class not been declared as abstract6 the compiler %ould have flashed an error unless an implementation of the abstract method foo1)G has not be &iven in the subclass+ >s far as desi&n is concerned6 the abstract classes are provided so that some common &uidelines can be provided to the subclasses+ 5or e+&+ a class named as 5i&ure %ill have an abstract method as! abstract void set&olor(); %hich %ill ma e sure that S0uare6 9ectan&le and Trian&le %hich extend the 5i&ure class %ill have to provide a method body for the above method+ 8ne more implication of abstract classes is that since abstract classes are meant to be extended6 so they canMt be instantiated+ 7o%ever a reference can be declared and is declared 0uite often in %ell desi&ned application+ 5or e+& in the 5i&ure class above6 a reference to 5i&ure class can hold obHects of type S0uare6 9ectan&le and Trian&le and hence provides more usability+ Please note that final and abstract are mutually exclusive+ The point to be ta en home from the above discussion is that declare classes as abstract %here &enerality is implicit and more concrete implementations for this &enerality follo%+

2ifference between String and String3uffer P1ST&2 3Y S,42&&P /,3&/S: SCJP' ST+"40 ,42 ST+"403.::&+' ST+"40 5S ST+"403.::&+ 6 C1MM&4TS The Strin& class is final and Strin& obHects are immutable %hich means that the value of Strin& obHects canMt be modified+ $ut there are situations %here one needs to modify the underlyin& Strin& text+ To solve this problem6 Hava has Strin&$uffer class %hose obHects are mutable and can be modified usin& the methods+ This means that instead of returnin& a ne% obHect as in case of Strin& class6 the methods of Strin&$uffer class return the modified obHect+

8ther thin& to note about Strin&$uffer class is that the methods are synchroni?ed+ Strin&$uilder is another class %hose obHects are mutable but its methods are not synchroni?ed+ 5or the SCJP exam6 it is crucial to no% that Stri&$uffer class has constructor %hich can accept an obHect of type Strin& but the reverse is not true+ ,oreover6 the Strin& and Strin&$uffer obHects are never e0ual to each other even if the underlyin& text is same for both+

Strings in Ja$a P1ST&2 3Y S,42&&P 14 J./ 8E' (669 /,3&/S: :/Y)&"0HT 2&S"04 P,TT&+4' J,5,' ST+"40 /"T&+,/S' ST+"40S' ST+"40S "4 J,5, 6 C1MM&4TS The Strin& type is so %idely used that Java treats its values as literals %ithin double 0uotes+ $ut internally6 the Strin&s are stored as 8bHects+ Since they are so %idely used6 there is a dan&er that a Strin& %ritten by somebody may be over%ritten by others erroneously+ To avoid such ind of situation6 the Strin& class has been made final %hich means that no class can extend Strin& class so as to modify the operations %hich are meant to be standard for all users@pro&rammers+ ,oreover6 the Strin& obHects are immutable %hich means that the Strin& classMs methods donMt modify the Strin& obHect on %hich the method is invo ed+ <nstead6 they return a ne% Strin& obHect after modification operation+ Thus one invo es the trim1) method on a Strin& literal as Strin# a ' Strin# ; a.trim(); System.out.println(( ) a (); > ne% Strin& obHect is return by the trim1) method %hich is sho%n by the value printed by the 3rd line+ Thus %e have learnt that 1) String class is final 2) String ob=ects are immutable% >nother important concept associated %ith Strin&s is Strin& literals and the literal pool+ The J:, places all the Strin& literals in a separate pool and uses Strin& literals from this pool %hen referenced multiple times+ This saves on creatin& the same obHect a&ain+ 5or e+&+ Strin# a ' Strin#;

Strin# b ' Strin#; a '' * The ans%er to above 0uestion is true because the both a and b point to the same Strin& obHect present in the Strin& literal pool and this is also no%n as fly%ei&ht desi&n pattern+

1$erloading rules in Ja$a P1ST&2 3Y S,42&&P 14 J./ 8D' (669 /,3&/S: J,5,' 15&+/1,2"40' 15&+/1,2"40 +./&S "4 J,5, 6 C1MM&4TS 3etAs 0uic ly define overloadin& in a basic %ay! 1$erloading is using the same method name but different number?t!pe?order parameters %

Case1! > method named fix1) is defined in a class as! void fi!() { System.out.println(+fi!,,no parameters+); } This method can be overloaded6 if a method %ith name fix1) is defined in the same class but %ith different parameters as! void fi!(int t) { System.out.println(+fi!,,one parameters+); } The compiler %ill not flash any error in the above case+ > method call as fix12) %ill print BbCfix**one parametersB@bC on console $ut a method call as fix1) %ill print BbCfix**no parametersB@bC on console Case2! Consider the overloaded methods defined as! void fi!(int t) { System.out.println(+fi!,,one int parameters+); } void fi!(lon# t) { System.out.println(+fi!,,one lon# parameters+);

} Guess %hat %ill the call fix12) do+ Ses the int parameteri?ed function %ill be called+ Case3! Consider the methods in case2 redefined as! int fi!(lon# t) { System.out.println(+fi!,,one int parameters+); return -; } void fi!(lon# t) { System.out.println(+fi!,,one lon# parameters+); } The above methods are not overloaded because return types donAt matter+ The compiler %ill flash an error in this case+ Case'! Consider the methods in case2 redefined as! void fi!(lon# t) thro"s I./!ception{ System.out.println(+fi!,,one int parameters+); return -; } void fi!(lon# t) thro"s S01/!ception{ System.out.println(+fi!,,one lon# parameters+); } The above methods are a&ain not overloaded as exception declarations also donAt matter %hile overloadin&+ Case(! Consider the fix methods defined as in Case2 above void fi!(int t) { System.out.println(+fi!,,one int parameters+); return -; } void fi!(lon# t) { System.out.println(+fi!,,one lon# parameters+); }

and method call as char ch'-; s.fi!(ch); 7ere ch %ill be implicitly typecasted to match method+ The castin& %ill be done to a minimum %ider types of those available in the method call+ Thus in this case void fix1int t) %ill be called+ Case-! void fi!(int t(lon# u) { System.out.println(+fi!,,one int parameters+); return -; } void fi!(int t(float u) { System.out.println(+fi!,,one lon# parameters+); } > method call fix1262) in this case %ill %or but a method call fix1262+)) %onAt %or because the second ar&ument type double canAt be typecasted to float or lon&+ Thus it is the method calls that determine the ambi&uity of the overloaded methods+ Jo% an interestin& case+ Suppose there is a class $inarySearch %hich has its constructor declared as 2inarySearch() { 33some code } Jotice that constructors donAt have any return type+ Jo% declare a method as! int 2inarySearch() {33some code } > method call for the instance bs of class $inarySearch as bs+$inarySearch1) %ill not call the constructor+<ts a call to the second method %hich is a normal method+ Thus the constructor names %ith different return types are also allo%ed+ $ut that is an exception for constructor names only and not for other normal methods as seen in Case3+

difference between comparable and comparator interface P1ST&2 3Y S,42&&P /,3&/S: C1MP,+,3/& ,42 C1MP,+,T1+ "4T&+:,C&' J,5,' SCJP E C1MM&4TS The ey difference bet%een comparable and comparator interface is! The comparable interface should be used %hen the current obHect is to be compared to

obHects of its type only+ The comparator should be used %hen some external class is ta in& your class as a parameter for some comparison operation and it doesnAt no% ho% to compare the obHects and expects you to &ive it+ <n this case you canAt &ive your class as the comparator+ <t has to be some other class %hich implements comparator interface and does the comparison+ The above is %hat %e %ill learn from the follo%in& discussion about the t%o interfaces+ 3ets start %ith the comparable interface! The comparable interface is present in Hava+lan& pac a&e+ This means that you need not import this interface %hen you are implementin& this interface+ This interface has only one method %hich has the si&nature as! public int compare%o(.b4ect o); >s the name su&&ests you %ant this obHect to be compared to someone else+ <n Java syntax6 the code is! CompareClass cmp1 D ne% CompareClass1)G CompareClass cmp2 D ne% CompareClass1)G cmp1+compareTo1cmp2)G The best definition of this interface %ill be the one &iven in Java >P< %hich is reproduced here! This interface imposes a total ordering on the ob=ects of each class that implements it <ts all upto the implementor to decide ho% and %hich ind of obHects %ill he be comparin& %ith the 8bHect for %hich compareTo method has been invo ed+ Some facts related to comparable interface are as follo%s! 1) The compareTo1) method should return *ve6?ero or Rve inte&er dependin& upon %hether this obHect is less than6e0ual to or &reater than the specified obHect 2) The value returned by compareTo1) should be consistent %ith the value returned by e0uals1) method of the same class+ if not so6 the class should explicitly state that+ 3) >ny comparison %ith null should thro% JullPointer/xception ')<f the obHect of the classes %hich implement this interface can be used as eys in the Sorted,ap or SortedSet+ ()3ists and >rrays that implemet this interface can be sorted usin& the Collections+sort13ist@>rray) method %ithout specifyin& any external comparator+ /xample! 3ets ta e the example of Strin& class+ 7ere is a sample code %hich %ill clear the compareTo method for you!

public class %est { public static void main(Strin#56 ar#s) { Strin# str7 ' +bar+; Strin# str- ' +barfoo+; int compare8esult ' str7.compare%o(str-); if (compare8esult 9 :){ System.out.println(str7 ) +is less than+ ) str-); }else if (result '' :){ System.out.println(str7 )+is e;ual to+ ) str-); }else{ System.out.println(str7 )+is #reater than+ ) str-); } } }

<n this example6 %e are comparin& Strin& obHects %ith other Strin& obHects and the comparTo method resides %ithin the Strin& class itself+ Jo% lets see the comparator interface+ The Comparator interface is a part of util pac a&e and needs to explicitly imported+ The &eneral contract that is true for comparable is also true for comparator interface %hich is restated here because of its importance+ The value returned by the compare method of the class implementin& the comparator interface should also return the same value %ith e0uals1) method+ This is important because the SortedSet and Sorted,ap %ill behave stran&ely+ There are t%o methods specified in the comparator interface %hich have the si&nature as follo%s! int compare(% o7( % o-); boolean e;uals(.b4ect ob4); The compare1) method should return *ve6?ero or Rve inte&er dependin& upon %hether this obHect is less than6e0ual to or &reater than the specified obHect /xample! import 4ava.util.<;

class %est{ private int prop7; public void set=rop7(int prop7){ this.prop7'prop7; } public int #et=rop7(){ return this.prop7; } } class %est&omparator implements &omparator{ public int compare(.b4ect ob47( .b4ect ob4-){ int test7 ' ( (%est) ob47).#et=rop7(); int test- ' ( (%est) ob4-).#et=rop7(); if( test7 > test- ) return 7; else if( test7 9 test- ) return ,7; else return :; } } So %hats the distin&uishin& part bet%een the comparable and comparatorT ;ell its the difference in terms of the method si&nature at code level+ $ut in terms of desi&n level6 there is a bi& difference and should not be overloo ed+ The comparable interface should be used %hen the current obHect is to be compared to obHects of its type only+ The comparator should be used %hen some external class is ta in& your class as a parameter for some comparison operation and it doesnAt no% ho% to compare the obHects and expects you to &ive it+ <n this case you canAt &ive your class as the comparator+ <t has to be some other class %hich implements comparator interface and does the comparison+ > typical example of this is the Collections+sort13ist l6 Comparator c) method+ $elo% is the lin to some more material on this topic

Comparable <nterface >P< Comparable <nterface >P<

,fter SCJP what P1ST&2 3Y S,42&&P 14 J./ 88' (669 /,3&/S: SC)C2 ,:T&+ SCJP 6 C1MM&4TS ;ell you are no% SCJP after passin& the so called SCJP exam and are no% %onderin& %hat to do no%T The ans%er is analy?e+ >naly?e %hat role you %ill be doin& %hile you %ill be codin&+ ;ill you be %or in& on client side and %or in& %ith Servlets6 JSP etc+ or you %ill be %or in& on the server side and %or in& %ith /J$Ms etc+ ;ell in both cases6 there is somethin& that can ma e your resume more appealin& and that is the SC;CP exam+ ;hile SCJP sho%s that the person has no%led&e of Java6 SC;CP sho%s that the person has no%led&e of Servlets6 JSP+ SC;CP stands for Sun Certified ;eb Component Peveloper and current version offered by Sun is SC;CP 1+(+ There is pre*re0uisite before one can appear for the SC;CP exam and that is the person should be SCJP %hich means SCJP 1+16 SCJP 1+26 SCJP 1+' or SCJP 1+-+ ;hatever version of SCJP have you passed6 you can al%ays appear for the SC;CP exam+ < as ed you to analy?e6 %hat %ill you be doin& after SCJP because there is life una%are of a client*server paradi&m 1may be S%in& or the li es) So all those &uys %ho fall in first cate&ory &o for SC;CP and decorate your resume %ith that lo&o of SC;CP+

checked and unchecked exceptions P1ST&2 3Y S,42&&P /,3&/S: CH&C<&2 ,42 .4CH&C<&2 &;C&PT"14S' &;C&PT"14S "4 J,5,' J,5, 8 C1MM&4T The exceptions can be of t%o types vi? chec ed and unchec ed+ Chec ed exceptions mean to compiler those exceptions from %hich the pro&ram can occur but that are not caused by pro&rammin& bu&s li e 5ile not available on hard dis 6 or Patabase is shutdo%n as pro&ram is tryin& to ma e some connection+ The compiler no%s these are areas %here problem can occur %hich is not due to a problem %ith the code+ Thus the compiler eeps a chec on the statements %hich try to induld&e in such activities+ e+& Try some code li e! public static void main1Strin&BC ar&s) E 5ile;riter f D ne% 5ile;riter1L/!UUne%+txtL)G F The compiler complains that Nunhandled exception of type <8/xceptionO Jo% %rite somethin& as! public static void main1Strin&BC ar&s) E 5ile;riter f D ne% 5ile;riter1L/!UUne%+txtL)G f+%rite1LaL)G F >&ain the compiler complains about6 Nunhandled exception of type <8/xceptionO on both lines+ Jo% try this one! public static void main1Strin&BC ar&s) E try E 5ile;riter f D ne% 5ile;riter1L/!UUne%+txtL)G f+%rite1LaL)G F catch1<8/xception e) E F F

Jo% the compiler doesnMt stops complainin& because it no%s that if some problem occurs durin& %ritin& a file6 a proper action is bein& ta en by the pro&ram as specified in the catch bloc + Some other chec ed exceptions are! S=3/xception6 5ileJot5ound/xception <n fact all subclasses of the class /xception %hich are not in the hierarchy of 9unTime/xception are chec ed exceptions+ 8ther thin& to no% about chec ed exceptions is that they need to be declared or catched+ This means that either catch the chec ed exception or declare that this function can thro% a chec ed exception in %hich case the caller has the responsibility of catchin& it or declarin& it+ The catchin& lo&ic has been sho%n above+ $elo% is the %ay to declare a chec ed exception public static void main1Strin&BC ar&s) thro%s <8/xception 5ile;riter f D ne% 5ile;riter1L/!UUne%+txtL)G f+%rite1LaL)G F The above is our %ay of sayin& to compiler that < may thro% a chec ed exception and < no% that and < am declarin& that so the caller should have the responsibility to handle the exception+ Inchec ed exceptions are those exceptions %hich occur at runtime and %hich occur because of fla% in pro&rammin& lo&ic+ /xamples are6 >rray<ndex8ut8f$ounds/xception6 JullPointer/xception6 >rithmetic/xception The compiler doesnMt complain about these exceptions and it is the sole responsibility of pro&rammer to ta e care of them+ 5or example consider the follo%in& code! public static void main1Strin&BC ar&s) thro%s <8/xception System+out+println1ar&sB1C)G F and the invocation as Hava ClassTest

Jo command line ar&uments have been supplied and thus %hen %e try to access the second element in the ar&s strin& array6 an >rray<ndex8ut8f$ounds/xception is thro%n This is unchec ed exception because compiler doesnMt place a chec that an exception is li ely to occur+ ThatMs all6 one has to no% at the level of N%hat is difference bet%een chec ed and unchec ed exceptionsO

"ntroduction to exceptions in =a$a P1ST&2 3Y S,42&&P /,3&/S: &;C&PT"14S "4 J,5, 6 C1MM&4TS There are some runtime operations %hich are invalid for the J:,+ These runtime operations may have been fired by the pro&ram or they may occur by default+ The former are no%n as exceptions and the latter as errors+ Thou&h there is nothin& that can be done by the pro&rammer in the event of an error but somethin& can be done in case of exceptions+ > typical example of an exception is NPivide by ?eroO6 N>ccessin& a null obHectO etc+ and that of an error can be N9unnin& out of memory so that no more obHects can be allocated by memoryO+ The bottom line is that error is somethin& from %hich the pro&ram can not recover and is terminated but exceptions are somethin& from %hich pro&ram can recover and both are some erroneous situations+

.nable to load default Pro=ectHelper due to =a$a%lang%4oClass2ef:ound&rror: org?xml?sax?S,;&xception P1ST&2 3Y S,42&&P /,3&/S: ,4T' &C/"PS&' .4,3/& T1 /1,2 2&:,./T P+1J&CTH&/P&+ 2.& T1 J,5,%/,40%41C/,SS2&::1.42&++1+: 1+0?;M/?S,;?S,;&;C&PT"14 6 C1MM&4TS Inable to load default ProHect7elper due to Hava+lan&+JoClassPef5ound/rror! or&@xml@sax@S>Q/xception < have been &ettin& this problem in /clipse %hen < try to build my proHect usin& >JT+ The problem occurs because of misconfi&uration+ To fix this issue6 do this!

Go to ;indo%VVPreferencesVV>ntVV9untimeVVClasspathVV>nt 7ome /ntries and add these 2 /xternal J>9s 1Clic to &et them)! xerces<mpl+Har xmlParser>P<s+Har Jote! The name of above HarAs may be different on your side+

SCJP mock exam links% P1ST&2 3Y S,42&&P 14 J./ 86' (669 /,3&/S: SCJP 8%D 3+,"4 2.MPS' SCJP 8%D M1C< &;,M' SCJP /"4<S ( C1MM&4TS Mock exams for SCJP C JavaPrepare for SCJP Mock exams for SCJPE /xmulator for SCJP (1Get daily a 0uestion on Java6 boo mar this %ebsite) Peva aAs /xam3ab for SCJP ( Java $eat moc exams 1SCJP () Mock exams for all SCJP $ersions 1consists of topics from SCJP 1+' but doesnMt cover the topics li e Generics6 >utoboxin& etc+) /xams Guide SCJP moc exam 1for all versions of SCJP) Sahir Shah moc tests applet 1for all versions of SCJP) :aloxo 1for all versions of SCJP) Panchisholm 1for all versions of SCJP) JC7= moc exam 1 JC7= moc exam 2

JC7= moc exam 3 >n&elfire 1for all versions of SCJP) lan% 1for all versions of SCJP) JavaCertificate 1for all versions of SCJP) s maHHi moc exams 1for all versions of SCJP) Javaranch online moc exams 1for all versions of SCJP) Coffee %ith Hava 1for all versions of SCJP) Tests%orld 1&eneral Hava test)

/inks for SCJP 8%D stud! notes P1ST&2 3Y S,42&&P /,3&/S: SCJP 8%D' SCJP 8%D ST.2Y 41T&S 6 C1MM&4TS http!@@%%%+Hch0+net@tutorial@)'K)1Tut+htm http!@@%%%+Havadeveloper+co+in@scHp@scHp*notes+html http!@@%%%+michael*thomas+com@tech@Hava@index+html http!@@%%%+freeHava&uide+com http!@@Hava+boot+by@scHp*ti&er@ http!@@%%%+Havacertificationexams+com@scHp*study*&uides+php http!@@%%%+Havacertificationexams+com@scHp*community+php

SCJP 8%E "?1 P1ST&2 3Y S,42&&P 14 J./ B' (669 /,3&/S: J,5,' J,5, "?1' +&,2&+' SCJP 8%E' )+"T&+ C/,SS&S 6 C1MM&4TS The exam says you need to no% the %riter classes6 Seriali?ation and desi&n pattern bein& used in implementin& <@8 pac a&e+ The %riter class heirarchy starts from ;riter class %hich is an abstract class+ The next usable class is 5ile;riter %hich extends from ;riter class and can be used to %rite to files+ <t has constructor %hich accepts the 5ile name as Strin& or can accept 5ile 8bHect+

The 5ile;riter class has limited use as it doesnAt have any buffer+ Similar heirarchy exists in 9eader classes %ith 9eader class bein& the abstract class and 5ile9eader corresponds to 5ile;riter of ;riter heirarchy+ $esides this6 one also needs to no% the desi&n pattern

SCJP 8%D Stud! 4otes7 Part7( P1ST&2 3Y S,42&&P 14 J./ D' (669 /,3&/S: J,5,' SCJP' SCJP 8%D' SCJP 8%D ST.2Y 41T&S 6 C1MM&4TS )) Superclass <nstance ,ethod Superclass Static ,ethod Subclass <nstance ,ethod 8verrides Generates a compile*time error Subclass Static ,ethod Generates a compile*time error 7ides <f static is specified in either superclass or subclass for a method the both the other class should also ma e it static+ 1) Jo variable can be native6 abstract or synchroni?ed+ ,ember variables can be transient6 final6 static6 volatile+ 3ocal variables can be final only+ 2) 5or same class names6 use the fully 0ualified name+ <f not done so6 the first path in the classpath %ill be used+ 3) const and &oto are ey%ords but are not in use+ ') ,emori?e all ey%ords6 null6 true and false are not ey%ords+ () 3ocal obHects and primitive variables must be initiali?ed before first use6 not necessarily on the first line+ -) <nitiali?ed individual elements of an array may be used %ith some other elements remainin& uninitiali?ed+ .) NJohnO R b is not a Strin& literal+ 2) There can be a maximum of 21 di&its in a octal number not includin& the leadin& ) and a maximum of 1- di&its in a hexadecimal number not includin& the leadin& )x+ 4) >n array of superclass can accommodate obHects of subclass by auto typecastin&+ $ut the reverse is not true+ /ven if explicit cast is done6 Hava+lan&+ClassCast/xception %ill be thro%n at runtime+ 1)) <nterfaces canMt have variables %ith modifier other than public static and final+ 11) >n interface canMt implement another interface 12) >n interface canMt extend any class 13) >n interface can only extend other interfaces+ 1super interfaces) 1') >n abstract class can implement an interface+ 1() >n abstract class can extend other classes+ 1-) >n abstract class can have final methods+ 1.) static final variable can be a member variable and needs special treatment than that %ithout static ey%ord+ Since it is static6 the initiali?ation in constructor may not %or + <t %ill %or if the variable has been initiali?ed before the class %as loaded+ This

initiali?ation can be in a static bloc or %hen declarin& the variable+ 8nce done that it becomes definitely assi&ned and hence canMt be reassi&ned+ ,oreover a final &lobal variable must be assi&ned %hile a final local variable may not be+ 12) <f not initiali?ed %hile declarin& a non*static final variable is expected to be initiali?ed in all the constructors+ 14) $ut if there is an infinite loop in a constructor6 then the initiali?ation of definitely unassi&ned non*static final variable can be avoided+ 2)) 5or an infinite loop6 the definitely unassi&ned non*static final variable %ill be unassi&ned for first iteration and %ill be assi&ned for every iteration after%ards+ 7ence compiler flashes error in both cases+ 21) $ut since an if1true) is iterated only once6 the initiali?ation canMt be avoided as far as constructor is concerned+ Predict the case for if1false)+ Ses6 the compiler flashes error+ 22) <f definitely unassi&ned non*static final variable is assi&ned in both if1cond) and correspondin& else then compiler comes to no% that the variable %ill be initiali?ed in any case and hence no error+ 23) 5or final primitives6 the value may not be altered once it is initiali?ed+ 5or obHects6 the data %ithin the obHect may be modified but the reference variable may not be chan&ed+ 2') 7ashtable and 7ashmap are different in the sense that 7ashmap is unsynchroni?ed and permits nulls as eys as %ell as values+ a+ <n case the iteration performance is important6 eep the capacity@si?e small because the time for iteration is proportional to capacity R si?e+ 7o%ever &et1) and put1) have constant time performance+ b+ The load factor and initial capacity effect the performance of hashmap+ ;hen the number of entries in the hashmap exceed the product of load factor and current capacity6 the hashmap is rehashed so as to have t%ice the number of buc ets+ > value of )+.( is for load factor is &ood tradeoff bet%een time and space cost+ c+ The expected number of entries should be ta en into account %hen settin& the initial capacity6 so as to minimi?e the number of rehash operations+ <f the initial capacity is &reater than the number of entries divided by the load factor6 no rehash %ill ever occur+ d+ The parameteri?ed constructors allo% for settin& the initial capacity and@or load factor+ e+ The hashmap is unsynchroni?ed for structural chan&es+ Collections+synchroni?ed,ap should be used for synchroni?ed access+ f+ The iterator returned by hashmap is fail*fast %hich means that if the map is modified by any means other than the iteratorMs modification methods6 the iterator thro%s Concurrent,odification/xception+ 7o%ever6 the fail fast behaviour is not &uaranteed+ &+ The put1) method returns null if there is no mappin& for the ey or null %as stored as the value for that ey other%ise it returns the previous value of the ey+ Similar is the case %ith &et1)+ The contains"ey1) method may be used to distin&uish bet%een the cases %hen there is no ey %ith specified name and %hen null is stored as value for the ey+ h+ The implementation class %hich %ants to leave out some operation6 simply thro%s Insupported8peration/xception in that method+ 2() s%itch expects an ar&ument of type int+ $ut due to auto castin& short6 byte6 char also %or + 2-) strictfp used in front of method or class indicates that floatin&*point numbers %ill follo% 5P*strict rules in all expressions+

2.) /ven the order of ar&uments matters %hen overridin& a method+ 22) 8bHect reference and local variables are stored on stac + <S a relationship is inheritance and 7>S a relationship is composition 18ne class has an obHect of other as its member)

SCJP 8%D Stud! 4otes7 Part78 P1ST&2 3Y S,42&&P /,3&/S: SCJP' SCJP 8%D' SCJP 8%D ST.2Y 41T&S 6 C1MM&4TS 1) 9eturn type and method name al%ays &o to&ether 2) Jative method declarations have no body 3) > top*level class can be public6 abstract@final6 strictfp+ ') > top*level interface can be public6 abstract6 strictfp+ abstract is implied by default+ () <nner classes can be only public6 protected6 private6 static6 abstract@final+ -) <nner interfaces can be only public6 protected6 private6 static6 abstract+ .) 8nly one class@interface can be public in a source file and if it is so6 the name of the source file should be the name of the public class@interface+ 2) The default access is also available for the class members+ 4) 5or searchin& a pattern use6 the pattern and matcher+ /+& Strin& strDObcbcbcbabcbbcbcbababbabaOG Strin& re&exDObcOG Pattern pattern D Pattern+compile1re&ex)G ,atcher match D pattern+matcher1str)G %hile1matcher+find1)) E System+out+println1matcher+start)G F 1)) Pro&ram to count the number of times a character appears in a strin&! ,ap hmap2 D ne% 7ash,ap1)G for1int counter1 D) G counter1 if 1hmap2+contains"ey1Strin&+value8f1str+char>t1counter1)))) E count D 1<nte&er)hmap2+&et1Strin&+value8f1str+char>t1counter1)))G countRRG F else E count D 1G F hmap2+put1Strin&+value8f1str+char>t1counter1))6ne% <nte&er1count))G F <terator it D hmap2+ eySet1)+iterator1)G %hile1it+hasJext1)) E ey D 1Strin&)it+next1)G System+out+println1 eyR L L R hmap2+&et1 ey))G F

11) Code to create database connection6 execute statement and process results is! Class+forJame1Lsun+Hdbc+odbc+Jdbc8dbcPriverL)G Connection con D Priver,ana&er+&etConnection1LHdbc!odbc!PatabaseL6LaL6LbL)G Statement stmt D con+createStatement1)G 9esultSet set D stmt+execute=uery1LSelect W from abcL)G %hile1set+next1)) E F 12) The Strin& class is a final class+ 13) 5inal classes improve performance as the methods are expanded inline+ 1') >ll the methods of final class are also final as the class canMt be subclassed and hence the methods canMt be overridden+ 1() volatile and transient can only be applied to member variables+ 1-) volatile and final canMt &o to&ether+ 1.) transient ma es member variables non*persist able %hile seriali?in& the obHect+ 12) volatile variables maintain a master copy in addition to the local copy of each thread and each thread has to eep its local copy in sync %ith the &lobal copy+ These variables are useful to avoid concurrency problem %hen synchroni?ation is not an option+ They are slo%er+ 14) To avoid havin& different people usin& the same pac a&e name6 Sun recommends usin& the reverse of the internet domain as pac a&e name+ e+& com+sun+Hava 2)) abstract and final are mutually exclusive 21) >ll Hava classes must extend a superclass+ 22) Thou&h classes can be built %ithout inheritance and interfaces6 but that desi&n %ill be poor+ 23) >ll variables in an interface are public static final by default and all methods are public abstract by default+ public because compiler no%s that interface by itself is abstract and somebody needs to implement it6 so even if public is omitted the methods and variables are public by default+ 2') ,ethod access modifiers! public6 private6 protected or none 1default) ,ethod special modifiers! abstract6 final6 static6 synchroni?ed6 native ;hen abstract is used for a method then final6 synchroni?ed6 strictfp6 static and native canMt be used+ 2() Constructor facts! a+ The return type is implicitly this6 but this value canMt be collected usin& assi&nment operator b+ Constructor canMt be inherited as other superclass methods c+ The constructor canMt be final6 abstract6 synchroni?ed6 native6 static 1special modifiers) 2-) <f only one constructor is supplied and is made private6 no class can instance that class+ 2.) >s main method is declared static6 it canMt use non*static variables declared in the same class+ 22) 8nly a constructor can invo e another constructor and that call must be the first statement of the callin& constructor+ 1this1) or super1)) 24) super1) is usually used to call parameteri?ed superclassM constructor+ <f there is no call to superclass constructor and there is no no*ar&ument constructor then compiler flashes

error because compiler automatically inserts a call to no*ar&ument constructor+ 3)) Constructor chainin& is the callin& of superclass constructor all throu&h the hierarchy+

How to code in ;S/ P1ST&2 3Y S,42&&P /,3&/S: +&P1+TS .S"40 ;S/' ;S/' ;S/T 6 C1MM&4TS 7ereAs a document to up&rade your QS3T s ills+ <ts a ind of study notes for QS3+ http!@@Havacentre+f*s%+com@tutorials@xslt@xslt+doc

How to design M5C architeture P1ST&2 3Y S,42&&P /,3&/S: C.ST1M& M5C' J,5,' JSP' M5C' +&-.&ST 13J&CT 6 C1MM&4TS The purpose of ,:C is to free the vie% of any details about %ho and ho% handles the business process+ The vie% simply needs to indicate %hat %as the action performed by the user and then business process should be performed based on that indication+ 5or the smooth flo% bet%een vie% and business process6 there has to be some intermediary %hich is no%n as controller+ >ll pa&es %ill submit to the same controller and the controller based on %hat is return from the vie%6 calls the correspondin& dispatcher+ The dispatcher on completin& its process for%ards to appropriate vie%+ The vie% mappin&s may be stored some%here or may be hardcoded %ithin& the dispatcher+ 8ne %ay the vie% can send the event fired by user to the controller is by the use of JSP %hich %ill add a parameter into the re0uest obHect+ $ut this %ill unnecessarily complicate the thin&s+ >nother approach is to use some hidden field %hich %ill automaticall included in the re0uest and %hose value can be set usin& Havascript dependin& upon the event fired by the user+ 7ere is some code to demonstrate this+

Jo% the 5rontController %ill do somethin& li e this

;S/T Process P1ST&2 3Y S,42&&P 14 J./ >' (669 /,3&/S: ;S/T P+1C&SS 6 C1MM&4TS 7ere is the process to &enerate the output 1txt6pdf6sc&6csv etc+) usin& xml6 xsl and xslt processor+ 1) Get the Q,3 containin& the data+ 2) Pecide on the layout of output+ 3) ;rite the QS3 file ') 9un the QS3T processor to &enerate the output document+

SCJP 8%E or 8%D P1ST&2 3Y S,42&&P /,3&/S: SCJP 8%D 1+ 8%E' SC)C2' S.4 M"C+1SYST&MS 6 C1MM&4TS < %as in the dilema that should < &o for SCJP 1+' or scHp 1+( certification+ $ut no% < have decided that < %ill &o for scHp 1+( because that much improved and %ill &ive much better appeal to C: than 1+' version+ ,oreover6 as it stands out that SIJ ,icrosystems may %ithdra% 1+' version certification by the time < appear for the exam+ 1+( is &oin& to stay and thats for sure+ > random thou&ht that SC;CP exam is 1+( no% and not 1+'+ So SCJP 1+( and SC;CP 1+( ma e better combination than SCJP 1+' and SC;CP 1+(

enums in =a$a P1ST&2 3Y S,42&&P 14 J.4 89' (669 6 C1MM&4TS static canAt be applied to method local classes but can be applied to inner classes+ ************************************************************************************ semicolon at the end of enums is optional enums can be a class outside the non*inner public class or a memeber of some class but not that of a function the enum values are constant enums can have constructors+ enums can have instance variables and enums can have functions a sin&le enum value can have content specific body %hich can &ive some particular behavious only for that enum constant+ <f the enum as %hole also provides the same function6 then that function is considered overriden for the enum value that has content specific body+ semicolon is necessary for the content body of an enum value+ enum constructors are called automatically and canAt be invo ed in the code

interfaces in =a$a are more of a contract

P1ST&2 3Y S,42&&P 14 J.4 8B' (669 6 C1MM&4TS <nterfaces can be used to co*relate classes %hich %ant to share a contract re&ardin& somethin& as those implementin& the Seriali?able interface+ $ut then inheritance also means contract as a ,arutiCar extends Car+ $ut the difference %ith interface is that the implementors of interface neednAt have same hierarchy as in inheritance+ Say ,arutiCar6 G,Car and TataCar extend Car but only ,arutiCar and G,Car implement the seriali?able interface and not TataCar+ This means that ,arutiCar and G,Car are in contract that they may be seriali?ed but TataCar is not+ The difference is in usa&e of interfaces and not in overridin& abstract methods+

published the article on J-uer! P1ST&2 3Y S,42&&P 14 J.4 8>' (669 6 C1MM&4TS The second volume of Technical Journal in my or&ani?ation is out and the much a%aited 1donAt no% by ho% many people !) ) article &ot published+ <t %as a &reat feelin&+ Thou&h the article doesnAt discuss anythin& ne% than %hat exists in the J=uery at this time+ $ut < really enHoyed %ritin& the article by searchin& the best content < can collect from internet and provide much better information on the topic+ 7o% by the %ay6 J=uery is somethin& easy Havascript =a$a access modifiers P1ST&2 3Y S,42&&P 14 2&C (D' (66B /,3&/S: J,5, ,CC&SS M12":"&+S 6 C1MM&4TS 1) > top level class can have public6 abstract and final as access modifiers+ To ma e the class default do not specify any access modifier+ 2) > top level interface can have public and abstract as access modifier 3) The strin& class is a final class+ 5inal classes can improve performance as the methods are expanded inline+ ') >ll the methods of final class are also final+ () Transient ey%ord can only be applied to member variables and it ma es those variable non*persistable %hile seriali?in& the obHect+ -) Java interfaces cannot have transient variables+ .) :olatile variables maintain a master copy in addition to the local copy of each thread and each thread has to eep its copy in sync %ith the local copy+ They are useful to avoid

concurrency problem %hen synchroni?ation is not an option+ They are some%hat slo%er+ 2) The only modifier that can be applied to local variables in final+ You might also like: Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 7o% to Send 7TTP P8ST 9e0uest in Java Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication 7o% to <terate >rray3ist in Struts2 /ink)ithin

2ifference between Hashmap and Hashtable P1ST&2 3Y S,42&&P /,3&/S: H,SHM,P' H,SHT,3/&' J,5, 6 C1MM&4TS 1) 7ashtable and 7ashmap are different in the sense that 7ashmap is synchroni?ed and permits nulls as eys as %ell as values+ 7ashtable re0uires non*null values for eys as %ell as values+ a+ <n case iteration performance is important6 eep the capacity@si?e of hashmap small because the time for iteration is proportional to the capacity R si?e+ 7o%ever6 &et1) and put1) have constant time performance+ b+ The load factor and initial capacity effect the performance of the hashmap+ ;hen the number of entries in the hashmap exceed the product of load factor and current capcity6 the hashmap is rehashed so as to have t%ice the number of buc ets+ > value of )+.( for load factor is &ood tradeoff bet%een time and space cost+ c+ The expected number of entries in the map and its load factor should be ta en into account %hen settin& its initial capacity6 so as to minimi?e the number of rehash operations+ <f the initial capacity is &reater than the maximum number of entries divided by the load factor6 no rehash operations %ill ever occur+ d+ The parameteri?ed constructors are allo% for specifyin& the initial capacity and@or load factor+ e+ The hashmap is not synchroni?ed for structural chan&es 1addition and deletion of eys) and not for operations li e updatin& the value for a ey+ Collections+synchroni?ed,ap should be used for synchroni?ed access+ f+ The iterator returned is fail*fast i+e+ as soon as the map is structurally modified usin& other than iteratorMs remove method6 the iterator thro%s Concurrent,odification/xception+ 7o%ever6 the fail*fast behaviour is not &uaranteed+ &+ The put method returns null if either there %as no such ey in the map or the value associated %ith the ey %as null or it returns the previous value associated %ith ey6 if it exists in the map+

h+ Similar is the case %ith &et1)6 it returns null if either there is no ey %ith name specified or the ey explicitly maps to null+ The contains"ey can be used to distin&uish these t%o cases+ You might also like: ,y 3ist of Top 2) Java 9elated $oo s Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication 7o% to <terate >rray3ist in Struts2 Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat /ink)ithin

Ja$a some tips P1ST&2 3Y S,42&&P /,3&/S: J,5, S1M& T"PS 6 C1MM&4TS 1) s%itch expects an ar&ument of int type+ $ut due to auto castin&6 short6 byte6 char also %or + 2) strictfp Ised in front of a method or class to indicate that floatin&*point numbers %ill follo% 5P*strict rules in all expressions+ 3) /ven the order of ar&uments matter %hen overridin& a method ') this and super are special ind of ey%ords () obHect references and local variables are stored on stac + -) <s a relationship is inheritance and 7>S a relationship is a composition 18ne class has an obHect of other as its member e+& > car has an en&ine) You might also like: 7o% to <terate >rray3ist in Struts2 9/ST ;eb Service <ntervie% =uestions 7o% to Send 7TTP P8ST 9e0uest in Java Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication /ink)ithin

,bstract Classes'"nterfaces and extends'implements all cases

P1ST&2 3Y S,42&&P /,3&/S: ,3ST+,CT C/,SS&S' "4T&+:,C&S ,// C,S&S' J,5, 6 C1MM&4TS 1) >n interface canMt implement another interface 2) >n interface can extend another interface 3) >n interface can extend multiple interfaces+ 1 no%n as super interface) ') >n abstract class can implement an interface () >n abstract class can extend another abstract class -) >n interface canMt extend an abstract class You might also like: 7o% to <terate >rray3ist in Struts2 9/ST ;eb Service <ntervie% =uestions Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication ,y 3ist of Top 2) Java 9elated $oo s /ink)ithin

Thread pool in =a$a P1ST&2 3Y S,42&&P /,3&/S: J,5,' TH+&,2 P11/ 6 C1MM&4TS <n lar&e scale application6 multithreadin& is commonly used to execute independent tas s+ Jo% ima&ine 1)) classes extendin& the Thread class 1or implementin& the runnable interface) and each one havin& its o%n run method and you are as ed to %rite those run methods+ 8bviously6 you need to repeat the same code and mana&in& that code even becomes more difficult+ > very simple solution to this is to build a thread pool %here in you %ill have a 0ueue of obHects on %hich the run method %ill be called+ >ny pre*pocessin& %ill be done in the obHects o%n member methods+ <ts only that the tas s %ill be added to the 0ueue and an infinite loop %ill loo for yet to run threads and %ill run them+ Sou need t%o 0ueues6 one containin& the threads that are currently runnin& and other containin& those yet to be run+ These 0ueues can be 3in ed3ists+ 1) ,aximum and minimum number of threads pendin& for execution can be controlled+ 2) ,aximum alive time for each thread can be controlled 3) ,any other business re0uirements in terms of multithreadin& can be achieved at a central point+ ') Sour applicationMs multithreadin& is se&re&ated %hich ma es it loo decent and %ell mana&ed and &ives a &ood impression to the revie%er+

() Sour life becomes much easier+ 7o% to achieve it! 1) Create a class to maintain the threadpool information li e the read and runnin& 0ueues6 the variables for max and min number of threads6 time to eep a thread alive 2) > class %hich contains the loop to chec for threads in the runnin& and ready 0ueues and ma e a decision %hether to invo e a particular thread or not+ You might also like: Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication Java :erbose 8ptions for 9unnin& Pro&rams 9/ST ;eb Service <ntervie% =uestions 7o% to Send 7TTP P8ST 9e0uest in Java /ink)ithin

,ll Ja$a J23C tips P1ST&2 3Y S,42&&P 14 2&C (>' (66B /,3&/S: ,// T"PS' J,5,' J23C' SCJP 6 C1MM&4TS 1) There are three levels of JP$C >P< 2) The &etConnection method is synchroni?ed 3) ,ultiple S=3 exceptions are chained ') Type 1 are the JP$C*8P$C drivers () Type 2 are the Jative >P< driver -) Type 3 driver JP$C calls are first translated to P$,S independent net protocol and then translated to P$,S specific protocol .) Type ' drivers are pure Hava classes that directly interact %ith the P$,S and are 0uite fast+ 2) PataSource interface %as introduced in J>:> 2+) and supports connection poolin&6 distributed tansactions 4) Patasource uses JJP< to find the datasource on the server and bind itself to it+ 1)) The context interface provides the facility to loo up6 bind and unbind the datasource 11) The JP$C url has three parts! Hdbc!! 12) The Statement obHect can be used to pass the S=3 commands to the database 1con+createStatement1)) 13) The prepared statement can be passed parameters and hence can be used %ith different values and is usually faster than statement+ 1con+prepareStatement) 1') The callable statement can be used to call stored procedures+ 1con+prepareCall) 1() The different versions for execute method are! a+ executeIpdate1Strin& s0l) X Statements %hich return a count

b+ execute=uery1Strin& s0l) X Statements %hich return a sin&le resultset c+ execute1Strin& s0l) X Statements %hich return multiple resultsets 1>dvanced 5unda) 1-) ;hile usin& the statement obHect6 the 0uery is passed %hen it is executed 1.) ;hen usin& prepared statement6 the 0uery is passed %hen creatin& the statement obHect from connection obHect+ This helps in pre*compilation 12) The callable statement also passes the call statement %hile creatin& the statement obHect from the connection obHect+ 14) Callable statement extends prepared statement 2)) Callable statement can also ta e output parameters too+ $ut that parameter must be re&istered usin& re&ister8utParameter1) method before callin& the execute method+ /+& callstmt+re&ister8utParameter136 Hava+s0l+Types+:>9C7>9)G if the third parameter is supposed to be the 8IT parameter+ 21) The commit occurs %hen the statement completes or the next execute occurs6 %hichever comes first+ <n the case of statements returnin& a 9esultSet6 the statement completes %hen the last ro% of the 9esultSet has been retrieved or the 9esultSet has been closed+ <n advanced cases6 a sin&le statement may return multiple results as %ell as output parameter values+ 7ere6 the commit occurs %hen all results and output parameter *values have been retrieved+ You might also like: Java :erbose 8ptions for 9unnin& Pro&rams 7o% to Send 7TTP P8ST 9e0uest in Java Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 9/ST ;eb Service <ntervie% =uestions /ink)ithin

=a$a #uestions " want answers to P1ST&2 3Y S,42&&P /,3&/S: J,5, -.&ST"14S ( C1MM&4TS <s it possible to! 1) <nterface extendin& multiple classes 1Jormal as %ell as abstract) 2) <nterface implementin& other interfaces 3) Jormal Classes extendin& interfaces ') Jormal classes extendin& abstract classes () >bstract classes extendin& abstract classes -) >bstract classes extendin& normal classes .) >bstract classes implementin& interfaces

7o% to! 2) Ise of enums in classes You might also like: 9/ST ;eb Service <ntervie% =uestions 7o% to Send 7TTP P8ST 9e0uest in Java ,y 3ist of Top 2) Java 9elated $oo s Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat /ink)ithin

o$erloading'o$erloading and autoboxing unboxed P1ST&2 3Y S,42&&P 14 2&C (8' (66B /,3&/S: 15&+/1,2"40' 15&+/1,2"40 ,42 ,.T131;"40 6 C1MM&4TS ,ethods &1int i) 1in base@derived) and &1<nte&er i) 1in derived@base) are different as %hile overridin& autoboxin& is i&nored+ &1<nte&er i)6 &1Jumber i) and &18bHect i) can all be overridden methods as <nte&er is a type of Jumber and Jumber is a type of 8bHect You might also like: ,y 3ist of Top 2) Java 9elated $oo s Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication 7o% to <terate >rray3ist in Struts2 /ink)ithin

multidimensional arra!s P1ST&2 3Y S,42&&P /,3&/S: ,++,YS' J,5,' M./T"2"M&4S"14,/ 6 C1MM&4TS

1) byteBCBC d D EE1FFG @@valid 2) byteB1CB1C D EE1F6E1FFG @@invalid 3) byteB1CB1C D E1FG @@invalid ') byteB1CB1C d D ne% byteBCBCG @@invalid () byteB2CBC d D ne% byteBCBCG -) conclusion! the si?e of dimensions canMt be specified %hile declarin& the array+ .) byteBCBC d D ne% byteB1CBCG declares multidimensional array+ Compiler expects each element of d to be of type byteBC+ > value of primitive type can be accessed by usin& the notation dB1CB1C 2) intBCBC multiPim D ne% intB(CB'CG @@ valid intBCBCBC multiPim D ne% intB(CB'CBCG @@ valid intBCBCBC multiPim D ne% intB(CBCB(CG @@ <nvalid You might also like: Java :erbose 8ptions for 9unnin& Pro&rams ,y 3ist of Top 2) Java 9elated $oo s Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 7o% to <terate >rray3ist in Struts2 /ink)ithin

single dimensional arra!s P1ST&2 3Y S,42&&P /,3&/S: ,++,YS' J,5,' S"40/& 2"M&4S"14,/ 8 C1MM&4T 1) > method returnin& an array may be declared as Strin& &etJames1)BC EF Strin&BC &etJames1) EF 2) >rray reference and array obHect are different thin&s+ >rray reference is stored in a stac and the array obHect is stored on the heap+ 3) >rray reference is re0uired at compile time and array is constructed at runtime+ ') The array reference can be made to point to different obHects at different times but the type of array obHect should match %ith that specified %hile declarin& the array reference+ () <f the array creation is specified %hile declarin& the array 1usin& ne% operator) the array obHect %ill still be created at runtime+ -) The array obHectMs si?e can be any variable or expression but the value should be no%n at runtime+ .) /ach member of array obHect may further refer to some other obHect+ 2) >rray initiali?er can be used to create obHects by array references in one line only+ /+&+ <nte&erBC a D E16263FG 4) Thou&h byte is a primitive data type6 byte b D ne% byteB1)CG is valid because itMs the

array obHect thatMs bein& &iven memory in heap and each member of array obHect is of type byte+ 1)) len&th is a property of array and not a method 11) >s Hava+lan&+8bHect is the superclass of an array6 arrays understand all method calls of Hava+lan&+8bHect class+ You might also like: Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 7o% to <terate >rray3ist in Struts2 ,y 3ist of Top 2) Java 9elated $oo s 9/ST ;eb Service <ntervie% =uestions /ink)ithin

"dentifiers'ke!words and literals P1ST&2 3Y S,42&&P /,3&/S: "2&4T":"&+S' J,5,' <&Y)1+2S' /"T&+,/S 6 C1MM&4TS 1) byte6 short6 int6 lon& are si&ned inte&rals+char represents unsi&ned inte&rals+ 2) 3iteral is a type of value and the behavior of value is determined by the type of the literal+ /+& true and false are boolean literals 3) The character literals are represented usin& Inicode form YUuaaaaM and special character literals are YUtM6 YUfM6 YUUM ') The non*primitives %hich can be used as literals are Strin& and array () The array in Hava+lan&+8bHect is different from Hava+lan&+reflect -) Si&ned literals are stored in 2Ms complement form .) byte X 2bits X ) ** *12. to 122 short X 1-bits X ) ** *21( to 21( * 1 int X 32bits X ) ** *231 to 231 X 1 lon& X -'bits X )3 or )l ** *2-3 to 2-3 *1 float X 32bits X )+)f or )+)5 X 5loat+,<JK:>3I/ to 5loat+,>QK:>3I/ double X -'bits X )+)d or )+)P ** Pouble+,<JK:>3I/ to Pouble+,>QK:>3I/ char X 1-bits ** ) to 121-*1) or YUu))))M to YUu5555M boolean X 1bit X true or false 2) The numbers havin& decimal point are double by default and canMt be assi&ned to float variables %ithout explicit castin&+ 1because float is narro%er than double) 4) > value %ill be interpreted as non*inte&er if either it has decimal point or the letter e or / 1denotin& the exponent) 1) >ll Hava ey%ords are al%ays in a lo%er case 2) Some hard to remember ey%ords are const &oto strictfp and volatile

3) <dentifiers can start %ith a*?6>*Z6K6[ ') K and [ are the only non*unicode characters that can start an identifier () <dentifier can have K6[6letters and di&its in it+ -) The ey%ords in Hava are! abstract6default6if6private6thro%6assert16do6implements6protected6thro%s6boolean6double6i mport6 public6transient6brea 6else 6instanceof6return6true26byte 6extends 6int6short6try6case6false26 interface6static6void6catch 6final 6lon& 6strictfp6volatile 6char 6finally 6native 6super 6%hile 6class 6 float6ne% 6s%itch 6const36for 6null26synchroni?ed 6continue 6&oto36pac a&e 6this .) There are a total of (2 reserved %ords and ey%ords+ 8f these const6&oto and three literals 1true6fals and null) are not ey%ords+ The ey%ords const and &oto are reserved6 even thou&h they are not currently used any%here in Hava+ The ey%ords true and false are actually boolean literalsG also6 the ey%ord null is the null literal+ These too cannot be used as identifiers+ assert is a ey%ord as per Hava 1+'+ 2) Technically spea in&6 reserved %ords are identifiers that can be used only as ey%ord You might also like: Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat 9/ST ;eb Service <ntervie% =uestions Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication 7o% to <terate >rray3ist in Struts2 /ink)ithin

2efault $alues of instance $ariable P1ST&2 3Y S,42&&P 14 2&C (6' (66B /,3&/S: 2&:,./T 5,/.&S' "4ST,4C& 5,+",3/&S 6 C1MM&4TS 8bHect 9eference***null byte***) short***) int***) lon&***)3 or )l float***)+)5 or )+)f double***)+)P or )+)d boolean***false char***AUu))))A You might also like:

Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat Java :erbose 8ptions for 9unnin& Pro&rams ,y 3ist of Top 2) Java 9elated $oo s 7o% to <terate >rray3ist in Struts2 /ink)ithin

The main P1ST&2 3Y S,42&&P /,3&/S: J,5,' M,"4 M&TH12 6 C1MM&4TS :alid main declarations are! public static void main 1Strin& ar&sBC) EF public static void main 1Strin&BC ar&s) EF public static void main 1Strin& BCar&s) EF static public void main1Strin&BC ar&s) EF Jote!The return type of main should al%ays be void You might also like: Pevelop Java // ;eb Services %ith /clipse6 >Q<S2 and Tomcat Java :erbose 8ptions for 9unnin& Pro&rams Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication ,y 3ist of Top 2) Java 9elated $oo s /ink)ithin

Ja$a file naming P1ST&2 3Y S,42&&P /,3&/S: J,5, S1.+C& :"/& 4,M& > C1MM&4TS :or 4aming of source file The name of the Hava source file should be the same as that of the public class or interface present in the file+ <f there is no public class or interface in the file6 the file can ta e any name+

The compiler error %hen you declare a public type but donMt name the file as publictypeMs name is! The public type name must be defined in its o%n file name+Hava You might also like: 7o% to <terate >rray3ist in Struts2 7o% to Send 7TTP P8ST 9e0uest in Java Java :erbose 8ptions for 9unnin& Pro&rams 9/ST ;eb Service <ntervie% =uestions /ink)ithin

Method o$erriding rules in J,5, P1ST&2 3Y S,42&&P /,3&/S: J,5,' M&TH12 15&++"2"40' SCJP 8%C 8 C1MM&4T 1) The si&nature includin& the number and type of ar&uments for the overridin& method should be same+ 2) The return type should be same+ 3) The access modifier should not be more limitin& than superclass method+ ') The overridin& method should not thro% exceptions other than those thro%n by the method in the superclass+ You might also like: Sho%in& Generic /rror Pa&e in Struts2 ;eb >pplication

Вам также может понравиться