OCA_Summary.pdf

Share Embed Donate


Short Description

Download OCA_Summary.pdf...

Description

OCA Summary : Chapter 1 : Java Basics ■

The structure of a Java class and source code file If a class includes a package statement, all the i mpor t statements should follow it.



A Java source code file (.java file) can define multiple classes and interfaces. ■ A publ i c class can be defined only in a source code file with the same name. por t statements apply to all the classes and interfaces defined in the same source ■ package and i m code file (.java file). . l ang ang & package with no name (if there’s no package declaration) are by default imported. ■ Syst em

Executable Java applications ai n method with the signature publ i c ■ For a class to be executable, the class should define a m st at i c voi d mai n( St r i ng ar gs[ ] or   St St r i ng. . . var ar gs or   St St r i ng[ ] ami nes) . at i c and publ i c can be interchanged. The positions of s t at ai n, provided that the signature of these ■ A class can define multiple methods with the name m t hese methods doesn’t match the signature of the t he mai n method defined in the previous point. po int. These other methods with different signatures aren’t considered the mai n method. Java packages ■

You can import either a single member or all members (classes and a nd interfaces) of a package using the i mpor t statement. ■ You can’t import classes from a subpackage by using the wildcard character, an aster isk (* ), in the i mpor t statement. ■ A class from a default package can’t be used in any named packaged class, regard less of whether it’s defined within the same directory or not. ■ i

mpor t st at i c . . *;  i mpor t st at i c . ; ass>;  i mpor t st at i c . . ;  i mpor t st at i c . *;



The members of default packages are accessible only to classes or interfaces defined in the same directory on your system. et hod( )  : i mpor t st at i c . . ass>. met hod ■ The syntax to import st at i c m

Java modifiers  Access modifiers modifiers  public  protected default  private Non-access modifiers

Package Classes

Non-package Classes

Nested Classes









if derived 















abstract

Interface redundant

 final



static strictfp synchronized native transient volatile

Class abstract/concrete methods cannot be extended only nested

Variable

Method  no body can’t be static 1 assignement cannot be  possible overriden common to all instances access only static members   (none-abstract)

































 (none- local)



pr ot ect ed and pr i vat e are not valid modifiers for a class or interface definition. ■ A pr i vat e method cannot be abst r act ■  A return type must be directly before the t he method’s name. ■

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 m i 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. ■ com par eTo( Wr apper )  compares two wrappers of the same type. ■ pr i m i t i veVal ue( ) returns the primitive value of the conversion of the selected wrapper. ■ st at i c par s ePr i m i 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). ■ s t at i c val ueOf ( St r i ng/ pr i m i t i ve) returns the primitive wrapper value of the para meter. ■ s t at i c t oSt r i ng( pr i m i 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 a l 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 a f 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 a doubl e value. Though it’s allowed, doing so is not required because the default value o f decimal literals is doubl e. ■ Decimal types accept all integer types (including char ). char  accepts only litterals and char . ■ Integers accept char  litterals depending on their capacity, but only i nt  & l ong accepts a char variable. ■ A method can’t accept an argument that is a literral without casting it if the parameter is an integer different than i nt  or l 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 a f 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. (or 0) to a maximum of ’ \ uf f f f ’ (or 65,535 inclusive) to store ■ You can use values from ’ \ u0000’ 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 integer value to a char instead of a letter, such as 122. ■

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 Unary new & Cast  Multiplication  Addition  Relational  Equality  Logical AND  Logical OR Conditional  Assignement ■

a++, a- - , [ ] , . member , met hod( ) , ++a, - - a, ! , ~ new, ( cast ) *, / , % +, , = ==, ! = && || ?: =, +=, - =, * =, / =, %=

All compound assignment operators internally do an explicit cast.

Left to Right Right to Left Right to Left Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Right to Left 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 , cons t r uc t or par ent , i ni t c hi l d, c ons t r uct or c hi 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 variables and allow access to these variables using methods. ■

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 of St 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 trim    () 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    ( )16 chars, (String) +16 chars, St r i ngBui l der (CharSequence) (int capacity) 2 append    add at the end: (type) (CharSequence,start,nb) 3 i ns er 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 arr ay, and initialization of array elements. ■ Square brackets can follow either the variable na me 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 t he 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 dest Pos, i nt l engt h) (Syst em. ar r aycopy) ■

