OCA Summary:: Chapter 1: Java Basics
OCA Summary:: Chapter 1: Java Basics
OCA Summary:: Chapter 1: Java Basics
Java packages
You can import either a single member or all members (classes and interfaces) of a package using the
import statement.
You cant import classes from a subpackage by using the wildcard character, an asterisk (*), in the
import statement.
A class from a default package cant be used in any named packaged class, regardless of whether its
defined within the same directory or not.
import static <package>.<class>.*; import static <package>.<class>;
import static <package>.<class>.<field>; import static <package>.*;
The members of default packages are accessible only to classes or interfaces defined in the same
directory on your system.
The syntax to import static method() : import static <package>.<class>.method
Java modifiers
Access modifiers Package Classes Non-package Classes Nested Classes
public
protected if derived
default
private
Non-access modifiers Interface Class Variable Method
abstract redundant abstract/concrete no body
methods cant be static
final cannot be 1 assignement cannot be
extended possible overriden
static only nested common to all instances
access only static members
strictfp (none-abstract)
synchronized
native
transient
volatile (none- local)
protected and private are not valid modifiers for a class or interface definition.
A private method cannot be abstract A return type must be directly before the methods name.
Chapter 2 : Working with Java data types
Primitive data types
Primitive data types: char, byte, short, int, long, float, double, and boolean.
Primitive wrappers
PrimitiveWrapper.MIN_VALUE + 1 == PrimitiveWrapper.MAX_VALUE.
Two primitive wrappers are never compatible (ex : Integer & Long).
Primitive wrappers are immutable. When trying to modify a primitive wrapper value, a new instance is
created and the original instance remains unchanged.
A primitive wrapper constructors argument accepts only a compatible primitive value.
A primitive wrapper can be compared to a compatible primitive using the == operator.
A primitive wrappers constructor accepts either the primitive value or the String representation.
primitiveValue() returns the primitive value of the conversion of the selected wrapper.
static parsePrimitive(String) returns the primitive value of the String (if it is valid).
static decode(String) returns the primitive wrapper value of the String (if it is valid).
If a method is given a primitive argument and no method signature with a corresponding primitive type
was found. The primitive is boxed into a wrapper to find a corresponding object type parameter method.
Java reuses all wraper objects whose values are between -128 and 127.
To designate an integer literal value as a long value, add the suffix L or l to the literal value.
To designate a decimal literal value as a float 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 double value. Though its allowed,
doing so is not required because the default value of decimal literals is double.
Decimal types accept all integer types (including char). char accepts only litterals and char.
Integers accept char litterals depending on their capacity, but only int & long accepts a char
variable.
A method cant accept an argument that is a literral without casting it if the parameter is an integer
When you assign a letter to a char, Java stores its integer equivalent value. You may assign a positive
Operators
Precedence
Postfix a++, a--, [], .member, method(), 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
Objects lifecycle
Varargs : int... days : only one and the last one in parameters list.
If there is code that can be executed only after a return statement, the class will fail to compile.
Constructors of a class
Default constructors are defined by Java, but only if the developer doesnt define any constructor in a
class.
Constructors are NEVER inherited.
You can define a constructor using the four access modifiers: public, protected, default, and
private.
If you define a return type for a constructor, itll 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 thats
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 cant 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 try-catch-finally blocks.
Constructors cant 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 : static parent, static child, init
parent, constructor parent, init child, constructor child.
An initializer (or static) block is called when a member (non-constant) or a constructor declared in the
class (rather than inherited) is invoked, used or assigned. Its not called by only declaring a reference
variable.
It is an obligation to initialize a final instance variable either in a constructor or in an initializer block.
Unlike non-final instance variables, final instance variables must be initialized before use.
String objects created using the operator new are never placed in the pool of String objects.
if not overloaded the method toString()of any object returns : objects name + hashCode().
StringBuffer synchronized StringBuilder.
new char[5] ). But for objects its possible (Ex : Animal[] array = new Lion[10] ).
public static void arraycopy(Object src, int srcPos, Object dest, int
Unlike arrays, you dont have specify an initial size to create an ArrayList.
If you frequently add elements to an ArrayList, specifying a larger capacity will improve the code
efficiency.
ArrayList allows null values to be added to it.
To access the elements of an ArrayList, you can use either the enhanced for loop, Iterator, or
ListIterator :
ListIterator<String> iterator = myArrList.listIterator();
While(iterator.hasNext()) ...iterator.next()...
An iterator (Iterator or ListIterator) lets you remove elements as you iterate through an
ArrayList. Its not possible to remove elements from an ArrayList while iterating through it using a
for loop.
ArrayList has subclasses such as AttributeList, RoleList & RoleUnresolvedList.
A switch 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 for statementsinitialization statements, termination condition, and
update clauseis optional. For example, for (;;); and for (;;){} are valid code for defining a
for 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 for loop may contain only : increment/decrement expression, method invocation
The only valid modifier for the enhanced for loop iterator is final.
Labeled statements
You can add labels ( label: ) to a code block defined using braces, {}, all looping statements (for,
enhanced for loop, while, do-while), conditional constructs (if and switch statements),
expressions and assignments, return statements, try blocks, throws statements or method calls.
You cant add labels to declarations of variables.
If there is no brace { after the label. Only one expression is included in the labels area.
You can use a labeled break label; statement to exit an outer loop or any kind of block.
You can use a labeled continue label; statement to skip the iteration of the outer loop.
If not inside a loop, you cant use a break or a continue statement inside an if or else block.
break/continue label; must be used inside the block that label refers to.
Conditions
It is not a compilation error to put a false as a condition test in an if 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 interfaces variables are implicitly public, final & static. They should be assigned at
declaration. Its methods are implicitly public and they cant be final or static.
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 overriding method may declare only exceptions declared in the original method or its subclasses. It
Implementing two interfaces that have the same variable name X is no problem. Referring to X is a
compilation error.
An abstract method can override a concrete method.
Nested classes
Nested classes that are declared static are called static nested classes. Non-static nested classes are
called inner classes.
A nested class can be declared private, public, protected, or package private.
Static nested classes are accessed using the enclosing class name: OuterClass.StaticNestedClas
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:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
To access a shadowed variable x of the OuterClass in its InnerClass : OuterClass.this.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 java.lang.Throwable, initializes it with the necessary information and hands it over to the
JVM.
A finally block will execute even if a try or catch block defines a return statement.
If both catch and finally blocks define return statements, the calling method will receive the
by it. If a catch block returns an object, a finally block can modify the value being returned by it.
The finally block cant appear before a catch block.
Categories of exceptions
SecurityException
IllegalStateException
NullPointerException
IOException ClassCastException
java.lang.Exception
java.lang.RuntimeException
IllegalArgument NumberFormat
NoClassDefFoundError Exception Exception
java.lang.Throwable
AssertionError
ArrayIndex
java.lang.Error ExceptionInInitializerError OutOfBounds
IndexOutOf Exception
BoundsException
StackOverFlowError StringIndex
OutOfBounds
OutOfMemoryError
If a method calls another method that may throw a checked exception, either it must be enclosed within a
try-catch block or the method should declare this exception to be thrown in its method signature.
You can use the operator instanceof to verify whether an object can be cast to another class before
casting it.
Runtime exceptions arising from any of the following may throw ExceptionInInitializerError:
exception.
NoClassDefFoundError is thrown by the JVM or a ClassLoader when it is unable to load the
definition of a class required to create an object of the class.
Local variables cant be used without being initialized or assigned (compilation error if not guaranteed).
But fields (objects) and elements (arrays) are implicitly initialized to default values.
A NullPointerException will be thrown if the JVM finds a null exception in the catch header.