Upload
zeng-frank
View
232
Download
0
Embed Size (px)
Citation preview
8/12/2019 SCJP Exam310 055 Notes
1/46
cohesive adj.
cohesive force
havoc n.; ; ; ;
stifle vt., (!") #$(up) [%&]'(stifle sobs
[yawn])*+,[-.]stifle a rebellion! The smoke stifled the fireman./0123
45
Polymorphism n.67(89)
ellipsis .(pl. ses [si!"]):;?:@AB(C, ... ")
nuance n.(DEFGHFIJFKLFMN")OP; QORN, SJ; IH
wrath n.TU, VUWXYZ; [\;:]
8/12/2019 SCJP Exam310 055 Notes
2/46
; $,('z),:/
8/12/2019 SCJP Exam310 055 Notes
3/46
through inheritance. -t doesn#t matter if the superclass and
subclass are in different packa%es, the protected superclass
member is still visible to the subclass (althou%h visible only in
a very specific way as we#ll see a little later). This is in
contrast to the default behavior, which doesn#t allow a subclassto access a superclass member unless the subclass is in the same
packa%e as the superclass.
when you thinkprotected, thinkpackage + kids. class with a
protected member is markin% that member as havin% packa%elevel
access for all classes, but with a special e*ception for
subclasses outside the packa%e.
The bottom line! when a subclassoutsidethepacka%e inherits a
protected member, the member is essentially private inside the
subclass, such that only the subclass and its subclasses can
access it.
5Fthere is only one modifier that can ever be applied to local
variablesfinal.
6F7et#s look at some le%al and ille%al varar% declarations!
7e%al!
void dotuff(int... *) 1 2 33 e*pects from 8 to many ints
33 as parameters
void dotuff4(char c, int... *) 1 2 33 e*pects first a char,
33 then 8 to many ints
void dotuff5(nimal... animal) 1 2 33 8 to many nimals-lle%al!
void dotuff6(int *...) 1 2 33 bad synta*
void dotuff9(int... *, char... y) 1 2 33 too many varar%s
void dotuff:(trin%... s, byte b) 1 2 33 varar% must be last
9Fomparison of modifiers on variables vs. methods
local variables! final
nonlocal variables! final, public, protected, private, static,
transient, volatile
methods! final, public, protected, private, static, abstract,
synchroni"ed, strictfp, native
:F
8/12/2019 SCJP Exam310 055 Notes
4/46
2
2
The followin% is C@T le%al!
public class offeeTest+ 1public static void main(trin%[] ar%s) 1
enum offeei"e 1 /-=, '>=?, @A?0B'?7-C= 2 33 B0@C=E
annot
33 declare enums in methods
offee drink D new offee();
drink.si"e D offeei"e./-=;
2
2
?ach of the enumerated offeei"e types are actually instances of
offeei"e.
33 conceptual e*ample of how you can think
33 about enums
class offeei"e 1
public static final offeei"e /-= D
new offeei"e(F/-=F, 8);
public static final offeei"e '>=? D
new offeei"e(F'>=?F, +);
public static final offeei"e @A?0B'?7-C= D
new offeei"e(F@A?0B'?7-C=F, 4);public offeei"e(trin% enumCame, int inde*) 1
33 stuff here
2
public static void main(trin%[] ar%s) 1
ystem.out.println(offeei"e./-=);
2
2
GFThe overridin% method cannot have a more restrictive access
modifier than the method bein% overridden (for e*ample, you can#t
override a method marked public and make it protected).
The rules for overridin% a method are as follows!
1The ar%ument list must e*actly match that of the overridden
method. -f they don#t match, you can end up with an overloaded
method you didn#t intend.
1The return type must be the same as, or a subtype of, the return
type declared in the ori%inal overridden method in the
superclass.
1The access level can#t be more restrictive than the overridden
method#s.1The access level C be less restrictive than that of the
8/12/2019 SCJP Exam310 055 Notes
5/46
overridden method.
1-nstance methods can be overridden only if they are inherited by
the subclass. subclass within the same packa%e as the instance#s
superclass can override any superclass method that is not marked
private or final. subclass in a different packa%e can overrideonly those nonfinal methods marked public or protected (since
protected methods are inherited by the subclass).
1The overridin% method C throw any unchecked (runtime)
e*ception, re%ardless of whether the overridden method declares
the e*ception.
1The overridin% method must C@T throw checked e*ceptions that
are new or broader than those declared by the overridden method.
Hor e*ample, a method that declares a HileCotHound?*ception
cannot be overridden by a method that declares a I7?*ception,
?*ception, or any other nonruntime e*ception unless it#s a
subclass of HileCotHound?*ception.
1The overridin% method can throw narrower or fewer e*ceptions.
Just because an overridden method Ftakes risksF doesn#t mean that
the overridin% subclass# e*ception takes the same risks. /ottom
line! an overridin% method doesn#t have to declare any e*ceptions
that it will never throw, re%ardless of what the overridden
method declares.
1Kou cannot override a method marked final.
1Kou cannot override a method marked static. Be#ll look at ane*ample in a few pa%es when we discuss static methods in more
detail.
1-f a method can#t be inherited, you cannot override it. 0emember
that overridin% implies that you#re reimplementin% a method you
inheritedE Hor e*ample, the followin% code is not le%al, and even
if you added an eat() method to 'orse, it wouldn#t be an override
of nimal#s eat() method.
public class Testnimals 1
public static void main (trin% [] ar%s) 1
'orse h D new 'orse();
h.eat(); // Not legal because Horse didn't inherit
eat()
2
2
class nimal 1
private void eat() 1
ystem.out.println(F=eneric nimal ?atin% =enericallyF);
2
2class 'orse e*tends nimal 1 2
8/12/2019 SCJP Exam310 055 Notes
6/46
Using super to invoke an overridden method only applies to
instance methods. (Remember, static methods cant be overridden.!
If a method is overridden but you use a polymorphic (supertype)
reference to refer to the subtype object with the overriding
method, the compiler assumes youre calling the supertype versionof the method. If the supertype version declares a checked
exception, but the overriding subtype method does not, the
compiler still thinks you are calling a method that declares an
exception.
Lets take a look at an example
class nimal 1
public void eat() throws ?*ception 1
33 throws an ?*ception
2
2
class
8/12/2019 SCJP Exam310 055 Notes
7/46
override, because
the ar%ument list chan%ed
public trin% eat() 1 2 Cot an override because
of the return type,
not an overload either because thereLs no chan%e inthe ar%ument list
MF n interface can e*tend more than one interface
interface %ounceable extends Mo!eable& pherical // o*
void bounce();
void set/ounceHactor(int bf);
2
interface oveable 1
void move-t();
2
interface pherical 1
void dophericalThin%();
2
class Hoo 1 2 33 @N
class /ar implements Hoo 1 2 33 CoE an#t implement a class
interface /a" 1 2 33 @N
interface Hi 1 2 33 @N
interface Hee implements /a" 1 2
33 CoE -nterface can#t implement an interface
interface Oee implements Hoo 1 233 CoE -nterface can#t implement a class
interface Ooo e*tends Hoo 1 2
33 CoE -nterface can#t e*tend a class
interface /oo e*tends Hi 1 2
33 @N. -nterface can e*tend an interface
class Toon e*tends Hoo, /utton 1 2
33 CoE lass can#t e*tend multiple classes
class Ooom implements Hi, Hee 1 2
33 @N. class can implement multiple interfaces
interface Aroom e*tends Hi, Hee 1 2
33 @N. interface can e*tend multiple interfaces
class Kow e*tends Hoo implements Hi 1 2
33 @N. lass can do both (e*tends must be +st)
Fsi* rules for returnin% a value!
+. Kou can return null in a method with an ob$ect reference
return type.
public /utton dotuff() 1
return null;
24. n array is a perfectly le%al return type.
8/12/2019 SCJP Exam310 055 Notes
8/46
public trin%[] %o() 1
return new trin%[] 1FHredF, F/arneyF, FBilmaF2;
2
5. -n a method with a primitive return type, you can return any
value orvariable that can be implicitly converted to the declared return
type.
public int foo() 1
char c D #c#;
return c; 33 char is compatible with int
2
6. -n a method with a primitive return type, you can return any
value or
variable that can be e*plicitly cast to the declared return type.
public int foo () 1
float f D 54.9f;
return (int) f;
2
9. Kou must not return anythin% from a method with a void return
type.
public void bar() 1
return Fthis is itF; 33 Cot le%alEE
2
:. -n a method with an ob$ect reference return type, you canreturn any
ob$ect type that can be implicitly cast to the declared return
type.
public nimal %etnimal() 1
return new 'orse(); 33 ssume 'orse e*tends nimal
2
public @b$ect %et@b$ect() 1
int[] nums D 1+,4,52;
return nums; 33 0eturn an int array,
33 which is still an ob$ect
2
public interface hewable 1 2
public class =um implements hewable 1 2
public class Testhewable 1
33 ethod with an interface return type
public hewable %ethewable() 1
return new =um(); 33 0eturn interface implementer
2
2+8F+ules for "onstructors
8/12/2019 SCJP Exam310 055 Notes
9/46
1onstructors can use any access modifier, includin% private. (
privateconstructor means only code within the class itself can
instantiate an ob$ectof that type, so if the private constructor
class wants to allow an instanceof the class to be used, the
class must provide a static method or variable thatallows accessto an instance created from within the class.)
1The constructor name must match the name of the class.
1onstructors must not have a return type.
1-t#s le%al (but stupid) to have a method with the same name as
the class,but that doesn#t make it a constructor. -f you see a
return type, it#s a methodrather than a constructor. -n fact, you
could have both a method and aconstructor with the same namethe
name of the classin the same class,and that#s not a problem for
Java. /e careful not to mistake a method for aconstructorbe sure
to look for a return type.
1-f you don#t type a constructor into your class code, a default
constructor willbe automatically %enerated by the compiler.
1The default constructor is 7BK a noar% constructor.
1-f you want a noar% constructor and you#ve typed any other
constructor(s)into your class code, the compiler won#t provide
the noar% constructor (orany other constructor) for you. -n
other words, if you#ve typed in a constructorwith ar%uments, you
won#t have a noar% constructor unless you type it inyourself E
1?very constructor has, as its first statement, either a call toan overloadedconstructor (this()) or a call to the superclass
constructor (super()), althou%hremember that this call can be
inserted by the compiler.
1-f you do type in a constructor (as opposed to relyin% on the
compiler%enerateddefault constructor), and you do not type in
the call to super() or a callto this(), the compiler will insert
a noar% call to super() for you, as the veryfirst statement in
the constructor.
1 call to super() can be either a noar% call or can include
ar%uments passedto the super constructor.
1 noar% constructor is not necessarily the default (i.e.,
compilersupplied)constructor, althou%h the default constructor
is always a noar% constructor.The default constructor is the one
the compiler providesE Bhile the defaultconstructor is always a
noar% constructor, you#re free to put in your own
noar%constructor.
1Kou cannot make a call to an instance method, or access an
instance variable,until after the super constructor runs.
1@nly static variables and methods can be accessed as part of thecall to super()or this(). (?*ample! super(nimal.C?) is @N,
8/12/2019 SCJP Exam310 055 Notes
10/46
because C? isdeclared as a static variable.)
1bstract classes have constructors, and those constructors are
always calledwhen a concrete subclass is instantiated.
1-nterfaces do not have constructors. -nterfaces are not part of
an ob$ect#sinheritance tree.1The only way a constructor can be invoked is from within another
constructor.-n other words, you can#t write code that actually
calls a constructor asfollows!
class 'orse 1
'orse() 1 2 33 constructor
void dotuff() 1
'orse(); 33 callin% the constructor ille%alE
2
2
,e +ule. he first line in a constructor must be a call to
super() or a call to this()0
Co e*ceptions. -f you have neither of those calls in your
constructor, the compiler will insert the noar% call to super().
-n other words, if constructor () has a call to this(), the
compiler knows that constructor () will not be the one to invoke
super().
The precedin% rule means a constructor can never have both a call
to super() and a call to this(). /ecause each of those calls must
be the first statement in a constructor, you can#t le%ally useboth in the same constructor. That also means the compiler will
not put a call to super() in any constructor that has a call to
this().
++Fremember that static methods cant be overriddenE This doesn#t
mean they can#t be redefined in a subclass, but redefinin% and
overridin% aren#t the same thin%. 7et#s take a look at an e*ample
of a redefined (remember, not overridden), static method!
class nimal 1
static void dotuff() 1
ystem.out.print(Fa F);
2
2
class
8/12/2019 SCJP Exam310 055 Notes
11/46
a1x20dotuff()3 // in!oe the static method
2
2
0unnin% this code produces the output!
a a a0emember, the synta* a[*].dotuff() is $ust a shortcut (the
synta* trick)Sthe compiler is %oin% to substitute somethin% like
nimal.dotuff() instead.
+4Fchar a D 8*M4; 33 he*adecimal literal
char b D M4; 33 int literal
char c D (char)G8888; 33 The cast is re&uired; G8888 is out of
char ran%e
char d D (char) M; 33 0idiculous, but le%al
nd the followin% are not le%al and produce compiler errors!
char e D 4; 33 Possible loss of precision; needs a cast
char f D G8888 33 Possible loss of precision; needs a cast
byte b D 5; 33 Co problem, 5 fits in a byte
byte c D M; 33 Co problem, M fits in a byte
byte d D b R c; 33 hould be no problem, sum of the two bytes
fits in a byte
The last line won#t compileE Kou#ll %et an error somethin% like
this!
Test/ytes.$ava!9! possible loss of precision
found ! intre&uired! byte
byte c D a R b;
-t would
have compiled if we#d done the explicit cast!
byte c D (byte) (a R b);
float a D +88.88+f;
int b D (int)a; 33 ?*plicit cast, the float could lose info
Bhen you narrow a primitive, Java simply truncates the hi%her
order bits that won#t fit. -n other words, it loses all the bits
to the left of the bits you#re narrowin% to.
byte b D 5;
b D (byte) (b R G); 33 Bon#t compile without the
33 cast, since b R G results in an int
arrays must always be %iven a si"e at the time they are
constructed.The JA needs the si"e to allocate the appropriate
space on the heap for the newarray ob$ect. -t is never le%al, for
e*ample, to do the followin%!
int[] car7ist D new int[]; 33 Bill not compile; needs a si"e
o don#t do it, and if you see it on the test, run screamin%toward the nearest answer marked Fompilation fails.F
8/12/2019 SCJP Exam310 055 Notes
12/46
twodimensional array (an array of arrays) can be initiali"ed
as follows!
int[][] scores D new int[5][];
33
8/12/2019 SCJP Exam310 055 Notes
13/46
inti D 9;
go(i); 33 which %o() will be invokedV
2
2
lon%if the only version of the %o() method was one that took
an -nte%er, then Java 9#s bo*in% capability would allow the
invocation of %o() to
succeed. 7ikewise, if only the lon% version e*isted, the compiler
would use it to
handle the %o() invocation. The &uestion is, %iven that both
methods e*ist, which
one will be usedV -n other words, does the compiler think that
widenin% a primitive
parameter is more desirable than performin% an autobo*in%
operationV The answer is
that the compiler will choose widenin% over bo*in%, so the output
will be lon%
Java 9#s desi%ners decided that the most important rule should be
that pree*istin%
code should function the way it used to, so since widenin%
capability already e*isted,
a method that is invoked via widenin% shouldn#t lose out to a
newly created methodthat relies on bo*in%. /ased on that rule, try to predict the
output of the followin%!
class ddAarar%s 1
static void %o(int *, int y) 1 ystem.out.println(Fint,intF);2
static void %o(byte... *) 1 ystem.out.println(Fbyte... F); 2
public static void main(trin%[] ar%s) 1
byte b D 9;
%o(b,b); 33 which %o() will be invokedV
2
2
s you probably %uessed, the output is
int,int
/ecause, once a%ain, even thou%h each invocation will re&uire
some sort of
conversion, the compiler will choose the older style before it
chooses the newer
style, keepin% e*istin% code more robust. o far we#ve seen that
. Bidenin% beats bo*in%
.Bidenin% beats varar%st this point, in&uirin% minds want to know, does bo*in% beat
8/12/2019 SCJP Exam310 055 Notes
14/46
varar%sV
class /o*@rAarar% 1
static void %o(/yte *, /yte y)
1 ystem.out.println(F/yte, /yteF); 2
static void %o(byte... *) 1 ystem.out.println(Fbyte... F); 2public static void main(trin% [] ar%s) 1
byte b D 9;
%o(b,b); 33 which %o() will be invokedV
2
2
s it turns out, the output is
/yte, /yte
+:FIts tempting to think that you might be able to widen an
Integer wrapper to a Long wrapper, but the following will %&!
compile
class
8/12/2019 SCJP Exam310 055 Notes
15/46
tran%ely enou%h, it - possible for the compiler to perform a
bo*in% operation
followed by a widenin% operation in order to match an invocation
to a method. This
one mi%ht blow your mind!class /o*ndBiden 1
static void %o(@b$ect o) 1
/yte b4 D (/yte) o; 33 ok it#s a /yte ob$ect
ystem.out.println(b4);
2
public static void main(trin% [] ar%s) 1
byte b D 9;
%o(b); 33 can this byte turn into an @b$ect V
2
2
This compiles (E), and produces the output!
9
BowE 'ere#s what happened under the covers when the compiler,
then the JA,
%ot to the line that invokes the %o() method!
+. The byte b was bo*ed to a /yte.
4. The /yte reference was widened to an @b$ect (since /yte
e*tends @b$ect).
5. The %o() method %ot an @b$ect reference that actually refersto a /yte
ob$ect.
6. The %o() method cast the @b$ect reference back to a /yte
reference (remember, there was never an ob$ect of type @b$ect in
this scenario, only an ob$ect
of type /yteE).
9. The %o() method printed the /yte#s value.
Bhy didn#t the compiler try to use the bo*thenwiden lo%ic when
it tried to deal with the Bidennd/o* classV Think about itSif it
tried to bo* first, the byte would have been converted to a /yte.
Cow we#re back to tryin% to widen a /yte to a 7on%, and of
course, the - test fails.
class Aarar% 1
static void wideWvarar%(lon%... *)
1 ystem.out.println(Flon%...F); 2
static void bo*Wvarar%(-nte%er... *)
1 ystem.out.println(F-nte%er...F); 2
public static void main(trin% [] ar%s) 1
int i D 9;wideWvarar%(9,9); 33 needs to widen and use varar%s
8/12/2019 SCJP Exam310 055 Notes
16/46
bo*Wvarar%(9,9); 33 needs to bo* and use varar%s
2
2
This compiles and produces!
lon%...-nte%er...
'ere#s a review of the rules for overloadin% methods usin%
widenin%, bo*in%, and varar%s!
. Primitive widenin% uses the FsmallestF method ar%ument
possible.
.>sed individually, bo*in% and varar%s are compatible with
overloadin%.
.Kou CC@T widen from one wrapper type to another. (- fails.)
.Kou CC@T widen and then bo*. (n int can#t become a 7on%.)
.Kou can bo* and then widen. (n int can become an @b$ect, via
-nte%er.)
.Kou can combine varar%s with either widenin% or bo*in%.
+GFric Little finali5e() 6otcha's
There are a couple of concepts concernin% finali"e() that you
need to remember.
. Hor any %iven ob$ect, finali"e() will be called only once (at
most) by the%arba%e collector.
. allin% finali"e() can actually result in savin% an ob$ect from
deletion.7et#s look into these statements a little further. Hirst of all,
remember that any code that you can put into a normal method you
can put into finali"e(). Hor e*ample, in the finali"e() method
you could write code that passes a reference to the ob$ect in
&uestion back to another ob$ect, effectively uneligibli"ing the
ob$ect for %arba%e collection. -f at some point later on this
same ob$ect becomes eli%ible for %arba%e collection a%ain, the
%arba%e collector can still process this ob$ect and delete it.
The %arba%e collector, however, will remember that,
+MF=iven!
class ard/oard 1
hort story D 9;
ard/oard %o(ard/oard cb) 1
cb D null;
return cb;
2
public static void main(trin%[] ar%s) 1
ard/oard c+ D new ard/oard();
ard/oard c4 D new ard/oard();ard/oard c5 D c+.%o(c4);
8/12/2019 SCJP Exam310 055 Notes
17/46
c+ D null;
33 do tuff
2
2
Bhen 33 dotuff is reached, how many ob$ects are eli%ible for =V. 8
/. +
. 4
8/12/2019 SCJP Exam310 055 Notes
18/46
6. int[] b D (int[]) a[+];
9. @b$ect o+ D a;
:. int[][] a4 D (int[][]) o+;
G. int[] b4 D (int[]) o+;
M. ystem.out.println(b[+]);. 2
+8. 2
Bhat is the resultV
. 4
/. 6
. n e*ception is thrown at runtime
8/12/2019 SCJP Exam310 055 Notes
19/46
7ns$er.
X 6 is correct. Two rules apply to the first invocation of doY().
Kou canLt widen and then bo*
in one step, and varar%s are always chosen last. Therefore you
canLt widen shorts to eitherints or lon%s, and then bo* them to -nte%ers or 7on%s. /ut you
can bo* shorts to horts and
then widen them to Cumbers, and this takes priority over usin% a
varar%s method. The
second invocation uses a simple bo* from int to -nte%er.
X7& %& "& 8& E& and 9 are incorrect based on the above.
(@b$ective 5.+)
44F=iven!
+. class onvert 1
4. public static void main(trin%[] ar%s) 1
5. 7on% *7 D new 7on%(69:7);
6. lon% *+ D 7on%.value@f(F+45F);
9. 7on% *4 D 7on%.value@f(F+45F);
:. lon% *5 D *7.lon%Aalue();
G. 7on% *6 D *7.lon%Aalue();
M. 7on% *9 D 7on%.parse7on%(F69:F);
. lon% *: D 7on%.parse7on%(F+45F);
+8. 2
++. 2Bhich will compile usin% Java 9, but will C@T compile usin% Java
+.6V (hoose all that apply.)
. 7ine 6.
/. 7ine 9.
. 7ine :.
8/12/2019 SCJP Exam310 055 Notes
20/46
G. e+.e D e5;
M. e4 D null;
. e5 D null;
+8. e4.e D e+;
++. e+ D null;+4. 2
+5. ?co e;
+6. 2
t what point is only a sin%le ob$ect eli%ible for =V
. fter line M runs.
/. fter line runs.
. fter line +8 runs.
8/12/2019 SCJP Exam310 055 Notes
21/46
Bhat is the resultV
. pre b+ b4 r5 r4 hawk
/. pre b4 b+ r4 r5 hawk
. pre b4 b+ r4 r5 hawk r+ r6
8/12/2019 SCJP Exam310 055 Notes
22/46
boolean b4 D false;
boolean b5 D true;
if((b+ Z b4) (b4 Z b5) Z b5)
ystem.out.print(Falpha F);
if((b+ D false) (b+ Z b5) (b+ b4))ystem.out.print(Fbeta F);
2
2
Bhat is the resultV
. beta
/. alpha
. alpha beta
8/12/2019 SCJP Exam310 055 Notes
23/46
either operand is a trin%,the operands are concatenated. -f both
operands are numbers they are added to%ether.>nbo*in% works in
con$unction with concatenation.
X7& %& "& 8& E& 9& H& and I are incorrect based on the above.
(@b$ective G.:)4MF switch#s e*pression must evaluate to a char, byte, short,
int, or, as of Java 9, an enum. That means if you#re not usin% an
enum, only variables and values that can be automatically
promoted (in other words, implicitly cast) to an int are
acceptable. Kou won#t be able to compile if you use anythin%
else, includin% the remainin% numeric types of lon%, float, and
double.
case constant must evaluate to the same type as the switch
e*pression can use, with one additionaland bi%constraint! the
case constant must be a compile time constantE ince the case
ar%ument has to be resolved at compile time, that means you can
use only a constant or final variable that is assi%ned a literal
value. -t is not enou%h to be final, it must be a compile time
constant. Hor e*ample!
final int a D +;
final int b;
b D 4;
int * D 8;
switch (*) 1case a! 33 ok
case b! 33 compiler error
7ook at the followin% switch!
byte % D 4;
switch(%) 1
case 45!
case +4M!
2
This code won#t compile. lthou%h the switch ar%ument is le%ala
byte is
implicitly cast to an intthe second case ar%ument (+4M) is too
lar%e for a byte,
and the compiler knows itE ttemptin% to compile the precedin%
e*ample %ives
you an error somethin% like
Test.$ava!:! possible loss of precision
found ! int
re&uired! byte
case +4M!-t is le%al to levera%e the power of bo*in% in a switch
8/12/2019 SCJP Exam310 055 Notes
24/46
e*pression. Hor instance,
the followin% is le%al!
switch(new -nte%er(6)) 1
case 6! ystem.out.println(Fbo*in% is @NF);
24Ffor(declaration : expression)
The two pieces of the for statement are
declarationThe newly declared block variable, of a type compatible with the
elements of the array you are accessing. This variable will be available within
the for block, and its value will be the same as the current array element.
expressionThis must evaluate to the array you want to loop through. This
could be an array variable or a method call that returns an array. The array
can be any type: primitives, objects, even arrays of arrays. Using the above
denitions, let's look at some legal and illegal enhanced for
declarations:
int x;
long x2;
Long [] La = {4L, 5L, 6L};
long [] la = {7L, 8L, 9L};
int [][] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}};
String [] sNums = {"one", "two", "three"};
Animal [] animals = {new Dog(), new Cat()};
// legal 'for' declarations
for(long y : la ) ; // loop thru an array of longs
for(long lp : La) ; // autoboxing the Long objects into longs
for(int[] n : twoDee) ; // loop thru the array of arrays
for(int n2 : twoDee[2]) ; // loop thru the 3rd sub-array
for(String s : sNums) ; // loop thru the array of Strings
for(Object o : sNums) ; // set an Object reference to each String
for(Animal a : animals) ; // set an Animal reference to each element
// ILLEGAL 'for' declarations
for(x2 : la) ; // x2 is already declared
for(int x2 : twoDee) ; // can't stuff an array into an int
for(int x3 : la) ; // can't stuff a long into an int
for(Dog d : animals) ; // you might get a Cat!
58FIt is illegal to use a try clause without either a catch clause or a
finally clause. A try clause by itself will result in a compiler error.
Any catch clauses must immediately follow the try block. Any finally
clause must immediately follow the last catch clause (or it must
immediately follow the try block if there is no catch). It is legal to
omit either the catch clause or the finally clause, but not both. You
cant sneak any code in between the try, catch, or finally blocks. The
following wont compiletry {
8/12/2019 SCJP Exam310 055 Notes
25/46
// do stuff
}
System.out.print("below the try"); //Illegal!
catch(Exception ex) { }
all nonRuntimeExceptions are considered !checked! e"ceptions, because thecompiler checks to be certain you've acknowledged that !bad things could
happen here.!
Each method must either handle all checked exceptions by supplying a catch
clause or list each unhandled checked exception as a thrown exception.
RuntimeException, Error, and all of their subtypes are unchecked e"ceptions
and unchecked e"ceptions do not have to be specied or handled.
5+F9:;
?@ABCEF;FG:AGHIJKFLLMFLC
8/12/2019 SCJP Exam310 055 Notes
26/46
1. class Loopy {
2. public static void main(String[] args) {
3. int[] x = {7,6,5,4,3,2,1};
4. // insert code here
5. System.out.print(y + " ");
6. }
7. } }
#hich, inserted independently at line 1, compiles$ %&hoose all that apply.
(. for(int y : x) {
). for(x : int y) {
&. int y = 0; for(y : x) {
*. for(int y=0, z=0; z
8/12/2019 SCJP Exam310 055 Notes
27/46
(nswer:
F is correct. ( switch statement re7uires its case e"pressions to be
constants, and wrapper variables %even final static ones arent considered
constants. The rest of the code is correct.
A, B, C, D, E, and G are incorrect based on the above. %/bjective 0.556FStringBufer vs. StringBuilder
The 8tring)uilder class was added in 9ava . -t has e"actly the same (;- as the
8tring)u
8/12/2019 SCJP Exam310 055 Notes
28/46
!%! +nclose negative numbers in parentheses
widtThis value indicates the minimum number of characters to print. %-f you
want nice even columns, you'll use this value e"tensively.
precision or the e"am you'll only need this when formatting a Coatingpoint
number, and in the case of Coating point numbers, precision indicates thenumber of
digits to print after the decimal point.
conversionThe type of argument you'll be formatting. @ou'll need to know:
b boolean c char
d integer f Coating point s string
Det's see some of these formatting strings in action:
int i1 = -123; int i2 = 12345;
System.out.printf(">%1$(7d< \n", i1);
System.out.printf(">%0,7d< \n", i2);
System.out.format(">%+-7d< \n", i2);
System.out.printf(">%2$b + %1$5d< \n", i1, false);
This produces:
> (123)012,345+12345 false + -123y&lass, the e7uivalent code is as follows:
public static int getCount() {
synchronized(MyClass.class) {
return count;
8/12/2019 SCJP Exam310 055 Notes
43/46
}
}
#aitLwhat's that MyClass.class thing$ That's called a class literal. -t's a
special feature in the 9ava language that tells the compiler %who tells the 9Q>:
go and nd me the instance of &lass that represents the class called >y&lass.@ou can also do this with the following code:
public static void classMethod() {
Class cl = Class.forName("MyClass");
synchronized (cl) {
// do stuff
}
}
9:Fwait!"# notiy!"# and notiyAll!" must be called rom within a synchroni$ed
context A thread can%t invoke a wait or notiy method on an object unless it
owns that object%s lock.
The methods wait() , notify(), and notifyAll() are methods of only
%a&a.lang.b%ect, not of %a&a.lang.Thread or %a&a.lang.!unnable. +e
sure you know which methods are de6ned in Thread, which in b%ect,
and which in !unnable (%ust run(), so thats an easy one). f the key
methods in Thread, be sure you know which are staticsleep() and
yield(), and which are not staticjoin() and start().
9GF2iven the following
@S^K JJKFLLF:Cd
8/12/2019 SCJP Exam310 055 Notes
44/46
D is correct. 5 and 0 will be printed, but there will be no return from the
wait call because
no other thread will notify the main thread, so F will never be printed. -t's
fro=en at line 3.
A is incorrectB IllegalMonitorStateException is an unchecked e"ception. Band C are incorrectB F will never be printed, since this program will wait
forever. E is incorrect because IllegalMonitorStateException will never be
thrown because the wait() is done on args within a block of code
synchroni=ed on args. F is incorrect because any object can be used to
synchroni=e on and this and static don't mi". %/bjective 1.1
9MF2iven:
@S^K JLCFC JLb=JWBA= t
8/12/2019 SCJP Exam310 055 Notes
45/46
T =FKdWB
8/12/2019 SCJP Exam310 055 Notes
46/46
%remember they're static and final, and static methods.
:+Fwhich of the followin% statements is tureV
-n an assert statement, the e*pression after the colon(!) can
be any Java e*pression.
/ -f a switch block has no default, addin% an assert default isconsidered appropriate.
-n an assert statement, if the e*pression after the colon(! )
doe not have a value, the assertLs error messa%e will be empty.
< -t is appropriate to handle assertion failures usin% a catch
clause.
?*planation!
/ is correct. is incorrect because only Jave e*pressions that
return a value can be used. Hor e*ample, a method that returns
void is ille%al. is incorrect because the e*pression after the
colon must have a value.
:4Fssumin% that an interrupted e*ception has C@T been thrown and
that \a7iveThread is a runnable thread, which three %uarantee
that a thread will leave the runnin% stateV
yield() / wait() notify() < notifyll()
? sleep(+888) H a7iveThread.$oin() = Thread.killThread()
/,?,H is correct. is incorret, the yield() method is not
%uaranteed to cause a thread to leave the runnin% state, althou%h
if there are runnabel threads of the same priority as the
currently runnin% thread, then the current thread will probablyleave the runnin% state.
:5FBhich instantiation creates the ti%htest couplin%V
/io