Java Notes
Java Notes
Java Notes
www.shareittips.com
OOPS
File
Object field;
C(@NonNull
Object p) {
field = p;
}
@NonNull
Object get() {
}
return field;
Comments
}
Error
History of Java
Classes - Classification
Encapsulation - maintainability, flexibility and extensibility.
Polymorphism – one method will behave differently.
Inheritance – Reusability, Easier updates, Do not break
what is already working.
Structure of JAVA Program
Package declaration;
Import statements
Class declaration
{
Variable declaration/ definition;
method declaration / definition;
}
Main method
class <classname>
{
public static void main(String[] args)
{
// Object instantiation
<classname> m = new <classname>();
}
}
CamelCase Convention
Variables - myVariable
Method - myMethod()
Class - MyClass
Package - mypackage
Constants - MYCONSTANT
Types of Variable
Note:
Local variables require explicit initialization.
Instance variables are initialized automatically.
Variable Initialization
Variable Value
byte 0
short 0
int 0
long 0L
float 0.0F
double 0.0D
char '\u0000'
boolean false
All reference types null
Constructor
It is a Spl. Method
Purpose: To initialize the class members
Features:
Same name as that of the class name
No return type including VOID
Can have access specifier
Can be overloaded
Constructors are NOT inherited
Invoked automatically whenever the object is
created.
The no. of time of invocation depends on no. of
object created
Arrays
int[] myArray;
• Constructing an array
<array name> =
new <element type> [<array size>];
Primitive array:
*****************
int[] myArray = { 1 , 2 , 3 , 4 , 5 } ;
Reference Array:
********************
Object[] objArr = { new Pizza(), new Pizza(), null };
Initializing an Array
class Car
{
}
class BMW extends Car => IS-A R/S
{
boolean auto_gear = “true” => Has-A R/S
}
Polymorphism
Function Overloading
Constructor Overloading
NO operator Overloading in Java
Rules :
No. of parameter should change
Datatype of the parameter should change
Sequence of passing the paramter should change.
Overriding
The overridden method in the superclass is NOT inherited by the
subclass, and the new method in the subclass must uphold the
following rules of method overriding:
The new method definition must have the same method
signature (i.e., method name and parameters) and the same
return type.
Overridden Methods Cannot Be Less Accessible.
A subclass cannot override fields of the superclass, but it can
hide them.
Works only with inheritance.
Constructors cant be Overridden.
Super keyword is used to invoke an overridden method in the
superclass.
this() and super() call for
constructor
this() construct is used to implement local chaining of
constructors in the class when an instance of the class is
created.
The this() call invokes the constructor with the
corresponding parameter list.
super() method is used to invoke the IMMEDIATE base
class constructor. This allows the subclass to influence the
initialization of its inherited state when an object of the
subclass is created.
this() and super() call must occur as the first statement in
a constructor.
Example : this() and super()
class GParent
{
int a,b,c;
GParent() {
System.out.println("From gparent");
}
GParent(int a,int b) {
//this(a,b,100);
this();
System.out.println("a= "+a+" b = "+ b);
}
Parent(int x,int y)
{
super(x,y);
this.x=x;
this.y = y;
System.out.println("x= "+x+" y = "+ y);
}
Example : this() and super()
}
class SuperEx
{
public static void main(String[] a)
{
//Parent p = new Parent(12,23);
Child d = new Child();
}
instanceof operator
class StatEx1
{
static int counter;
//static initializer
static
{
counter=10;
System.out.println("Static block invoked
"+counter);
}
public static void sMethod()
{
System.out.println("Static method" +
counter++);
}
Static Initializer Example
class StatEx
{
public static void main(String arg[])
{
System.out.println("from main");
StatEx1.sMethod();
StatEx1.sMethod();
}
}
Final Keyword
Note:
All final variable need Explicit initialization
Wrapper Class
int x=10;
Integer n = new Integer(x); //Boxing
int y = n.intValue(); //UnBoxing
AutoBoxing and
AutoUnboxing
Example:
int x=10;
Integer n = x; //AutoBoxing
int y = n; //AutoUnBoxing
Methods to Extract the
Wrapped Values
Method Class
Primitive xxxValue()
To convert Wrapper to primitive
• Primitive parseXxx(String)
To convert a String to a primitive
• Wrapper valueOf(String)
To convert a String to a Wrapper
Object Class
enum Edge
{
TOP,BOTTOM,LEFT,RIGHT
};
class MyClass
{
public static void main(String[] a)
{
Edge e = Edge.TOP;
int i = e.ordinal();
System.out.println(e);
System.out.println(i);
}
}
Enum Example2
enum Edge
{
TOP,BOTTOM,LEFT,RIGHT;
MONDAY(8,true),
TUESDAY(8,true),
WEDNESDAY(8,true),
THURSDAY(8,true),
FRIDAY(8,true),
SATURDAY(4,false),
SUNDAY(0,false);
}
Inner Class
A class that is declared within another class or
interface, is called a nested class.
There are four categories of nested classes
Regular class - class within the class
Method-local class – class within the method of
the outer class
Static nested class - inner classes marked with
the static modifier (top-level nested class)
Anonymous class - part of a method argument.
All inner classes are nested classes, but not all
nested classes are inner classes.
Example for Regular
InnerClass
class MyOuter
{
int x =7;
class MyInner
{
public void InnerMethod()
{
System.out.println("x == " + x);
}
}
public void OuterMethod()
{
MyInner inn = new MyInner();
inn.InnerMethod();
}
Example for Regular
InnerClass
public static void main(String[] a)
{
MyOuter mo = new MyOuter();
MyOuter.MyInner mi = mo.new MyInner();
mi.InnerMethod();
mo.OuterMethod();
//mi.OuterMethod(); illegal
//mo.InnerMethod(); illegal
}
Method-local inner class
class OuterClass
{
static int i =10;
public void method()
{
System.out.println("i == " + ++i);
}
static class InnerClass
{
public void display()
{
System.out.println("i == " + i);
}
}
Static nested class
Throwable
Exception Error
Others…
Exception-handling
mechanism
Contains five keywords:
try - catch – throw - throws – finally
Method throws ExceptionName{
try{
--risky code goes here
}catch(ExceptionClassName ObjectName){
-- Exception handler block code
throw Exception_Instance //Ducking it
}
finally{
-- cleanup your code goes here
}
}
About try-catch-finally
A try block should be followed by at least one catch block.
The code inside try block is called as protected code.
Can have one or more catch block.
If you have multiple catch block, make sure that the last
catch block contain the super most class in the hierarchy.
You may also write an optional “finally” block. This block
contains code that is ALWAYS executed, either after the “try”
block code, or after the “catch” block code.
The catch block may or may not contain throw keyword.
The try block can also be nested.
Example 1
class PrintStack
{
public static void main(String args[])
{
int Num1= 30 , Num2 = 0;
try
{
int Num3=Num1/Num2;
}
catch(ArithmeticException obj)
{
System.out.println("Exception"+obj);
obj.printStackTrace();
}
}
}
Rules in Exception
class UncheckedThrows
{
public void show() throws ArithmeticException
{
System.out.println("Hai I am not handled");
}
v No exceptions
v One or more of the exceptions thrown by
the
overridden method.
v One or more subclasses of the exceptions
thrown by the overridden method.
v The overriding method cannot throw:
v Additional exceptions not thrown by the
overridden method.
v Super classes of the exceptions thrown by
the overridden method
User Defined Exception
class UserExceptions
{
public void valid()
{
try
{
String str1,str2;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Login id");
str1=br.readLine();
System.out.println("Enter password");
str2=br.readLine();
if(str1.equals(str2))
System.out.println("Hai welcome");
else
throw new MyException();
}
Example 2 cont …
catch(MyException e)
{
System.out.println("Sorry U r not a valid user" + e);
valid();
}
catch(IOException ioe){}
}
}
String Class Facts
word “java"
“Java"
Empty Strings
television television
i k i
Methods in String Clas
indexOf() => returns the index position of the
character.
equals()
equalsIgnoreCase()
compareTo()
compareToIgnoreCase()
trim()
replace()
toUpperCase()
toLowerCase()
StringBuffer Class
import java.util.*;
class ListExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add("one");
list.add("second");
list.add("3rd");
list.add(new Integer(4));
list.add(new Float(5.0F));
list.add("second"); // duplicate, is added
list.add(new Integer(4)); // duplicate, is
added
System.out.println(list);
}
}
Set
import java.util.*;
class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
set.add("one");
set.add("second");
set.add("3rd");
set.add(new Integer(4));
set.add(new Float(5.0F));
set.add("second"); // duplicate, not
added
set.add(new Integer(4)); // duplicate, not
added
System.out.println(set);
}
}
Collection API - Storage
The storage associated with any one collection can be
implemented in many ways, but the Collections API
implements the four methods that are most widely used:
Array: supports insertion, deletion, but growing the store
is more difficult.
ArrayList: grow in number of elements. Search is faster.
But not insertion and deletion. Vector(provides
synchronization)
Linked list: supports insertion, deletion, and growing the
store, but makes indexed access slower. Use when
insertions and deletions happen frequently.
Tree: supports insertion, deletion, and growing the list.
Indexed access is slow, but searching is faster.
Hash table: supports insertion, deletion, and growing the
store. Indexed access is slow, but searching is
particularly fast. However, hashing requires the use of
unique keys for storing data elements.
Set Classes
HashSet :
provides the faster access to a data item.
no guarantee that the items will be ordered.
does not offer synchronization.
Tree Set:
presents sorted data items.
performance is not as good as HashSet.
does not offer synchronization.
LinkedHashSet:
Similar to HashSet that maintains a doubly linked list.
It is an ordered collection, ordered by insertion, but not
sorted.
does not offer synchronization
Map Classes
HashTable:
implementation is based on the hashtable data structure.
No ordering.
implementation is synchronized
HashMap:
based on the hashtable data structure.
No ordering
allows null and is unsynchronized
LinkedHashMap:
maintains a doubly linked list.
TreeMap:
implements the SortedMap interface
Sorted and unsynchronized.
Class Interface Duplicates Ordered/ Synchronized
Allowed? Sorted
THREAD
STACK
SHARED
MEMOR
Y
THREAD
DATA
THREAD
TEXT
Why priorities?
Determine which thread receives CPU control
and gets to be executed first
Definition:
– Integer value ranging from 1 to 10
– Higher the thread priority → larger chance of
being executed first
– Example:
● Two threads are ready to run
● First thread: priority of 5, already running
● Second thread = priority of 10, comes in while first
thread is running
Thread Synchronization
● }
Wait() and notify()
output - stream
Program Device
input - stream
Program Device
keyboard
standard
input
stream
CPU
standar
doutput MEM
stream
monitor
terminal
console
HDD
How does information
travel across?
Streams
keyboard
standard
input
stream
CPU
standar
doutput MEM
stream
monitor
terminal
console file
input
strea
m
LOAD HDD
How does READ
information travel file
across? files outpu
Streams t
strea
m
SAVE
IOStreams
pro con
If an object is to be serialized:
The class must be declared as public
The class must implement Serializable
The class must have a no-argument constructor
All fields of the class must be serializable: either
primitive types or serializable objects
The Serializable interface does not define any methods!
Question: What possible use is there for an interface that does not
declare any methods?
Answer: Serializable is used as flag to tell Java it needs to do
extra work with this class
Object Serialization (cont’d)
● Fourth level
● Fifth level
Memory heap
When new keyword is called memory is allocated in the
heap and returned when the reference is made null
Stack
During method calls, objects are created for method
arguments and method variables. These objects are created
on stack.
Such objects are eligible for garbage-collection when they
go out of scope.
Garbage Collection
Finalize()
Class Object has a finalize() method.
Before gc happens the finalize() method is called
It is called only once
Finalize method can be overridden by the user.
Finalize can be used to make an object not to be garbage
collected
Classical Algorithms
@NonNull
Object get() {
return field;
}
}
Program
with
annotations Error Error
Annotation
Checker
Plugins
Annotation Types
Marker
Single-Element
Full-value or multi-value
Marker
Usage:
@MyAnnotation
public void mymethod() {
....
}
Single-Element
Example:
● public @interface MyAnnotation {
● String doSomething();
● }
Usage:
● @MyAnnotation ("What to do")
● public void mymethod() {
● ....
● }
Full-value or multi-value
Full-value type annotations have multiple data members.
Example:
public @interface MyAnnotation {
String doSomething();
int count;
String date();
}
Usage:
@MyAnnotation (doSomething=
"What to do",
count=1,
date="09-09-2005")
public void mymethod() {
....
}
The Built-In Annotations
@Target(ElementType.TYPE)
can be applied to any element of a class
@Target(ElementType.FIELD)
can be applied to a field or property
@Target(ElementType.METHOD)
can be applied to a method level annotation
@Target(ElementType.PARAMETER)
can be applied to the parameters of a method
@Target(ElementType.CONSTRUCTOR)
can be applied to constructors
@Target(ElementType.LOCAL_VARIABLE)
can be applied to local variables
@Target(ElementType.ANNOTATION_TYPE)
indicates that the declared type itself is a
Reflection
When we have some Annotations defined in the
source code and have a mechanism through
which we can say that to what extent the
Annotations should be retained. The three
possible ways of telling this are,
Retain the Annotation in the Source Code only
Retain the Annotation in the Class file also.
Retain the Annotation Definition during the Run-
time so that JVM can make use of it.
The Annotation that is used to achieve this is
@Retention and it takes a possible values of
SOURCE, CLASS and RUNTIME defined in
RetentionPolicy Enumeration.
Need of Annotation
Less coding
Easier to change
Smarter development.
Providing information to the Compiler.
Providing information to the tools.
Providing information to the Runtime System
www.shareittips.com
www.bcahub.shareittips.com