Java Programming Fundamentals
Java Programming Fundamentals
2013-14
Declaration &
Initialization
Arrays
<elementType>[] <arrayName>;
int [] a;
<elementType> <arrayName>[];
int a [];
<arrayName>=new <elementType>[arraySize];
a=new int[10];
final classes
final class BaseClass{}
// Error - The type DerivedClass cannot subclass the final
class BaseClass
public class DerivedClass extends BaseClass{
}
Garbage Collection
Garbage Collection
GC Phases
Mark Phase
Marks the live objects in the heap. Typically most of the GC
time is spent here.
Sweep Phase
Performs the actual garbage removal.
Compaction Phase
Compacts the heap to provide larger contiguous storage
areas.
GC Overview
GC manages the java Heap (default 512 MB)
GC only executes
When objects cannot be allocated with in the heap.
Requested via System.gc() call.
static variable
It is a variable which belongs to the class and not to
object(instance)
Static variables are initialized only once , at the start of
the execution . These variables will be initialized first,
before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class
name and doesnt need any object
Syntax : <class-name>.<variable-name>
static method
It is a method which belongs to the class and not to the
object(instance)
A static method can access only static data. It can not access
non-static data (instance variables)
A static method can call only other static methods and can not
call a non-static method from it.
A static method can be accessed directly by the class name and
doesnt need any object
Syntax : <class-name>.<method-name>
A static method cannot refer to this or super keywords in
anyway
static block
The static block, is a block of statement inside a Java class
that will be executed when the class is loaded into memory
by Class Loader of Java Virtual Machine.
class Test{
static {
//Code goes here
}
}
Class Loader
Every JVM has a built-in class loader (of type java.lang.ClassLoader) that is
responsible for loading classes into the memory of a Java program. Whenever a
class is referenced in the program, the class loader searches the classpath for
the class file, loads the bytecode into memory, and instantiates a
java.lang.Class object to maintain the loaded class.
The class loader loads a class only once, so there is only one java.lang.Class
object for each class that used in the program. This Class object stores the static
variables and methods.
During the class loading, the class loader also allocates the static variables, and
invokes the explicit initializers and static initializers (in the order of appearance).
Instantiation Process
The sequence of events when a new object is instantiated via the new
operator (known as the instantiation process) is as follows:
JVM allocates memory for the instance in the help.
JVM initializes the instance variables to their assigned values or default
values.
JVM invokes the constructor.
The first statement of the constructor is always a call to its immediate
superclass' constructor. JVM invokes the selected superclass' constructor.
JVM executes the instance initializers in the order of appearance.
JVM executes the body of the constructor.
The new operator returns a reference to the new object.
method call
Constructor
A constructor is different from an ordinary method in the following aspects:
The name of the constructor method is the same as the class name, and by class
name convention, begins with an uppercase.
Constructor has no return type (or implicitly returns void). Hence, no return statement
is allowed inside the constructor's body.
Constructor can only be invoked via the "new" operator. It can only be used once to
initialize the instance constructed.
You cannot call the constructor afterwards.
Constructors are not inherited (to be explained later).
A constructor with no parameter is called the default constructor, which initializes the
member variables to their default value.
Method overloading
Method overloading means that the same method name
can
have
different
implementations
(versions).
However, the different implementations must be
distinguishable by their argument list (either the
number of arguments, or the type of arguments, or their
order).
toString()
Every class should have a public method called toString() that returns a string description
of the object.
You can invoke the toString() method explicitly by calling an InstanceName.toString() or
implicitly via println() or String concatenation operator '+'.
Running println(anInstance) with an object argument invokes the toString() method of that
instance implicitly.
When you work with a primitive data type, such as an integer, you are working directly with values and no
Java object is involved. So the statement x = y actually copies the value of y into x.
When you work with reference types (objects), the variable does not contain the object. The variable is a
reference to that object in memory.
So the statement x = y does not copy the object, but only copies the reference. There is still only one object,
but it now has two references.
OOP
In OOP, we often organize classes in hierarchy to avoid
duplication and reduce redundancy. The classes in the lower
hierarchy inherit all the variables (static attributes) and methods
(dynamic behaviors) from the higher hierarchies. A class in the
lower hierarchy is called a subclass (or derived, child, extended
class). A class in the upper hierarchy is called a superclass (or
base, parent class). By pulling out all the common variables and
methods into the superclasses, and leave the specialized
variables and methods in the subclasses, redundancy can be
greatly reduced or eliminated as these common variables and
methods do not need to be repeated in all the subclasses.
Inheritance
instanceof
Java provides a binary operator called instanceof which
returns true if an object is an instance of a particular
class. The syntax is as follows:
anObject instanceof aClass
An instance of subclass is also an instance of its
superclass.
Method overriding
super
Recall that inside a class definition, you can use the keyword this to refer to this instance.
Similarly, the keyword super refers to the superclass, which could be the immediate parent or
its ancestor.
The keyword super allows the subclass to access superclass' methods and variables within the
subclass' definition. For example, super() and super(argumentList) can be used invoke the
superclass constructor. If the subclass overrides a method inherited from its superclass, says
getArea(), you can use super.getArea() to invoke the superclass' version within the subclass
definition. Similarly, if your subclass hides one of the superclass' variable, you can use
super.variableName to refer to the hidden variable within the subclass definition.
In the body of a constructor, you can use super(args) to invoke a constructor of its immediate
superclass. Note that super(args), if it is used, must be the first statement in the subclass'
constructor. If it is not used in the constructor, Java compiler automatically insert a super()
statement to invoke the no-arg constructor of its immediate superclass. This follows the fact
that the parent must be born before the child can be born. You need to properly construct the
superclasses before you can construct the subclass.
If the immediate superclass does not have the default constructor (it defines some constructors
but does not define a no-arg constructor), you will get a compilation error in doing a super() call.
Object class
The Object class, defined in the java.lang package, defines and implements behavior
common to all classesincluding the ones that you write. In the Java platform, many
classes derive directly from Object, other classes derive from some of those classes,
and so on, forming a hierarchy of classes. These common behaviors enable the
implementation of features such as multi-threading and garbage collectors.
finalize()
finalize() is called before Garbage collector reclaim the Object, its last chance for any object to perform cleanup
activity i.e. releasing any system resources held, closing connection if open etc.
Main issue with finalize method in java is its not guaranteed by JLS that it will be called by Garbage collector or
exactly when it will be called, for example an object may wait indefinitely after becoming eligible for garbage
collection and before its finalize() method gets called.
Similarly even after finalize gets called its not guaranteed it will be immediately collected.
Because of above reason it make no sense to use finalize method for releasing critical resources or perform any
time critical activity inside finalize
finalize method is called by garbage collection thread before collecting object and it is not intended to be called
like normal method.
There is one way you can guarantee running of finalize method by calling System.runFinalization() and
Runtime.getRuntime().runFinalization(). These methods ensures that JVM call finalize() method of all object
which are eligible for garbage collection and whose finalize has not yet called.
Any Exception thrown by finalize method is ignored by GC thread and it will not be propagated further, in fact I
doubt if you find any trace of it.
finalize()
One of the most important point of finalize method is
that its not automatically chained like constructors. If you
are overriding finalize method then its your responsibility
to call finalize() method of super-class, if you forgot to
call then finalize of super class will never be called.
Best way to call super class finalize method is to call
them in finally block as shown in below example. this will
guarantee that finalize of parent class will be called in all
condition except when JVM exits
Upcasting
Substituting a subclass instance for its superclass is
called "upcasting". This is because, in a UML class
diagram, subclass is often drawn below its superclass.
Upcasting is always safe because a subclass instance
possesses all the properties of its superclass and can do
whatever its superclass can do. The compiler checks for
valid upcasting and issues error "incompatible types"
Circle c1 = new Cylinder(); // Compiler checks to ensure that R-value is a
otherwise.
subclass of L-value.
Circle c2 = new String();
Downcasting
Substituting a subclass instance for its superclass is called "upcasting". You can
revert a substituted instance back to a subclass reference. This is called
"downcasting".
Downcasting requires explicit type casting operator in the form of prefix operator
(new-type). Downcasting is not always safe, and throws a runtime
ClassCastException if the instance to be downcasted does not belong to the
correct subclass. A subclass object can be substituted for its superclass, but the
reverse is not true. Compiler may not be able to detect error in explicit cast,
which will be detected only at runtime.
Circle c1 = new Cylinder(5.0);
// upcast is safe
Cylinder aCylinder = (Cylinder) c1; // downcast needs the casting operator
Circle c1 = new Circle(5); Point p1 = new Point(); c1 = p1; // compilation error: incompatible
types (Point is not a subclass of Circle) c1 = (Circle)p1; // runtime error:
java.lang.ClassCastException: Point cannot be casted to Circle
Why interfaces?
An interface is a contract (or a protocol, or a common understanding) of what the classes can
do. When a class implements a certain interface, it promises to provide implementation to all the abstract
methods declared in the interface. Interface defines a set of common behaviors. The classes implement
the interface agree to these behaviors and provide their own implementation to the behaviors. This allows
you to program at the interface, instead of the actual implementation. One of the main usage of interface
is provide a communication contract between two objects. If you know a class implements an interface,
then you know that class contains concrete implementations of the methods declared in that interface, and
you are guaranteed to be able to invoke these methods safely. In other words, two objects can
communicate based on the contract defined in the interface, instead of their specific implementation.
Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance
permits you to derive a subclass from more than one direct superclass. This poses a problem if two direct
superclasses have conflicting implementations. (Which one to follow in the subclass?). However, multiple
inheritance does have its place. Java does this by permitting you to "implements" more than one interfaces
(but you can only "extends" from a single superclass). Since interfaces contain only abstract methods
without actual implementation, no conflict can arise among the multiple interfaces. (Interface can hold
constants but is not recommended. If a subclass implements two interfaces with conflicting constants, the
compiler will flag out a compilation error.)
interface
A Java interface is a 100% abstract superclass which define a set of
methods its subclasses must support. An interface contains only public
abstract methods (methods with signature and no implementation) and possibly
constants (public static final variables). You have to use the keyword "interface" to
define an interface (instead of keyword "class" for normal classes). The keyword
public and abstract are not needed for its abstract methods as they are mandatory.
An interface is a contract for what the classes can do. It, however, does not specify
how the classes should do it.
An interface that have no member is known as marker or tagged interface. For
example: Serializable, Cloneable, Remote etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful operation.
interface
An interface is similar to a class in the following ways:
An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
interface
However, an interface is different from a class in several ways, including:
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
interface
When overriding methods defined in interfaces there are several rules to be
followed:
Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
interface
To implement interfaces there are several rules:
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
implements
A file of Java source code has the extension .java. It consists of an optional package statement
followed by any number of import statements followed by one or more class or interface
definitions. (The package and import statements will be introduced shortly.) If more than one class
or interface is defined in a Java source file, only one of them may be declared public (i.e., made
available outside of the package), and the source file must have the same name as that public
class or interface, plus the .java extension.
Each class or interface definition in a .java file is compiled into a separate file. These files of
compiled Java byte-codes are known as "class files," and must have the same name as the class or
interface they define, with the extension .class appended. For example, the class SoundEffects
would be stored in the file SoundEffects.class.
Class files are stored in a directory that has the same components as the package name. If the
fully qualified name of a class is david.games.tetris.SoundEffects, for example, the full path of the
class file must be david/games/tetris/SoundEffects.class. This filename is interpreted relative to
the Java "class path," described below
Package
A package is a collection of related Java entities (such as classes, interfaces, exceptions, errors and
enums). Packages are used for:
Resolving naming conflict of classes by prefixing the class name with a package name.
For example, com.zzz.Circle and com.yyy.Circle are two distinct classes. Although they share the same class name
Circle, but they belong to two different packages: com.zzz and com.yyy. These two classes can be used in the same
program and distinguished using the fully-qualified class name - package name plus class name. This mechanism is
called Namespace Management.
Access Control: Besides public and private, Java has two access control modifiers protected and
default that are related to package. A protected entity is accessible by classes in the same package
and its subclasses. An entity without access control modifier (i.e., default) is accessible by classes in
the same package only.
For distributing a collection of reusable classes, usually in a format known as Java Archive (JAR) file.
The prefix "java" and "javax" are reserved for core Java
packages and Java extensions, respectively.
The base directory ($BASE_DIR) could be located anywhere in the file system. Hence,
the Java compiler and runtime must be informed about the location of the $BASE_DIR
so as to locate the classes. This is accomplished by an environment variable called
CLASSPATH. CLASSPATH is similar to another environment variable PATH, which is used
by the command shell to search for the executable programs.
Creating Packages
To make a class as part of a package, you have to
include the package statement as the first statement in
the source file.
It is a good practice to store the source codes and the
classes in separate directories, to facilitate the
distribution of classes without the source codes.
Package
// d:\myJavaProject\src\com\yyy\Circle.java
package com.yyy;
Package
d:\myOtherProject> javac TestCircle.java
package com.yyy does not exist
// d:\myOtherProject\TestCircle.javaTestCircle.java:1:
import com.yyy.Circle;
^
import com.yyy.Circle;
We need to use the -cp (or -classpath) option to specify
the base directory of the package com.yyy, in order to
public class TestCircle {
locate com.yyy.Circle.
public static void main(String[] args)
{
d:\myOtherProject>
javac -cp d:\myJavaProject\classes
TestCircle.java
}
}
java.lang.NoClassDefFoundError: TestCircle
But now, the JRE can't even find the TestCircle class,
which is located in the current directory. This is because if
CLASSPATH is not explicitly set, it defaulted to the current
directory. However, if CLASSPATH is explicitly set, it does
not include the current directory unless the current
directory is included. Hence, we need to include current
directory (denoted as '.') in the CLASSPATH, together with
......
}
package com.zzz.project1.subproject2;
public class MyClass3 {
private MyClass4 myClass4;
public MyClass3 () { // constructor
System.out.println("MyClass3 constructed");
myClass4 = new MyClass4(); // use
MyClass4 in the same package
}
// main() included here for testing
public static void main(String[] args) {
new MyClass3();
}
}
Inner Class
Inner classes are class within Class. Inner class instance has
special relationship with Outer class. This special relationship
gives inner class access to member of outer class as if they
are the part of outer class. Inner class instance has access to
all member of the outer class(Public, Private & Protected).
Types of Inner Classes
Static
Method Local
Anonymous
Member class
From Outside Outer Class, Create outer class instance and then inner
class instance.
// Creating outer class instance
OuterClass outerclass = new OuterClass();
// Creating inner class instance
OuterClass.InnerClass innerclass = outerclass.new InnerClass();
OR
OuterClass.InnerClass innerClass = new OuterClass.new InnerClass();
In case of Inner class this keyword will refer the currently executing
inner class Object. But to get this for outer class use OuterClass.this.
Modifiers applied
Normal inner class will be treated like member of the
outer class so it can have several Modifiers as opposed
to Class.
final
abstract
public
private
protected
strictfp
Here, SuperClass is not the name of the class being defined, but
rather the name of the class being extended. The parameters are the
parameters to the constructor for that superclass.
An anonymous inner class may implement an interface:
new Interface(){ class body }
enum
Enums are type-safe!
Enums provide their namespace.
Whenever an enum is defined, a class that extends java.lang.Enum is created. Hence, enum
cannot extend another class or enum. The compiler also create an instance of the class for
each constants defined inside the enum. The java.lang.Enum has these methods:
public final String name();
// Returns the name of this enum constant, exactly as declared in its enum declaration.
// You could also override the toString() to provide a more userfriendly description.
public String toString(); // Returns the name of this enum constant, as contained in the
declaration.
// This method may be overridden.
public final int ordinal();
// Returns the ordinal of this enumeration constant.
All constants defined in an enum are public static final. Since they are static, they can be
accessed via EnumName.instanceName.
You do not instantiate an enum, but rely the constants defined.
Enums can be used in a switch-case statement, just like an int.
Wrapper classes
The designers of Java language retain the primitive types in
an object-oriented language, instead of making everything
object, so as to improve the runtime performance.
However, in some situations, an object is required instead of a
primitive value.
The data structures in the Collection framework, such as
the "dynamic array" ArrayList and Vector, stores only
objects (reference types) and not primitive types.
Object is needed to support synchronization in
multithreading.
Objects are needed, if you wish to modify the arguments
passed into a method (because primitive types are passed
by value).
JDK provides the so-called wrapper classes that wrap primitive
values into objects, for each primitive type as shown in the
class diagram. Each of the wrapper classes contains a private
member variable that holds the primitive value it wraps. The
wrapped value cannot be changed.
Number class
The following methods are declared in Number class, which are
implemented in concrete subclasses Byte, Short, Integer, Long,
Float, Double.
public
public
public
public
public
public
public
public
byte byteValue()
short
shortValue()
abstract int intValue()
abstract long longValue()
abstract float floatValue()
abstract double doubleValue()
char charValue()
boolean
booleanValue()
Exception Handling
Older programming languages such as C have some drawbacks in exception handing.
For example, suppose the programmer wishes to open a file for processing:
The programmers are not made to be aware of the exceptional conditions. For
example, the file to be opened may not necessarily exist. The programmer therefore
did not write codes to test whether the file exists before opening the file.
Suppose the programmer is aware of the exceptional conditions, he/she might decide
to finish the main logic first, and write the exception handling codes later this
"later", unfortunately, usually never happens. In other words, you are not force to
write the exception handling codes together with the main logic.
Suppose the programmer decided to write the exception handling codes, the
exception handling codes intertwine with the main logic in many if-else statements.
This makes main logic hard to follow and the entire program hard to read. For
example,
Exception Handling
Java overcomes these drawbacks by building the
exception handling into the language rather than
leaving it to the discretion of the programmers:
You will be informed of the exceptional conditions that
may arise in calling a method - Exceptions are declared
in the method's signature.
You are forced to handle exceptions while writing the
main logic and cannot leave them as an afterthought Your program cannot compiled without the exception
handling codes.
Exception propagation
When an exception occurs inside a Java method,
the method creates an Exception object and
passes the Exception object to the JVM (in Java
term, the method "throw" an Exception).
The Exception object contains the type of the
exception, and the state of the program when
the exception occurs.
The JVM is responsible for finding an exception
handler to process the Exception object.
It searches backward through the call stack until
it finds a matching exception handler for that
particular class of Exception object (in Java term,
it is called "catch" the Exception).
If the JVM cannot find a matching exception
handler in all the methods in the call stack, it
terminates the program.
assert
Assertion enables you to test your assumptions about your program
logic (such as pre-conditions, post-conditions, and invariants).
The assert statement has two forms:
assert booleanExpr;
assert booleanExpr : errorMessageExpr;
String class
String s1 = "Hello";
String s2 = "Hello";
String s3 = s1;
String s4 = new
String("Hello");
String s5 = new
String("Hello");
s1 == s1;
s1 == s2;
s1 == s3;
s1.equals(s3);
s1 == s4;
s1.equals(s4);
s4 == s5;
State
Description
State
Description
Ready The thread is ready to run and
waiting for the CPU.
Ready The
thread
is ready
to run and
waiting
Running
The
thread
is executing
on the
CPU. for the CPU.
Running
The thread
is executing
the CPU.
Waiting
The thread
is waiting
for someonevent
to happen.
Waiting
The
thread
is
waiting
for
some
event
to happen.
Sleeping
The thread has been told to sleep for
a time.
Sleeping
The
thread
has
been
told
to
sleep
for
a time.
BlockedThe thread is waiting for I/O to finish.
BlockedThe
threadisisterminated.
waiting for I/O to finish.
Dead
The thread
Dead The thread is terminated.
Defau Size(bits
Type Description
lt
)
Min/Max
boole
an
true/false
false
char
Unicode
character
\u0000
16
byte
Signed
integer
short
Signed
integer
16
-32768
32767
int
Signed
integer
32
-2147483648
2147483647
long
Signed
integer
64
-9223372036854775808
9223372036854775807
float
IEEE 754
Floating point
0.0
32
+/- 1.40239846E-45
+/- 3.40282347E+38
doubl
e
IEEE 754
floating point
0.0
64
Not applicable
\u0000
\uFFFF
-128
127
+/4.94065645841246544E324
+/1.79769313486231570E-
Asso
c.
Description
++
-+
~
!
(type)
Arithmetic
Arithmetic
Arithmetic
Integral
Boolean
Any
Right
Right
Right
Right
Right
Right
Unary
Unary
Unary
Unary
Unary
cast
Arithmetic
Left
+
+
Arithmetic
String
Left
Left
<<
>>
>>>
Integral
Integral
Integral
Left
Left
Left
Left shift
Right shift with sign extension
Right shift with zero extension
<
<=
>
>=
instanceof
Arithmetic
Arithmetic
Object,
Left
Left
Left
pre/post decrement
pre/post decrement
plus and minus
bitwise complement
logical complement
Precede
nce
Java Operator
Operands
Asso
c.
Description
==
!=
==
!=
Primitive
Primitive
Object
Object
Left
Left
Left
Left
&
&
Integral
Boolean
Left
Left
Bitwise AND
Boolean AND
^
^
Integral
Boolean
Left
Left
Bitwise XOR
Boolean XOR
|
|
Integral
Boolean
Left
Left
Bitwise OR
Boolean OR
10
&&
Boolean
Left
Conditional AND
11
||
Boolean
Left
Conditional OR
12
?:
Conditional ternary
13
=
*=
Variable, any
Variable, any
Assignment
Assignment with
/=
%/
+=
-=
<<=
>>=
Righ
t
Inner Classes
This features lets you define a class as part of another class, just as fields
and methods are defined within classes. Java defines four types of inner
classes.
A nested top-level class or interface is a static member of an enclosing
top-level class or interface.
A member class is a nonstatic inner class. As a full-fledged member of
its containing class, a member class can refer to the fields and methods of
the containing class, even the private fields and methods. Just as you would
expect for the other instance fields and methods of a class, all instances of a
member class are associated with an instance of the enclosing class.
A local class is an inner class defined within a block of Java code, such
as within a method or within the body of a loop. Local classes have local
scope they can only be used within the block in which they are defined. Local
classes can refer to the methods and variables of their enclosing classes.
They are used mostly to implement adapters, which are used to handle
events.
An anonymous class is a local class whose definition and use are
When Java compiles a file containing a named inner class, it creates separate
class files for them with names that include the nesting class as a qualifier.
For example, if you define an inner class named Metric inside a top-level
class named Converter, the compiler will create a class file named
Converter$Metric.class for the inner class. If you wanted to access the inner
class from some other class (besides Converter), you would use a qualified
name: Converter.Metric.
An
anonymous
class
ConverterFrame$1.class.
bytecode
files
are
given
names
like
Dynamic Polymorphism
If a base class reference is used to call a method, the
method to be invoked is decided by the JVM, depending
on the object the reference is pointing to.
The keyword super can be used to access any data
member or methods of the super class in the sub class.