OCA Summary :
OCA Summary :
Chapter 1 : Java Basics
Chapter 1 : Java Basics
The structure of a Java class and source code file
The structure of a Java class and source code file
■■ If a class includes aIf a class includes a
package
package
statement, all thestatement, all theii m
mp
po
orr tt
statements should follow it.statements should follow it.■
■ A Java source code file (.java file) can define multiple classes and interfaces.A Java source code file (.java file) can define multiple classes and interfaces.
■
■ AA
p
pu
ub
bll ii c
c
class can be defined only in a source code file with the same name.class can be defined only in a source code file with the same name.■
■
package
package
andandii m
mp
po
orr tt
statements apply to all the classes and interfaces defined in the same sourcestatements apply to all the classes and interfaces defined in the same source code file (.java file).code file (.java file).
■
■
S
Syst
yst em
em.. ll an
ang
g
& package with no name (if there’s & package with no name (if there’s no package declaration) are by default no package declaration) are by default imported.imported.Executable Java applications
Executable Java applications
■■ For a class to For a class to be executable, the class should define abe executable, the class should define a
m
mai
ai n
n
method with the signaturemethod with the signaturep
pu
ub
bll ii c
c
st
st a
att ii c
c v
vo
oii d
d m
ma
aii n
n(( S
Stt rr ii n
ng
g a
arr g
gs[
s[ ]]
or orS
Stt rr ii n
ng
g.. .. .
. v
va
arr a
arr g
gs
s
or orStt rr ii n
S
ng
g[[ ]
] a
am
mii n
ne
es)
s)
..The positions of
The positions of
s t a
s t att ii c
c
andandp
pu
ub
bll ii c
c
can be interchanged.can be interchanged.■
■ A class can define multiple A class can define multiple methods with the namemethods with the name
m
mai
ai n
n
, provided that the signature of t, provided that the signature of these methodshese methods doesn’t match the signature of tdoesn’t match the signature of thehe
m
mai
ai n
n
method defined in the previous pomethod defined in the previous point. These other methods withint. These other methods with different signatures aren’t considereddifferent signatures aren’t considered thethe
mai
m
ai n
n
method.method.Java packages
Java packages
■■ You can import either a single You can import either a single member or all members (classes amember or all members (classes and interfaces) of a package using thend interfaces) of a package using the
ii m
mp
por
or tt
statement.statement.■
■ You can’t import classes You can’t import classes from a subpackage by using the wildcard character, an asterfrom a subpackage by using the wildcard character, an aster isk (isk (
**
), in the), in theii m
mp
por
or tt
statement.statement.■
■ A class from a default A class from a default package can’t be used in any named packaged class, regardpackage can’t be used in any named packaged class, regard less of whether it’sless of whether it’s defined within the same directory or
defined within the same directory or not.not.
■
■
ii m
mp
po
orr t
t st
st at
at ii c <
c <p
pa
acka
ckag
ge
e>
>.. <
<cl
cl ass>
ass>.. *;
*;
ii m
mp
por
or t
t st
st at
at ii c <
c <p
packa
ackag
ge>
e>.. <
<cl
cl ass>
ass>;;
ii m
mp
po
orr t
t st
st a
att ii c
c <
<p
pa
acka
ckag
ge
e>
>.. <
<cl
cl a
ass
ss >
>.. <
<ff ii e
ell d
d>
>;;
ii m
mp
po
orr t
t st
st at
at ii c <
c <p
pack
acka
ag
ge
e>
>.. *;
*;
■
■ The members of default packages are accessible only to classes or interfaces defined in the sameThe members of default packages are accessible only to classes or interfaces defined in the same directory on your system.
directory on your system.
■
■ The syntax to importThe syntax to import
st
st a
att ii c
c m
me
ett h
ho
od
d(( ))
: :ii m
mp
por
or t
t st
st at
at ii c
c <
<p
packa
ackag
ge>
e>.. <
<cl
cl ass>
ass>.. m
met
et h
hod
od
Java modifiers
Java modifiers
Access modifi
Access modifiersers Package Package Classes Classes Non-package Non-package Classes Classes Nested Nested ClassesClasses
public
public
protected
protected if derived if derived
default
default
private
private
Non-access modifiers
Non-access modifiers Interface Interface Class Class Variable Variable MethodMethod
abstract
abstract redundant redundant abstract/concreteabstract/concrete methods methods no bodyno body can’t be static can’t be static final
final cannot becannot be extended extended 1 assignement 1 assignement possible possible cannot be cannot be overriden overriden static
static only only nested nested common common to to all all instancesinstances access only static members access only static members strictfp
strictfp (none-abstract)(none-abstract) synchronized synchronized native native transient transient volatile
volatile (none- local)(none- local)
■
■ pprr oott eectct eedd and andpprr ii vvaatt ee are not valid modifiers for a are not valid modifiers for a class or interface definition.class or interface definition. ■
Chapter 2 : Working with Java data types
Primitive data types
■ Primitive data types: char, byt e, shor t, i nt,l ong, f l oat, doubl e, and bool ean.
Primitive wrappers
■ Pr i mi t i veWr apper . MI N_VALUE + 1 == Pr i mi t i veWr apper . MAX_VALUE. ■ Two primitive wrappers are never compatible (ex : I nt eger & Long).
■ Primitive wrappers are immutable. When trying to modify a primitive wrapper value, a new instance is
created and the original instance re mains unchanged.
■ A primitive wrapper constructor’s argument accepts only a compatible primitive value. ■ A primitive wrapper can be compared to a compatible primitive using the == operator.
■ A primitive wrapper’s constructor accepts e ither the primitive value or the String representation. ■ compar eTo( Wr apper ) compares two wrappers of the same type.
■ pr i mi t i veVal ue( ) returns the primitive value of the conversion of the selected wrapper. ■ st at i c par sePr i mi t i ve( St r i ng) returns the primitive value of the String (if it is valid). ■ st at i c decode( St r i ng) returns the primitive wrapper value of the String (if it is valid).
■ st at i c val ueOf ( St r i ng/ pr i mi t i ve) returns the primitive wrapper value of the para meter. ■ s t at i c t oSt r i ng( pr i mi t i ve) returns the String value of the parameter
■ t oSt r i ng( ) returns the String value of the selected wrapper.
■ If a method is given a primitive argument and no method signature with a co rresponding primitive type
was found. The primitive is boxed into a wrapper to find a corr esponding object type parameter method.
■ Java reuses all wraper objects whose values are between -128 and 127.
Numeric data types
■ The float and double data types use 32 and 64 bits, respect ively, to store their values. ■ The default type of integers—that is, nondecimal numbers—is i nt.
■ To designate an integer literal value as al ong value, add the suffix L or l to the literal value. ■ Prefixes : octal : 0 (zero), hexadecimal : 0x or 0X, binary : 0b or 0B.
■ Underscores within the Java literal values : not in : start, end, after binary or hexa prefixes, before
suffixes (l, L, f, F, d, D) , adjacent to a point, string of digits..
■ The default type of a decimal number is doubl e.
■ To designate a decimal literal value as af l oat value, add the suffix F or f to the literal value. ■ The suffixes D and d can be used to mark a literal value as adoubl e value. Though it’s allowed,
doing so is not required because the default value of decimal literals is doubl e.
■ Decimal types accept all integer types (includingchar). char accepts only litterals andchar. ■ Integers acceptchar litterals depending on their capacity, but only i nt & l ong accepts achar
variable.
■ A method can’t accept an argument that is a literral without casting it if the parameter is an integer
different thani nt orl ong.
■ When comparing a decimal to an integer, the decimal is cast ed to it’s integer value. ■ There is a loss of precision when cast ing to af l oat or doubl e.
■ All operands of type byte, char or short are promoted AT LEAST to an int before math operations. ■ CONSTANT values up to i nt can be assigned to variables of lesser size if it fits.
Character primitive data types
■ A char data type can store a single 16-bit Unicode character; that is, it can store characters from
virtually all the world’s existing scripts and languages.
■ You can use values from ’ \ u0000’ (or 0) to a maximum of’ \ uf f f f ’ (or 65,535 inclusive) to store
a char. Unicode values are defined in the hexadecimal number syste m.
■ Internally, the char data type is stored as an unsigned integer value (only positive integers).
■ When you assign a letter to a char, Java stores its integer equivalent value. You may assign a positive
Valid identifiers
■ A valid identifier starts with a letter, a currency sign, or an underscore.
■ A valid identifier can’t contain any special characters, including!,@,#,%, ^,&,*, (,
), ' ,: ,; , [,/ , \ , or}.
■ Keywords : assert, goto, const, native, strictfp, volatile, instanceof, default, null.
Operators
Precedence
Postfix a++, a- - , [ ] , . member , met hod( ) , Left to Right Unary ++a, - - a, ! , ~ Right to Left new & Cast new, ( cast ) Right to Left Multiplication *, / , % Left to Right
Addition +, - Left to Right
Relational <, >, <=, >= Left to Right
Equality ==, ! = Left to Right
Logical AND && Left to Right
Logical OR | | Left to Right
Conditional ?: Right to Left
Assignement =, +=, - =, *=, / =, %= Right to Left
Chapter 3 : Methods and encapsulation
Scope of variables
■ In a method, if a local variable exists with the same name as an instance variable, the local variable takes
precedence.
■ If a reference variable A can never reference a variable of type B :A i nst anceof B is a compilation
error. Otherwise it is not a compilation error but it could be a runtime exception.
■ A st at i c method can’t be abst r act. ■ An unprecedeed semicolon is allowed.
Object’s lifecycle
■ Varargs : i nt . . . days : only one and the last one in parameters list.
■ If there is code that can be executed only after a r et ur n statement, the class will fail to compile.
Create an overloaded method
■ It is a compilation error when calling an overloaded method that accepts literal values t hat may
correspond to 2 different types ( example : doubl e mi n( doubl e a, i nt b) ; doubl e mi n( i nt a, doubl e b) ; doubl e x = mi n( 2, 3) ; ).
■ For Objects & primitives, when a method is called it’s parameters are expanded to the exact match prior
to their nearest type. For primitives : widening is preferred to wrappers, wrappers are preferred to varargs.
Constructors of a class
■ Default constructors are defined by Java, but only if the developer doesn’t define a ny constructor in a
class.
■ Constructors are NEVER inherited.
■ You can define a constructor using the four access modifiers: publ i c, pr ot ect ed, default, and
pr i vat e.
■ If you define a return type for a constructor, it’ll no longer be treated like a constructor.
■ An initializer block is defined within a class, not as a part of a method. It executes for every object that’s
created for a class.
■ If you define both an initializer and a constructor for a class, both of these will execute. The initializer
block will execute prior to the constructor.
■ Unlike constructors, an initializer block can’t accept method parameters.
■ An initializer block can create local variables. It can access and assign values to instance and static
variables. It can call methods and define loops, conditional statements, and t r y-cat ch-f i nal l y blocks.
■ Constructors can’t exist without a body.
■ Constructors accept all but only access modifiers.
■ Constructors may end with a semi-colon (ignored by the compiler).
■ The access type of a default constructor is same as the access type of the class.
■ Order of precedence when instantiating a class : s t at i c par ent , s t at i c chi l d, i ni t
par ent , const r uct or par ent , i ni t chi l d, const r uct or chi l d.
■ An initializer (or st at i c) block is called when a member (non-constant) or a constructor declared in the
class (rather than inherited) is invoked, used or assigned. It’s not called by only declaring a re ference variable.
■ It is an obligation to initialize a f i nal instance variable either in a constructor or in an initializer block. ■ Unlike non-final instance var iables, f i nal instance variables must be initialized before use.
Accessing object fields
■ The terms encapsulation and information hiding are also used interchangeably.
■ One of the best ways to define a well-encapsulated class is to define its instance variables as private
Chapter 4 : String, StringBuilder, Arrays, ArrayList
String & StringBuilder
■ A St r i ng object can be created by using the operator new, by using the assignment operator (=), or by
using double quotes.
■ St r i ng objects created using the assignment operator are placed in a pool ofSt r i ng objects. ■ St r i ng objects created using the operator new are never placed in the pool of St r i ng objects. ■ if not overloaded the method t oSt r i ng( )of any object returns : object’s name +hashCode( ). ■ StringBuffer synchronized StringBuilder.
method String StringBuilder Parameters Mod
1 char At (int index)
2 subst r i ng (int start) (int start, int end) returns String 3 subSequence (int start, int end) returns CharSequence
4 l engt h ( )
1 i ndexOf (char) (String) (char/String, int start)
2 t r i m ( )
3 st ar t sWi t h (String) (String, int startOrig)
4 endsWi t h (String)
5 r epl ace (char old, char new) (CharSequence old,
CharSequence new)
6 i nt er n () returns reference of the string in the pool 7 equal sI gnor eCase ()
8 concat (String new)
1 new
St r i ngBui l der
( )16 chars, (String) +16 chars, (CharSequence) (int capacity)
2 append add at the end: (type)
(CharSequence,start,nb)
3 i nser t (startOrig, CharSequence, startNew,
nbNew) (startOrig, type)
4 del et e (int start, int end) 5 del et eChar At (int pos)
6 reverse ( )
7 r epl ace (int start, int end, String new) 8 set Lengt h (int) appends 0s at the end if larger 9 ensur eCapaci t y (int minimum) sets capacity if less
0 i ndexOf (String) (String, int start)
*end not included
Arrays
■ An array’s size only accepts byte, char, short, int. It is allowed to be equal to a 0.
■ The creation of an array involves three st eps: declaration of an array, allocation of an array, and
initialization of array elements.
■ Square brackets can follow either the variable name or its type and they should be empty. In the case of
multidimensional arrays, it can follow both of them.
■ i nt T[ ] =new i nt [ 5] ; i nt T[ ] [ ] ={{0, 1}, {3, 4, 5}};
i nt T[ ] [ ] =new i nt [] [] {{0, 1}, {3, 4, 5}}; i nt T[ ] ; T=new i nt [] {0, 1};
i nt T[ ] ; T={0, 1}; i nt [ ] mul t i Ar r [ ] ; mul t i Ar r = new i nt [ 2] [ ] ;
■ The Java compiler doesn’t check the range of the index positions at which you try to access an array
element.
■ All the arrays are objects and can access the variable l engt h, which specifies the number or
components stored by the array.
■ For primitives, an array of a certain type can’t refer to an arra y of a compatible type (Ex : int[] array =
new char[5] ). But for objects it’s possible (Ex : Animal[] array = new Lion[10] ).
■ publ i c st at i c voi d ar r aycopy( Obj ect sr c, i nt sr cPos, Obj ect dest , i nt
ArrayList
method Parameters
add (object) (i, object)
set (i, object)
remove (i) (object) first occurence, test of equality with equals() addAll (Collection) (i, Collection)
clear, size, clone, toArray ( )
get (i)
contains, indexOf, lastIndexOf true, false (object) index, -1
■ By default, an Ar r ayLi st creates an array with an initial size of 10 to store its elements. ■ Unlike arrays, you don’t have specify an initial size t o create an Ar r ayLi st.
■ If you frequently add elements to an Ar r ayLi st, specifying a larger capacity will improve the code
efficiency.
■ Ar r ayLi st allowsnul l values to be added to it. ■ Ar r ayLi st supports generics, making it type safe.
■ Internally, an array of type j ava. l ang. Obj ect is used to store the data in anAr r ayLi st.
■ To access the elements of anAr r ayLi st, you can use either the enhanced f o r loop,I t er at or, or
Li s t I t er at or :
Li s t I t er at or <St r i ng> i t er at or = myAr r Li s t . l i s t I t er at or ( ) ; Whi l e( i t er at or . has Next ( ) ) . . . i t er at or . next ( ) . . .
■ An iterator (I t er at or orLi s t I t er at or) lets you remove elements as you iterate through an
Ar r ayLi st. It’s not possible to remove elements from anAr r ayLi st while iterating through it using a
f o r loop.
■ Ar r ayLi st has subclasses such as At t r i but eLi s t, Rol eLi st & Rol eUnr esol vedLi st. ■ AnAr r ayLi st can only store Objects.
■ Ar r ayLi st implements RandomAcc es s interface direct access constant time access. ■ Ar r ayLi st <E>extends Abst r act Li st <E>extends Abst r act Col l ect i on<E>.
■ Ar r ayLi st <E>implementsSer i al i z abl e,Cl oneabl e,Li st <E>, RandomAcces s. ■ Li st <E>extends Col l ect i on<E>,I t er abl e<E>.
Comparing objects for equality
■ Except for String, The default implementation of the equal s method only compares whether two
object variables refer to the same object.
■ Java equals contract :publ i c bool ean equal s( obj ect o) : reflexive, symmetric, transitive,
Chapter 5 : Flow Control
switch statements
■ A swi t ch accepts only char, byte, short, int, String (and Enums) as a variable or expression.
■ The case value should be a compile-time constant (f i nal and assigned at declaration or literrals),
assignable to the argument passed to theswi t ch statement.
■ The case value can’t be the literal valuenul l . ■ The case values cannot be repeated.
■ A swi t ch head accepts a constant.
■ A swi t ch must have a body but could be empty. There could be nothing after a case label as well.
for loops
■ The definition of any of the three f o r statements—initialization statements, termination condition, and
update clause—is optional. For example, f or ( ; ; ) ; and f o r ( ; ; ) { } are valid code for defining a
f o r loop (infinite loops).
■ A f o r loop can declare and initialize multiple variables in its initialization block, but the variables that
it declares should be of the same type.
■ The update clause of a f o r loop may contain only : increment/decrement expression, method invocation
or class instance creation expression.
Enhanced for loops
■ The enhanced f o r loop can’t be used to initialize an arra y and modify or delete its elements. ■ The enhanced f o r loop elements are passed by value.
■ The only valid modifier for the enhanced f o r loop iterator isf i nal .
Labeled statements
■ You can add labels ( l abel : ) to a code block defined using braces, {}, all looping statements (f or,
enhancedf o r loop,whi l e, do-whi l e), conditional constructs (i f and swi t ch statements), expressions and assignments, r et ur n statements, t r y blocks,t hr ows statements or method calls.
■ You can’t add labels to declarations of variables.
■ If there is no brace { after the label. Only one expression is included in the label’s area. ■ You can use a labeled br eak l abel ; statement to exit an outer loop or any kind of block. ■ You can use a labeled cont i nue l abel ; statement to skip the iteration of the outer loop.
■ If not inside a loop, you can’t use a br eak or a cont i nue statement inside an i f orel s e block. ■ br eak/ cont i nue l abel ; must be used inside the block that l abel refers to.
■ A cont i nue statement can be used only in loops.
while & do while loops
■ The condition expression in a whi l e &do whi l e header is required.
■ It is a compilation error to putf al se as a condition test in awhi l e or f or header (block unreachable).
Conditions
■ It is not a compilation error to put af al se as a condition test in an i f header. ■ For the operator ?: both sides of : must return the same type (except void).
Chapter 6 : Working with inheritance
Inheritance with interfaces and classes
■ An interface can extend zero or more interfaces. An interface cannot extend a class or implement an
interface.
■ An interface’s variables are implicitlypubl i c,f i nal & st at i c. They should be assigned at
declaration. It’s methods are implicitly publ i c and they can’t be f i nal or st at i c.
■ Anabstract class can inherit a concrete class, and a concrete class can inherit anabstract class. ■ A base class can use reference variables and objects of its derived classes.
■ The keyword ext ends should always come before i mpl ement s. ■ An interface can only be instantiated with an anonymous inner class.
Using super and this to access objects and constructors
■ The reference variablesuper can be used to access a variable or method from the base class if there is
a clash of these names. This situation normally occurs when a derived class defines var iables and methods with the same names as in the base class.
■ The reference variablet hi s can be used to access the inherited members of a base class in the derived
class.
■ When defining a class that has no constructors, if Java doesn’t find a no-argument constructor in the base
class it fails to compile.
■ The reference variablest hi s and super can’t be used in a static context.
Polymorphism with classes
■ The return type of the overriding method, if it is an Object, can be the same, or a subclass of the return
type of the overridden method in the base class. But should be exactly the same if it is a primitive.
■ Classes are not polymorhpic if they don’t define polymorphic methods, even if they extend each other. ■ Access modifiers for an overriding method can be the sa me or less restrictive but can’t be more
restrictive than the method being overridden.
■ With inheritance, the instance variables, exceptions & static members bind at compile time while
instance methods bind at runtime.
■ The hashcode( ) and equal s( ) methods can be overriden.
■ The overriding method may declare only exceptions declared in the original method or it’s subclass es. It
may choose not to declare any exception as well. ( Checked exceptions).
■ The constructor of a subclass doesn’t have to declare the exceptions declared in the called superclass
constructor. If it declares an exception it can’t be the subclass of t he superclass’s constructor exception.
■ Variables & st at i c methods are not overriden, they are shadowed. ■ There is no way to go more than one level up for non-stat ic methods.
■ Implementing two interfaces that have the same variable name X is no problem. Referring to X is a
compilation error.
■ Anabst r act method can override a concrete method.
■ A st at i c method cannot override a non-static method and vice-versa.
Nested classes
■ Nested classes that are declaredst at i c are called static nested classes. Non-static nested classes are
called inner classes.
■ A nested class can be declared pr i vat e, publ i c, pr ot ect ed, or package private.
■ Static nested classes are accessed using the enclosing class name:Out er Cl ass. St at i cNest edCl as ■ An inner class cannot define any static members itself.
■ An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the
methods and fields of its enclosing instance.
■ To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object
within the outer object with this syntax:
Out er Cl ass. I nner Cl ass i nner Obj ect = out er Obj ect . new I nner Cl ass( ) ;
Chapter 7 : Exception handling
An exception is thrown
■ When a piece of code hits an obstacle in the form of an exceptional condition, it creates an object of
subclass j ava. l ang. Thr owabl e, initializes it with the necessar y information and hands it over to the
JVM.
■ A f i nal l y block will execute even if at r y or cat ch block defines a r et ur n statement.
■ If both cat ch and f i nal l y blocks define r et ur n statements, the calling method will receive the
value from the f i nal l y block.
■ If acat ch block returns a primitive data type, af i nal l y block can’t modify the value being returned
by it. If a cat ch block returns an object, af i nal l y block can modify the value being returned by it.
■ The f i nal l y block can’t appear before acat ch block.
■ The f i nal l y block always executes except if there is aSyst em. exi t ( ) call.
Categories of exceptions
■ If a method calls another method that may throw a checked exception, either it must be enclosed wit hin a
t r y- cat ch block or the method should declare this exception to be thrown in its method signature.
■ You can use the operator i nst anceof to verify whether an object can be cast to another class before
casting it.
■ Runtime exceptions arising from any of the following may throw Exc ept i onI nI ni t i al i z er Er r or:
– Execution of an anonymous st at i c block – Initialization of a st at i c variable
– Execution of a st at i c method (called from either of the previous two items)
■ The error Exc ept i onI nI ni t i al i z er Er r or can be thrown only by an object of a runtime
exception.
■ NoCl assDef FoundEr r or is thrown by the JVMor aCl assLoader when it is unable to load the
definition of a class required to create an object of the class.
■ Local variables can’t be used without being initialized or assigned (compilation error if not guaranteed).
But fields (object’s) and elements (array’s) are implicitly initialized to default values.
■ A Nul l Poi nt er Except i on will be thrown if the JVM finds a nul l exception in the catch header. ■ Whenpr i nt St ackTr ace( ) is called, implicitly (t hr owabl e not catched) or explecitly, it prints a
complete chain of methods names and lines numbers. WhenSyst em. out . pr i nt ( t hr owabl e) is called only the method’s name and the message are printed.
■ Asser t i onEr r or is used when you reach code that should never execute.
■ Advantages of exceptions : Separating Error-Handling Code from "Regular" Code + Propagating Errors
Up the Call Stack + Grouping and Differentiating Error Types.
■ If the JVM doesn’t find the main method it throws NoSuchMet hodEr r or.
BAGDOURI Mohammed Amine
java.lang.Throwable java.lang.Exception IOException java.lang.RuntimeException SecurityException IllegalStateException NullPointerException ClassCastException IllegalArgument Exception NumberFormat Exception IndexOutOf BoundsException ArrayIndex OutOfBounds Exception StringIndex OutOfBounds java.lang.Error NoClassDefFoundError AssertionError ExceptionInInitializerError StackOverFlowError OutOfMemoryError