100 Minute Java
100 Minute Java
History of Java
Features of Java
Java Bytecode
Things you should know...
Naming conventions
FirstProgram.c
FirstProgram.obj
FirstProgram.exe
Execution cycle of Java Program
class FirstProgram
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Go to Command Prompt :
To compile the Java Program -
javac <FileName with Extension>
e.g:- javac FirstProgram.java
/**
* This is JavaDoc comment.
*/
These comments are used for documentation purpose.
Keywords in Java
class Foo
{
public int break(int b)
{
// code that appears to break something
}
}
Ranges of Primitive Data Type
int x =1;
while (x) { } // Won’t compile; x is not a boolean
while (x = 5) { }
//Won’t compile; resolves to 5 (result of assignment)
while (x == 5) { } // Legal, equality test
while (true) { } //Legal
Remember, characters are just 16-bit unsigned integers under the
hood. That means you can assign a number literal, assuming it will
fit into the unsigned 16-bit range (65535 or less).
For example, the following are all legal:
char a = 0x892; // octal literal
char b = 982; // int literal
char c = (char) 70000; // The cast is required; 70000 is out of
char range
And the following are not legal and produce compiler errors:
char e = -29; // Possible loss of precision; needs a cast
char f = 70000 // Possible loss of precision; needs a cast
Command Line Arguments
class TestMain
{
public static void main (String [] args)
{
System.out.println("First arg is :" + args[0]);
}
}
int str = 2;
String i = “Hello”;
System.out.println(str);
System.out.println(i);
Arithmetic Operators
Operator Description
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment (pre – post)
-- Decrement (pre - post)
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulus Assignment
Bitwise Operators
Operator Description
~ Unary NOT
& AND
| OR
^ X-OR
>> Right Shift
>>> Right Shift Zero fill
<< Left Shift
&= AND assignment
|= OR assignment
^= X-OR assignment
>>= Right Shift assignment
>>>= Right Shift Zero fill assignment
<<= Left Shift assignment
Relational Operators
Operator Description
== Equal to (Equality)
!= Not Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Boolean Logical Operators
Operator Description
& Logical AND
| Logical OR
^ Logical X-OR
|| Short-circuit OR
&& Short-circuit AND
! Logical NOT
?: Ternary
Coffee Cram
• Can we have different Java Source file name and Class Name ?
If yes, then how to compile and run the program?
byte b1 = 2;
byte b2 = 3;
byte b3 = b1+b2;
System.out.println(b3);
byte b1 = 2;
byte b2 = 3;
b1+=b2;
System.out.println(b1);
Widening and Narrowing Conversions
The compiler won’t let you put a value from a large cup into
a small one.
• With abstraction you can drive the car ignoring the details
of how the engine, transmission and braking system works.
Instead you are free to use the ‘Car’ object as a whole.
1. Encapsulation
Bike Scooter
Has – A relationship
4. Polymorphism
Move ( )
Move ( )
Move ( )
Invoking move() method on
different objects, would
produce different results
differing in speed.
Polymorphism : How is it useful ?
name
Shape getName( )
calculateArea( )
base
Circle Square Triangle height
calculateArea( )
Benefits of Object Oriented Approach
State
- The state of an object encompasses the current values
of all its attributes. An attribute can be static or
dynamic.
Behavior
- Behavior is how an object acts or reacts, in terms of its
state changes and operations performed upon it.
Identity
- Identity is that property of an object which uniquely
identifies the object.
State of an Object
Car Attributes
Color
Average
Make Static
Power
Fuel type
Window Operations
Open
Close
Maximize Total number of operations that can be
Minimize performed upon a window object and
Resize consequent changes in its state
Move defines behavior of an object
Identity of an Object
Bank Account
Account Number Identity
Balance
Interest Rate
Customer Name
datatype methodname2(parameter-list)
{
// method body
}
}
Data or variables, defined within a class are called instance
variables. Variables and methods are called as members of class.
Thus the structure and behavior of an object is defined in a class.
class Student
{
int rollNo;
String name; instance variables
String course;
}
The class declaration only creates a template; it does not
create the actual object.
rollNo
objStudent name
course
Movable Boundary
Dynamically allocated Area
Heap Area
(Objects)
Code Section
Student objStudent1 = new Student();
rollNo
objStudent1 name
course
rollNo
objStudent2 name
course
objStudent1
rollNo
name
course
objStudent2
objstudent1 = null;
objStudent1 null
rollNo
objStudent2 name
course
Arguments are the things you pass into the methods. And
parameters are nothing but local variables for that method.
‘this’ keyword
Continued…
Coffee Cram
class A
{
int i=10,j=20;
void printij()
{
System.out.println(“i=”+ i+ “j=”+ j);
}
}
class B extends A
{
int k=30;
void printk()
{
System.out.println(“k=”+ k);
}
}
Multilevel Inheritance
D
Multiple Inheritance
Father Mother
Child
Superclass reference can refer to Subclass Object
General form :
super.member
member could be a suerclass method or a variable.
void disp( )
{
System.out.println(“U R in class B”) // output
}
}
class Main
{
public static void main(String args[])
{
B b = new B();
b.disp();
}
}
Call to an overridden method is resolved at run-time, rather
than at compile time.
Shape Shape
Circle Square
Circle Square
Upcasting
• static
• final
• native
• transient
• volatile
Understanding Static
Static Methods
Final class
• Compile the file and keep the .class files in this directory.
package p1;
class B extends A
{
...
}
package p2;
Class C extends p1.B
{
...
}
Importing packages
• Java includes the import statement to bring certain classes,
or entire packages into visibility.
Continued…
Coffee Cram
Animal
Lion Elephant
• But class can not extend more than once class. Java does
not support multiple class inheritance.
Syntax:
access interface name
{
return-type method1 (paramter-list);
return-type method2 (paramter-list);
type final-varname1 = value;
type final-varname2 = value;
}
• class Foo { } // OK
• interface Baz { } // OK
• interface Fi { } // OK
static int sf1 = sf2 = 30; // (7) Static field. Assignment to sf2 allowed
static int sf2; // (8) Static field
int if1 = 5; // (9) Non-static field
int nsf1 = nsf2 = 30; // (7) Non-static field. Assignment to nsf2 allowed
int nsf2; // (8) Non-static field
static int sf1 = 5; // (9) Static field
Movable Boundary
Dynamically allocated Area
Heap Area
(Objects)
Code Section
Garbage Collection (continued…)
void go()
{
Life z = new Life();
}
When someone calls method go(), ‘z’ is set to null. The only
reference (i.e. ‘z’) to Life() object has been set to null.
void gc()
Requests the garbage collection to run. However, it is
recommended to use the more convenient static method
System.gc().
void runFinalization()
Requests that any pending finalizers to run for objects
eligible for garbage collection. Again, it is more convenient to
use the static method System.runFinalization().
long freeMemory()
Returns the amount of free memory (bytes) in the JVM, that
is available for new objects.
long totalMemory()
Returns the total amount of memory (bytes) available in the
JVM. This includes both memory occupied by current objects
and free memory (that is available for new objects).
Always Remember …
• There are no guarantees that objects that are eligible for
garbage collection will have their finalizers executed. GC
might not even run if the program execution does not warrant
it. Thus, any memory allocated during program execution might
remain allocated after program termination, but will be
reclaimed by the operating system.
Local Classes
void nsm() {
class NSLC {/*...*/}
// (5) Local (inner) class in non-static context
}
public NonStaticMemberClass()
{ this.banner = ToplevelClass.this.headlines; }
The expression
parseXxx() -
• Six parseXxx() methods (one for each numeric wrapper
type)
• parseXxx() returns the named primitive.
• parseXxx() takes a String, returns a primitive, is static.
valueOf() –
• valueOf() returns a newly created wrapped object of the
type that invoked the method.
Wrapper Conversion Utility methods
double d4 = Double.parseDouble("3.14");
// convert a String to a primitive
System.out.println("d4 = " + d4); // result is "d4 = 3.14"
Double d5 = Double.valueOf("3.14");
// create a Double object
System.out.println(d5 instanceof Double );
// result is "true"
Priorities Class
ArrayList
int size()
boolean isEmpty()
boolean contains(Object element)
boolean add(Object element)
boolean remove(Object element)
boolean containsAll(Collection c)
boolean addAll(Collection c)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
void clear()
boolean hasMoreElements()
This returns true, when there are still more elements in the
collection you are enumerating. Returns false, when all the
elements have been enumerated.
Object nextElement()
Returns the next object in the enumeration as a generic
Object reference.
Iterator
boolean hasNext() :-
Object remove() :-
Removes the element that was returned by the last call to the
next() method, from the underlying collection. Invoking this method
results in an IllegalStateException, if the next() method has not
yet been called, or when the remove() method has already been
called after the last call to the next() method. This method is
optional for an iterator, that is, it throws an
UnsupportedOperationException if the remove operation is not
supported.
Set
• Implementations of the Set interface do not allow duplicate
elements.
• This also means that a set can contain at most one null value.
HashSet(Collection c)
Constructs a new set containing the elements in the specified
collection. The new set will not contain any duplicates. This offers
a convenient way to remove duplicates from a collection.
HashSet(int initialCapacity)
Constructs a new, empty set with the specified initial capacity.
// Element Search
int indexOf(Object o)
int lastIndexOf(Object o)
These methods respectively return the index of the first and
the last occurrence of the element in the list if the element is
found; otherwise, the value –1 is returned.
List (continued…)
ArrayList()
Constructs a new, empty ArrayList. An analogous constructor is
provided by the LinkedList and Vector classes.
ArrayList(Collection c)
Constructs a new ArrayList containing the elements in the
specified collection. The new ArrayList will retain any duplicates.
The ordering in the ArrayList will be determined by the
traversal order of the iterator for the collection passed as
argument. An analogous constructor is provided by the
LinkedList and Vector classes.
ArrayList(int initialCapacity)
Constructs a new, empty ArrayList with the specified initial
capacity. An analogous constructor is provided by the Vector
class.
Map
• A Map does not allow duplicate keys, in other words, the keys
are unique.
• Both the keys and the values must be objects. This means that
primitive values must be wrapped in their respective wrapper
objects, if they are to be put in a map.
• A map is not a collection and the Map interface does not extend
the Collection interface.
Map methods
void putAll(Map t)
Copies all entries from the specified map to the current map.
Map methods
int size()
These methods return the number of entries (i.e., number of
unique keys in the map)
boolean isEmpty()
Returns true / false depending upon whether map is empty or not.
void clear()
deletes all the entries from the current map.
Map (continued…)
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
Constructs a new, empty HashMap, using either specified or
default initial capacity and load factor.
HashMap(Map otherMap)
Constructs a new map containing the elements in the specified
map.
Properties
• Properties is a subclass of Hashtable.
• It is used to maintain list of values in which, key is also a String
and value is also a String.
• Properties class is used by many other Java classes.
E.g. System.getProperties() is used to get environmental values.
Thread Creation
Thread(Runnable threadTarget)
Thread(Runnable threadTarget, String threadName)
The first method returns the name of the thread. The second
one sets the thread's name passed as an argument.
void run()
void start()
This method spawns a new thread, that is, the new thread will
begin execution as a child thread of the current thread. The
spawning is done asynchronously as the call to this method
returns immediately. It throws an IllegalThreadStateException
if the thread was already started.
Coffee Cram
Ready-to-run state
A thread starts life in the
Ready-to-run state.
Running state
If a thread is in the Running
state, it means that the thread
is currently executing.
Thread Life Cycle
Dead state
Non-runnable states
A running thread can transit to one of the non-runnable
states, depending on the circumstances.
A thread remains in a non-runnable state until a special
transition occurs.
A thread does not go directly to the Running state from a non-
runnable state, but transits first to the Ready-to-run state.
Thread Life Cycle
1) Preemptive scheduling:
If a thread with a higher priority than the current running thread
moves to the Ready-to-run state, then the current running thread
can be preempted (moved to the Ready-to-run state) to let the
higher priority thread execute.
Thread Scheduler
Thread 4 Thread 3
Thread Priorities
myThread.setPriority(Math.min(Thread.MAX_PRIORITY,
myThread.getPriority()+1));
Unary and Binary Numeric Promotions (continued...)
Floating-Point Arithmetic