ArrayList method

Parameters (object) (i, object) add (i, object) set (i) (object) first occurence, test of equality with equals() remove (Collection) (i, Collection) addAll () clear, size, clone, toArray (i) get true, false (object) index, -1 contains, indexOf, lastIndexOf ■ 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. allows nul l values to be added to it. ■ Ar r ayL i s t supports generics, making it type safe. ■ Ar r ayL i s t is used to store the data in an Ar r ayLi st . ■ Internally, an array of type j ava. l ang. Obj ect ■ To access the elements of an Ar 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 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 or Li 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 an Ar r ayLi s t 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 . ■ An Ar r ayLi st  can only store Objects. ■ Ar r ayLi st  implements Random Acc es s  interface  direct access  constant time access. ■ Ar r ayLi st < E>extends Abst r act Li st extends Abst r act Col l ect i on. ■ Ar r ayLi st < E>implements Ser i al i z abl e, Cl oneabl e, Li st , RandomAcces s. ■ Li st < E>extends  Col l ect i on, I t er abl e.

Comparing objects for equality method only compares whether two ■ Except for String, The default implementation of the equal s object variables refer to the same object. ■ Java equals contract : publ i c bool ean equal s( obj ect o) : reflexive, symmetric, transitive, consistent, same class, i f ( x ! =nul l ) x. equal s ( nul l ) r et ur ns f al s e.

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 the swi t ch statement. ■ The case value can’t be the literal value nul 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 for 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 is f i nal .

Labeled statements You can add labels ( l abel :  ) to a code block defined using braces, {}, all looping statements ( f or , enhanced f 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. statement to skip the iteration of the outer loop. ■ You can use a labeled cont i nue l abel ; ■ If not inside a loop, you can’t use a br eak or a cont i nue statement inside an i f  or el 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 w hi l e header is required. ■ It is a compilation error to put f al se as a condition test in a whi l e or f or  header (block unreachable). Conditions ■ ■

It is not a compilation error to put a f 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 implicitly publ 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. ■ An abstract class can inherit a concrete class, and a concrete class can inherit an abstract class. ■ A base class can use reference variables and objects of its derived classes. ■ The keyword ext ends should always come before i m pl ement s . ■ An interface can only be instantiated with an ano nymous inner class. ■

Using super and this to access objects and constructors ■ The reference variable super can be used to access a var iable 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 variable t 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 variables t 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. ■ An abst 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 declared st 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( ) ; ■ To access a shadowed variable x of the OuterClass in it’s InnerClass : Out er Cl as s. t hi s . x

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. or cat ch  block defines a r et ur n statement. ■ A f i nal l y  block will execute even if a t r y ■ 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 a cat ch  block returns a primitive data type, a f i nal l y  block can’t modify the value being returned  by it. If a cat ch  block returns an object, a f i nal l y  block can modify the value being returned by it. ■ The f i nal l y  block can’t appear before a cat ch  block. ■ The f i nal l y  block always executes except if there is a Syst em . exi t ( )  call. ■

Categories of exceptions SecurityException IllegalStateException NullPointerException IOException

ClassCastException

 java.lang.Exception  java.lang.RuntimeException NoClassDefFoundError

 java.lang.Throwable

IllegalArgument Exception

AssertionError  java.lang.Error

ExceptionInInitializerError StackOverFlowError OutOfMemoryError

IndexOutOf BoundsException

NumberFormat Exception ArrayIndex OutOfBounds Exception StringIndex OutOfBounds

If a method calls another method that may throw a checked exception, either it must be enclosed wit hin a t r y- cat c h  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. is thrown by the JVM or a Cl assLoader when it is unable to load the ■ NoCl assDef FoundEr r or 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. ■ When pr 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. When Syst 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 NoSuchM et hodEr r or . ■

BAGDOURI Mohammed Amine

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF