SlideShare a Scribd company logo
Java.lang package tutorial
Java.util package contains the classes that are fundamental to
the design of the Java programming language.
Java.langBooleanClass
The java.lang.Boolean class wraps a value of the primitive
type boolean in an object. An object of type Boolean contains
a single field whose type is boolean.
Class declaration
Following is the declaration for java.lang.Boolean class:
public final class Boolean
extends Object
implements Serializable, Comparable<Boolean>
Java.lang.Byte Class
The java.lang.Byte class wraps a value of primitive type byte
in an object. An object of type Byte contains a single field
whose type is byte.
Class declaration
Following is the declaration for java.lang.Byte class:
public final class Byte
extends Number
implements Comparable<Byte>
Java.lang.Character Class
The java.lang.Character class wraps a value of the primitive
type char in an object. An object of type Character contains a
single field whose type is char.
Class declaration
Following is the declaration for java.lang.Character class:
public final class Character
extends Object
implements Serializable, Comparable<Character>
Java.lang.Character.Subset Class
The java.lang.Character.Subset class instances represent
particular subsets of the Unicode character set. The only family
of subsets defined in the Character class is UnicodeBlock.
Class declaration
Following is the declaration
for java.lang.Character.Subset class:
public static class Character.Subset
extends Object
Java.lang.Character.UnicodeBlock Class
The java.lang.Character.UnicodeBlock class is a family of
character subsets representing the character blocks in the
Unicode specification. Character blocks generally define
characters used for a specific script or purpose.
Class declaration
Following is the declaration
for java.lang.Character.UnicodeBlock class:
public static final class Character.UnicodeBlock
extends Character.Subset
Java.lang.Class Class
The java.lang.Class class instance represent classes and
interfaces in a running Java application.It has no public
constructor.
Class declaration
Following is the declaration for java.lang.Class class:
public final class Class<T>
extends Object
implements Serializable, GenericDeclaration, Type,
AnnotatedElement
Java.lang.ClassLoader Class
The java.lang.ClassLoader class is an object that is
responsible for loading classes. This class is an abstract class.
It may be used by security managers to indicate security
domains.
Class declaration
Following is the declaration for java.lang.ClassLoader class:
public abstract class ClassLoader
extends Object
Java.lang.Compiler Class
The java.lang.Compiler class is provided to support Java-to-
native-code compilers and related services. By design, it
serves as a placeholder for a JIT compiler implementation.
Class declaration
Following is the declaration for java.lang.Compiler class:
public final class Compiler
extends Object
Java.lang.Double Class
The java.lang.Double class wraps a value of the primitive type
double in an object. An object of type Double contains a single
field whose type is double.
Class declaration
Following is the declaration for java.lang.Double class:
public final class Double
extends Number
implements Comparable<Double>
Java.lang.Enum Class
The java.lang.Enum class is the common base class of all
Java language enumeration types.
Class declaration
Following is the declaration for java.lang.Enum class:
public abstract class Enum<E extends Enum<E>>
extends Object
implements Comparable<E>, Serializable
Java.lang.Float Class
The java.lang.Float class wraps a value of primitive type float
in an object. An object of type Float contains a single field
whose type is float.
Class declaration
Following is the declaration for java.lang.Float class:
public final class Float
extends Number
implements Comparable<Float>
Java.lang.InheritableThreadLocal Class
The java.lang.InheritableThreadLocal class extends
ThreadLocal to provide inheritance of values from parent
thread to child thread: when a child thread is created, the child
receives initial values for all inheritable thread-local variables
for which the parent has values.
Class declaration
Following is the declaration
for java.lang.InheritableThreadLocal class:
public class InheritableThreadLocal<T>
extends ThreadLocal<T>
Java.lang.Integer Class
The java.lang.Integer class wraps a value of the primitive type
int in an object. An object of type Integer contains a single field
whose type is int.
Class declaration
Following is the declaration for java.lang.Integer class:
public final class Integer
extends Number
implements Comparable<Integer>
Java.lang.Long Class
The java.lang.Long class wraps a value of the primitive type
long in an object. An object of type Long contains a single field
whose type is long.
Class declaration
Following is the declaration for java.lang.Long class:
public final class Long
extends Number
implements Comparable<Long>
Java.lang.Number Class
The java.lang.Number class is the superclass of classes
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and
Short.The Subclasses of Number must provide methods to
convert the represented numeric value to byte, double, float,
int, long, and short.
Class declaration
Following is the declaration for java.lang.Number class:
public abstract class Number
extends Object
implements Serializable
Java.lang.Object Class
The java.lang.Object class is the root of the class hierarchy.
Every class has Object as a superclass. All objects, including
arrays, implement the methods of this class.
Class declaration
Following is the declaration for java.lang.Object class:
public class Object
Java.lang.Package Class
The java.lang.Package class contain version information
about the implementation and specification of a Java package
Class declaration
Following is the declaration for java.lang.Package class:
public class Package
extends Object
implements AnnotatedElement
Java.lang.Process Class
The java.lang.Process class provides methods for performing
input from the process, performing output to the process,
waiting for the process to complete, checking the exit status of
the process, and destroying (killing) the process.
Class declaration
Following is the declaration for java.lang.Process class:
public abstract class Process
extends Object
Java.lang.ProcessBuilder Class
The java.lang.ProcessBuilder class is used to create
operating system processes.This class is not synchronized.
Class declaration
Following is the declaration
for java.lang.ProcessBuilder class:
public final class ProcessBuilder
extends Object
Java.lang.Runtime Class
The java.lang.Runtime class allows the application to
interface with the environment in which the application is
running.
Class declaration
Following is the declaration for java.lang.Runtime class:
public class Runtime
extends Object
Java.lang.RuntimePermission Class
The java.lang.RuntimePermission class is for runtime
permissions. A RuntimePermission contains a name (also
referred to as a "target name") but no actions list; you either
have the named permission or you don't.
Class declaration
Following is the declaration
for java.lang.RuntimePermission class:
public final class RuntimePermission
extends BasicPermission
Java.lang.String Class
The java.lang.String class represents character strings. All
string literals in Java programs, such as "abc", are
implemented as instances of this class.Strings are constant,
their values cannot be changed after they are created
Class declaration
Following is the declaration for java.lang.String class:
public final class String
extends Object
implements Serializable, Comparable<String>,
CharSequence
Java.lang.StringBuffer Class
The java.lang.StringBuffer class is a thread-safe, mutable
sequence of characters. Following are the important points
about StringBuffer:
 A string buffer is like a String, but can be modified.
 It contains some particular sequence of characters, but
the length and content of the sequence can be changed
through certain method calls.
 They are safe for use by multiple threads.
 Every string buffer has a capacity.
Class declaration
Following is the declaration for java.lang.StringBuffer class:
public final class StringBuffer
extends Object
implements Serializable, CharSequence
oops:
1)object oriented programming system(oops)
The features related to object oriented programming
system are
1)class/object
2)Encapsulation
3)Abstraction
4)Inheritance
5)polymorpism
class/object:Entire oops metholodogy has been derived
from a single root concept called object.An object is
nothing that really exists in the worldand can be
distiunshed from others.
string name;
int age;
char sex;
It is possible that some object s may have similar
properties and objects .such objects belong to some
category a class.
variables variables
name raju
age 25
sex Male
methods methods
talking Talk()
walking walk()
eating eat()
A class is a modeal for creating objects and does not exit
phyisically,An object is actually that exits phyisically,Both
the class and objects contain variable and methods
Class person
//Properties of a person ---variable
string Name;
int age;
//Action done by a person --method
Void talk()
{
}
void eat()
{
}
}
encapsulation:The encapsulation is achieved by
combining the methods and attribute into a class.The class
acts like a container.
Int id;
string name;
Encapsulation in java:
class person
{
//Variable _data
private string name;
private int age
//method
public void talk()
{
system.out.println("Hello,I am "+name);
system.out.println("my age is "+age);
}
}
abastraction:There me be a lot af data a class contains and
the user does not need the entire data.The user requires
only some part of the available data. In these case ,we can
hide the unnecessary data from the user and expose only
the data is of interest to the user .This is called abstraction
Eg:Class bank
{
Privcate int accno;
private string name;
private float balance;
private float profit;
private float loan;
Public void display_to_cleark()
{
System.out.printl=n("aCCNO="+aCCNO);
System.out.printl=n("NAME="+name);
System.out.printl=n("balance="+balance);
}
}
Inheritance:Inheritance is the property whicH Allows a
child class to inherit some properties from its parent class.
class b extends a
{
}
eg:
class a
{
protected int a;
protected int b;
public void method ()
{
}
}
class b extends a
private int c;
public void method 2()
{
}
}
polymorphism:
The word polymorphisim came from the greek word ply
means many and morphos means meaning
The ability to define more than one function with the same
name is called as ploymorphism
Class one
{
Void calculate (int x)]
{
system .out .println("square value ="+?(x*x));
}
}
class two extends one
{
void calculate (int x)
system.out.println("cute value="+(x*x*x));
}
}
collections:
A collection Framework is a class library to handle goups of
objects collection is a framework implemented in
java.util.package
A collection object or a container object is an object which can
store a group of other objects.
java .util
collection class
collection objects
A group of objects stored in a single collection objects.
Sets: A set represents group of elements arranged just like an
array. The sets will grow dynamically when the elements are
stored into it. A set will not allow duplicate elements. If we try to
pass the same element that is already in the set, then it is not
shared into the set.
List:
Lists are like sets ,they store a group of elements, But list
allows duplicate values to be stored.
Queues:
A queues represents arrangement of elements in FIFO(First in
first out) order. This means elements into the queue will be
removed first from the queue.
Maps:
Maps are stored elements in the form of key and value pairs .If
the key value is provided then it is corresponding value can be
obtained of course ,the key should have unique value.
Iterator interface:
Iterator is an interface that contains methods to retrieve the
elements one by one from a collection object. It has 3 methods
Boolean has next():The method returns true if the iterator has
more elements.
Element next(): The method returns the next element in the
itetrator.
Void remove: This method removes from the collection the lost
elements returned by the iterator.
List Iterator Interface:
List iterator is an interface that contains methods retrieve the
elements from a collection object ,both in forward and reverse
diretions.
Enumeration interface: This interface is useful to retrieve one
by one elements like the Iterator It has 2 methods
Boolean has more elements():
This method tests if the enumeration has any more elements or
not.
Elements next Elements():This returns the next element thats is
avilable in the Enumeration.
Java Exceptions :l
Exception are used in Java to handle errors or any other
exceptional event that occurs in the normal flow of program.
There are several way Exception can occur in Java.
 Data provided is not in expected format(eg. int instead of
String).
 DB can not connected.
 Network connection Lost.
 Object is null.
JVM running out of memory is a type of Error which can occur
at runtime.
Overloading:
Overloaded method gives you an option to use the same
method name in a class but with different argument.
Overloading Method Rules
There are some rules associated with overloaded method.
Overloaded methods
 Must change the argument list
 Can change the return type
 Can change the access modifier(Broader)
 Can declare new or broader checked exception
A method can be overloaded in Class or in SubClass.
Overloading Method Example
1
2
3
//Overloaded method with two argument
public void add(int input1, int input2) {
System.out.println("In method with two argument");
4
5
6
7
8
9
}
//Overloaded method with one argument
public void add(int input1) {
System.out.println("In method with one argument");
}
Java Method Override:
Class inheriting the method from its super class has the option
to override it. Benefit of overriding is the ability to define
behaviour specific to particular class.
Method Overriding Example
1
2
3
4
5
public class ParentClass
{
public void show()
{
System.out.println("Show method of Super class");
6
7
8
9
10
11
12
13
14
15
16
}
}
public class SubClass extends ParentClass
{
//below method is overriding the ParentClass version of
show method
public void show()
{
System.out.println("Show method of Sub class");
}
}
Method Override Rules
 Overriding method can not have more restrictive access
modifier than the method being overriden but it can be less.
 The argument list must exactly match that of the overriden
method, if they don’t it is more likely that you are
overloading the method.
 Return type must be the same as, or subtype of the return
type declared in overriden method in Super class.
 Overriding method can throw any unchecked
exception(Runtime)but it can throw checked exception
which is broader or new than those declared by the
overriden method but it can not throw fewer or narrow
checked exception.
 Final method can not be overriden.
 Static methods can not be overriden.
 If a method cannot be inherited then it cannot be overriden.
HashMap
HashMap is HashTable based implementation of Map. This is
the reason why interviewer always ask for difference between
HashMap and HashTable. HashMap is mostly equals to
HashTable except below two differences.
1. HashMap is unsynchronized while HashTable is
synchronised. which means hash table can be shared
between multiple threads but hash map cannot be shared.
2. HashMap permits null while HashTable doesn’t.
3. one more diference is that because of threads safety and
synchronization hash Table is mush slower than hash map
if used in single thread
Example of HashMap
1. How to iterate a Map
2. Different ways of iterating a Map
3. When HashCode and Equals will get called. (Pay close
attention to output of HashCode and equals method call)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
Map<JBT, Integer> m1 = new HashMap<JBT, Integer>();
JBT t1 = new JBT(1, 2);
JBT t2 = new JBT(1, 3);
JBT t3 = new JBT(2, 1);
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
m1.put(t1, 1);
m1.put(t2, 2);
m1.put(t3, 3);
System.out.println("Addition Done");
/*
* Below you can find 3 different ways to iterate a Map.
Uncomment
* different section and see the different in Output. Pay
attention to
* when Hashcode and Equals is called
*/
/* Set s = m1.entrySet();
for (Iterator i = s.iterator(); i.hasNext();) {
Map.Entry me = (Map.Entry) i.next();
System.out.println(me.getKey() + " : " + me.getValue());
}
*/
/* for (Map.Entry<JBT, Integer> entry :
m1.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
*/
for (Object key : m1.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ m1.get(key));
}
}
}
class JBT {
JBT(int i, int j) {
this.i = i;
this.j = j;
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
}
int i, j;
@Override
public int hashCode() {
System.out.println("Inside HashCode Method");
int k = i + j;
return k;
}
@Override
public boolean equals(Object obj) {
System.out.println("Inside Equals Method");
if (i == ((JBT) obj).i && j == ((JBT) obj).j)
return true;
else
return false;
}
@Override
public String toString() {
return String.valueOf(i).concat(String.valueOf(j));
}
}
Java Hashtable class
o A Hashtable is an array of list.Each list is known as a
bucket.The position of bucket is identified by calling the
hashcode() method.A Hashtable contains values based on
the key. It implements the Map interface and extends
Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
Example of Hashtable:
1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4.
5. Hashtable<Integer,String> hm=new Hashtable<Integer,String
>();
6.
7. hm.put(100,"Amit");
8. hm.put(102,"Ravi");
9. hm.put(101,"Vijay");
10. hm.put(103,"Rahul");
11.
12. for(Map.Entry m:hm.entrySet()){
13. System.out.println(m.getKey()+" "+m.getValue());
14. }
15. }
16.
17. Output:103 Rahul
18. 102 Ravi
19. 101 Vijay
20. 100 Amit
What is Serialization
Serialization is a process in which current state of Object will be
saved in stream of bytes. As byte stream create is platform
neutral hence once objects created in one system can be
deserialized in other platform.
What is the use of Serialization
As written above serialization will translate the Object state to
Byte Streams. This B
yte stream can be used for different purpose.
 Write to Disk
 Store in Memory
 Sent byte stream to other platform over network
 Save byte stream in DB(As BLOB)
Serialization and Deserialization in Java
Now we know what is serialization. But in terms of Java how
this serialization will work and how to make a class serializable.
Java has already provided out of the box
way(java.io.Serializable Interface) to serialize an Object. If you
want any class to be serialized then that class needs to
implement give interface.
Note*: Serializable Interface is a Marker Interface. Hence there
is no method in Serializable interface.
Code for Serialization of Java Class
Employee.java
1
2
3
4
5
6
7
8
9
10
11
12
package com.jbt;
import java.io.Serializable;
public class Employee implements Serializable
{
public String firstName;
public String lastName;
private static final long serialVersionUID = 5462223600l;
}
SerializaitonClass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.jbt;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializaitonClass {
public static void main(String[] args) {
Employee emp = new Employee();
emp.firstName = "Vivekanand";
emp.lastName = "Gautam";
try {
FileOutputStream fileOut = new
FileOutputStream("./employee.txt");
ObjectOutputStream out = new
ObjectOutputStream(fileOut);
out.writeObject(emp);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in ./employee.txt
file");
} catch (IOException i) {
i.printStackTrace();
}
}
}
DeserializationClass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.jbt;
import java.io.*;
public class DeserializationClass {
public static void main(String[] args) {
Employee emp = null;
try {
FileInputStream fileIn = new
FileInputStream("./employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
emp = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserializing Employee...");
System.out.println("First Name of Employee: " +
emp.firstName);
System.out.println("Last Name of Employee: " +
emp.lastName);
}
}
First run “SerializaitonClass” and you will get “employee.txt”
file created.
Second run “DeserializationClass” and java will deserialize
the class and value will be printed in console.
Output would be
1
2
3
4
5
Deserializing Employee...
First Name of Employee: Vivekanand
Last Name of Employee: Gautam
Java Interface
Creating an Interface means defining a Contract. This Contract
states what a class can do without forcing how it should do.
Declaring an Interface
Interface can be defined with Interface keyword.
Java Interface Example
1
2
3
4
5
6
7
public interface MyInterface
{
int i=0;
public void Height(int height);
public abstract void setHeight();
}
Rules for Declaring Interface
There are some rules that needs to be followed by Interface.
 All Interface methods are implicitly public and abstract. Even
if you write these keyword it will not create problem as you
can see in second method declaration.
 Interfaces can declare only Constant. Instance variables are
not allowed. It means all variables inside Interface must be
public, static, final. Variables inside interface are implicitly
public static final.
 Interface methods can not be static.
 Interface methods can not be final, strictfp or native.
 Interface can extend one or more other interface. Note:
Interface can only extend other interface.
Interface vs Abstract Class
Interface are like 100% Abstract Class. Interface can not
have non abstract methods while abstract class can have. A
Class Can implement more than one interface while Class can
extend only one class. As Abstract class comes in hierarchy of
Classes it can extend other classes too while Interface can only
extend Interfaces.
Use Interface in Class
How can we take the advantage of Interface after creating it in
Java. To take the advantage we need to implement or class
with given Interface. Implement keyword can be used for this
purpose.
Examples of Class Implementing Interface
Example 1:
1
2
3
4
5
6
7
public class InterfaceExampleOne implements interfaceOne {
}
interface interfaceOne {
}
Example 2:
1
2
3
4
/*
* As implmeneted Interface have any abstract method so
this class
* need to implement any method.
*/
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class InterfaceExampleTwo implements interfaceTwo {
@Override
public void methhod() {
System.out.println(var);
}
}
/*
* Below interface has an abstract method so implemented
class needs to
* implement this method unless and untill it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
public abstract void methhod();
}
Example 3:
1
/*
* As below class is not abstract class and it is extending
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
abstract class which
* has not yet implemented the method from interface so this
class is FORCED to
* implement method from Interface in
hierarachy(interfaceTwo).
*/
class InterfaceExampleTwo extends InterfaceExampleThree
{
@Override
public void methhod() {
System.out.println(var);
}
}
/*
* Below interface has an abstract method so implemented
class needs to
* implement this method unless and untill it is abstract itself
*/
interface interfaceTwo {
public final int var = 9;
24
25
26
27
28
29
30
31
32
33
34
public abstract void methhod();
}
/*
* Even if Interface has abstract method ABSTRACT CLASS
is not forced to
* implement it. Abstract class may/may not navigate this
responsibility of
* implementing abstract method to class which is not
abstract.
*/
abstract class InterfaceExampleThree implements
interfaceTwo {
// Method from Interface is not implemented here
}
Java Thread :
Thread term can be used in two ways
 An instance of class java.lang.Thread
 A Thread of Execution
An Instance of Thread is an object like any other object in Java,
it contains variables and methods which lives and dies on the
heap. But a Thread of Execution is an individual process which
has its ownstack call. Even if you don’t create any thread in
your program, thread will be running there and main() method
will start that.
Note: In case of thread most of thing is unpredictable.
Type of Thread
Thread can be of two types.
 User Thread
 Daemon Thread
Difference between these two type of thread is that JVM exit an
application only when all User Thread are complete. JVM
doesn’t care about the status of Daemon Thread.
Thread Definition
A thread can be defined in two ways
 Extend the java.lang.Thread class.
 Implement the Runnable interface.
Extending Java Thread class:
Class need to extend the Thread class & Override the
run()method.
1
2
3
4
5
6
7
class MyThread extends Thread
{
public void run()
{
System.out.println("Important job running in MyThread");
}
}
But the problem with this approach is that class can not extend
any more class.
Note : run method can be overloaded in class. but only run()
method(without argument) will be consider by JVM. Any other
overridden method will needs to be called explicitly.
Implements runnnable interface
Class needs to implement runnable interface and override the
run() method. Creating Thread in this way gives you flexibility
to extend any class you like.
1
2
3
4
5
6
7
class MyRunnable implements Runnable {
public void run() {
System.out.println("Important job running in MyRunnable");
} }
Instantiating Thread :
Every thread of execution begins as an instance of class
Thread. In any case Thread objects needs to be created before
creating Thread of Execution.
Creating Thread object is different for both the cases. In case of
Extending Thread class you can directly initiate class with new
keyword as it has extended Thread class itself.
1 MyThread t = new MyThread()
In case of implimenting Runnable interface. First created
runnable class needs to be instatiated.
1 MyRunnable r = new MyRunnable();
Now pass this runnable object to Thread.
1 Thread t = new Thread(r);
If you create a thread using the no-arg constructor, the thread
will call its own run(). This happened in first case(Extending
Thread class) But in case of Runnable Thread class needs to
know that run method from class implementing runnnable
interface needs to be invoked instead of run() from Thread
class. So we need to pass the class as argument to Thread.
Single runnable instance can be passed to multiple Thread
object.
1
2
public class TestThreads {
3
4
5
6
7
8
9
10
11
12
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
}}
Giving the same target to multiple threads means that several
threads of execution will be running the very same job (and that
the same job will be done multiple times).
Note : The Thread class itself implements Runnable. (After all,
it has a run() method that we were overriding.) This means that
you could pass a Thread to another Thread’s constructor.
Overloaded constructor in Thread class:
1
2
Thread()
Thread(Runnable target)
3
4
Thread(Runnable target, String name)
Thread(String name)
Till now we have created Thread object and it knows what to do
in form of run() method. But till now it is still an object. It does
not have its own call stack. In other words Thread of execution
has not been started. A Thread object will have its own stack
only when start() method will be called on Thread.
Till now Thread has 2 states.
 New state (Thread object created but Start method not
invoked)
 runnable(alive) state (start method is invoked )
Note : Calling run() method from java code directly mean that
you are invoking a method and stack will not be created.
When a Thread is in runnable state means Thread is created
but it’s run method is not yet executed and thread is waiting for
his turn. Once Thread got selected thread’s run method will
execute and that state will called running state.
Thread Scheduler :
The thread scheduler is the part of the JVM that decides which
thread should run at any given moment, and also takes threads
out of the run state. Any thread in the runnable state can be
chosen by the scheduler to be the one and only running thread.
If a thread is not in a runnable state, then it cannot be chosen
to be the currently running thread. Some method that can
influence scheduler to some extent(Note*: We can’t control the
behavior of Thread scheduler)
These methods are from Thread class
1
2
3
4
* public static void sleep(long millis) throws
InterruptedException
* public static void yield()
* public final void join() throws InterruptedException
* public final void setPriority(int newPriority)
Methods from Object class.
1
2
3
* public final void wait() throws InterruptedException
* public final void notify()
* public final void notifyAll()
Till now we come across 3 state of Thread
 New
 Runnable
 Running
There are some more state of thread in which Thread will not
be eligible to run.
 Waiting/blocked/sleeping
 Dead
A thread is in Dead state when its run method completed its
execution.
Sleeping
The sleep() method is a static method of class Thread. (where
it still has to beg to be the currently running thread). as it is
static method only currently running Thread will sleep. Syntax
would be : Thread.sleep()
yield: yield method is related with the priority of Thread. It is
also static method so it works only on currently running thread.
Scheduler make it sure that If a thread enters the runnable
state, and it has a higher priority than any of the threads in the
pool and a higher priority than the currently running thread, the
lower-priority running thread usually will be bumped back to
runnable and the highest-priority thread will be chosen to run.
at any given time the currently running thread usually will not
have a priority that is lower than any of the threads in the pool.
yield() is supposed to do is make the currently running thread
head back to runnable to allow other threads of the same
priority to get their turn.
Join()
Join is a non static method. It lets one thread “join onto the end”
of another thread. If you join Thread B to Thread A Thread B
will not start untill Thread A complets.
Syntax :
1
2
3
Thread t = new Thread();
t.start();
t.join();
takes the currently running thread and joins it to the end of the
thread referenced by t
There are several other way in which Thread can leave running
state and can return to Runnable state. run methods completes
a call to wait()
Synchronize: It works with Lock. Lock is of two type.
Static lock
Non static lock
Note: There is only one lock per object. Once a thread got the
lock of an object no other thread can enter the synchronise
block/method of given object.
Only methods/block can be synchronised not variable or class.
A class can have both synchronised / non synchronised
method.
Thread can access non synchronised block even if one Thread
got the lock of give object.
If a thread goes to sleep, it holds any locks it has. A thread can
have Lock of different object at the same time.
Syntax :
1
2
3
4
5
6
7
8
9
10
11
class SyncTest {
public void doStuff() {
System.out.println("not synchronized");
synchronized(this) {
System.out.println("synchronized");
}}}
Synchronised Static method :
There is only one copy of the static data, so you only need one
lock per class to synchronize static methods—a lock for the
whole class. There is such a lock; every class loaded in Java
has a corresponding instance of java.lang.Class representing
that class. It’s that java.lang.Class instance whose lock is used
to protect the static methods of the class.
Syntax:
1
2
3
4
5
public static synchronized int getCount() {
return count;
}
MyClass.class thing is called a class literal. It tells the compiler
(who tells the JVM): go and find me the instance of Class that
represents the class called MyClass.
Note : Threads calling non-static synchronized methods in the
same class will only block each other if they’re invoked using
the same instance. As there is only one lock per instance.
Threads calling static synchronized methods in the same class
will always block each other— As there is only one lock per
class.
A static synchronized method and a non-static synchronized
method will not block each other. As they need lock for different
thing(Object & class)
Note : join(), sleep(), yield() these methods keep locks. while
wait release Lock.
What are mutable objects and immutable objects?
An Immutable object is a kind of object whose state cannot be
modified after it is created. This is as opposed to a mutable
object, which can be modified after it is created.
In Java, objects are referred by references. If an object is
known to be immutable, the object reference can be shared.
For
example, Boolean, Byte, Character, Double, Float, Integer,Lo
ng, Short, and String are immutable classes in Java, but the
class StringBuffer is a mutable object in addition to the
immutable String.
class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
str.toLower();
System.out.println(str);
}
}
The output result is
HELLO
HELLO
From the above example, the toLower() method does not
impact on the original content in str. What happens is that a
new String object "hello" is constructed. The toLower() method
returns the new constructed String object's reference. Let's
modify the above code:
class Program {
public static void main(String[] args) {
String str = "HELLO";
System.out.println(str);
String str1 = str.toLower();
System.out.println(str1);
}
}
The output result is
HELLO
hello
The str1 references a new String object that contains "hello".
The String object's method never affects the data the String
object contains, excluding the constructor.
"Classes should be immutable unless there's a very good
reason to make them mutable....If a class cannot be made
immutable, you should still limit its mutability as much as
possible."

More Related Content

What's hot

The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
Java notes
Java notesJava notes
Java notes
Upasana Talukdar
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Madishetty Prathibha
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Prarabdh Garg
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_concepts
Arriz San Juan
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
C#
C#C#
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
Shiva Cse
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to java
Kalai Selvi
 
Core java questions
Core java questionsCore java questions
Core java questions
Pradheep Ayyanar
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
Uzair Salman
 

What's hot (20)

The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
 
Java notes
Java notesJava notes
Java notes
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
11 advance inheritance_concepts
11 advance inheritance_concepts11 advance inheritance_concepts
11 advance inheritance_concepts
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
C#
C#C#
C#
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Complete java&j2ee
Complete java&j2eeComplete java&j2ee
Complete java&j2ee
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to java
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 

Viewers also liked

VSM TEX PROFILE
VSM TEX PROFILEVSM TEX PROFILE
VSM TEX PROFILE
Sathish Kumar
 
Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)
Phyllis Deroian
 
Aukční katalog 2015
Aukční katalog 2015Aukční katalog 2015
Aukční katalog 2015
nadaceleontinkacz
 
A Movement for Improvement; Part 2 - Case Study 3, Part 2----
A Movement for Improvement; Part 2 - Case Study 3, Part 2----A Movement for Improvement; Part 2 - Case Study 3, Part 2----
A Movement for Improvement; Part 2 - Case Study 3, Part 2----
Alexandra E. P. Dahl
 
David Peak CV 11.16
David Peak CV 11.16David Peak CV 11.16
David Peak CV 11.16
David Peak
 
Amplify & MaRS DD - Financial Fundementals
Amplify & MaRS DD -  Financial FundementalsAmplify & MaRS DD -  Financial Fundementals
Amplify & MaRS DD - Financial Fundementals
Kyle Turriff
 
CONCEPTO
CONCEPTOCONCEPTO
CONCEPTO
anyclavijo
 
ExpLOD: a framework for explaining recommendations based on the Linked Open D...
ExpLOD: a framework for explaining recommendations based on the Linked Open D...ExpLOD: a framework for explaining recommendations based on the Linked Open D...
ExpLOD: a framework for explaining recommendations based on the Linked Open D...
Fedelucio Narducci
 
Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)
Phyllis Deroian
 
Lr4 saglaeva
Lr4 saglaevaLr4 saglaeva
Lr4 saglaeva
Saglaeva
 
Conflictos en las organizaciones
Conflictos en las organizacionesConflictos en las organizaciones
Conflictos en las organizaciones
julio cedeno
 

Viewers also liked (11)

VSM TEX PROFILE
VSM TEX PROFILEVSM TEX PROFILE
VSM TEX PROFILE
 
Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)
 
Aukční katalog 2015
Aukční katalog 2015Aukční katalog 2015
Aukční katalog 2015
 
A Movement for Improvement; Part 2 - Case Study 3, Part 2----
A Movement for Improvement; Part 2 - Case Study 3, Part 2----A Movement for Improvement; Part 2 - Case Study 3, Part 2----
A Movement for Improvement; Part 2 - Case Study 3, Part 2----
 
David Peak CV 11.16
David Peak CV 11.16David Peak CV 11.16
David Peak CV 11.16
 
Amplify & MaRS DD - Financial Fundementals
Amplify & MaRS DD -  Financial FundementalsAmplify & MaRS DD -  Financial Fundementals
Amplify & MaRS DD - Financial Fundementals
 
CONCEPTO
CONCEPTOCONCEPTO
CONCEPTO
 
ExpLOD: a framework for explaining recommendations based on the Linked Open D...
ExpLOD: a framework for explaining recommendations based on the Linked Open D...ExpLOD: a framework for explaining recommendations based on the Linked Open D...
ExpLOD: a framework for explaining recommendations based on the Linked Open D...
 
Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)Park plaza sweetshoppe (2)
Park plaza sweetshoppe (2)
 
Lr4 saglaeva
Lr4 saglaevaLr4 saglaeva
Lr4 saglaeva
 
Conflictos en las organizaciones
Conflictos en las organizacionesConflictos en las organizaciones
Conflictos en las organizaciones
 

Similar to core java for hadoop

Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
SURBHI SAROHA
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
Khaled Anaqwa
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
venud11
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
Java basics
Java basicsJava basics
Java basics
sagsharma
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Ayes Chinmay
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
İbrahim Kürce
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
Pankaj kshirsagar
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
VijalJain3
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
VasanthiMuniasamy2
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 

Similar to core java for hadoop (20)

Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUEITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
 
Java basics
Java basicsJava basics
Java basics
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 

core java for hadoop

  • 1. Java.lang package tutorial Java.util package contains the classes that are fundamental to the design of the Java programming language. Java.langBooleanClass The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean. Class declaration Following is the declaration for java.lang.Boolean class: public final class Boolean extends Object implements Serializable, Comparable<Boolean> Java.lang.Byte Class The java.lang.Byte class wraps a value of primitive type byte in an object. An object of type Byte contains a single field whose type is byte. Class declaration Following is the declaration for java.lang.Byte class: public final class Byte
  • 2. extends Number implements Comparable<Byte> Java.lang.Character Class The java.lang.Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. Class declaration Following is the declaration for java.lang.Character class: public final class Character extends Object implements Serializable, Comparable<Character> Java.lang.Character.Subset Class The java.lang.Character.Subset class instances represent particular subsets of the Unicode character set. The only family of subsets defined in the Character class is UnicodeBlock. Class declaration Following is the declaration for java.lang.Character.Subset class: public static class Character.Subset
  • 3. extends Object Java.lang.Character.UnicodeBlock Class The java.lang.Character.UnicodeBlock class is a family of character subsets representing the character blocks in the Unicode specification. Character blocks generally define characters used for a specific script or purpose. Class declaration Following is the declaration for java.lang.Character.UnicodeBlock class: public static final class Character.UnicodeBlock extends Character.Subset Java.lang.Class Class The java.lang.Class class instance represent classes and interfaces in a running Java application.It has no public constructor. Class declaration Following is the declaration for java.lang.Class class:
  • 4. public final class Class<T> extends Object implements Serializable, GenericDeclaration, Type, AnnotatedElement Java.lang.ClassLoader Class The java.lang.ClassLoader class is an object that is responsible for loading classes. This class is an abstract class. It may be used by security managers to indicate security domains. Class declaration Following is the declaration for java.lang.ClassLoader class: public abstract class ClassLoader extends Object Java.lang.Compiler Class The java.lang.Compiler class is provided to support Java-to- native-code compilers and related services. By design, it serves as a placeholder for a JIT compiler implementation. Class declaration Following is the declaration for java.lang.Compiler class: public final class Compiler
  • 5. extends Object Java.lang.Double Class The java.lang.Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double. Class declaration Following is the declaration for java.lang.Double class: public final class Double extends Number implements Comparable<Double> Java.lang.Enum Class The java.lang.Enum class is the common base class of all Java language enumeration types. Class declaration Following is the declaration for java.lang.Enum class: public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable
  • 6. Java.lang.Float Class The java.lang.Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float. Class declaration Following is the declaration for java.lang.Float class: public final class Float extends Number implements Comparable<Float> Java.lang.InheritableThreadLocal Class The java.lang.InheritableThreadLocal class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values. Class declaration Following is the declaration for java.lang.InheritableThreadLocal class: public class InheritableThreadLocal<T> extends ThreadLocal<T>
  • 7. Java.lang.Integer Class The java.lang.Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Class declaration Following is the declaration for java.lang.Integer class: public final class Integer extends Number implements Comparable<Integer> Java.lang.Long Class The java.lang.Long class wraps a value of the primitive type long in an object. An object of type Long contains a single field whose type is long. Class declaration Following is the declaration for java.lang.Long class: public final class Long extends Number implements Comparable<Long>
  • 8. Java.lang.Number Class The java.lang.Number class is the superclass of classes BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.The Subclasses of Number must provide methods to convert the represented numeric value to byte, double, float, int, long, and short. Class declaration Following is the declaration for java.lang.Number class: public abstract class Number extends Object implements Serializable Java.lang.Object Class The java.lang.Object class is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Class declaration Following is the declaration for java.lang.Object class: public class Object
  • 9. Java.lang.Package Class The java.lang.Package class contain version information about the implementation and specification of a Java package Class declaration Following is the declaration for java.lang.Package class: public class Package extends Object implements AnnotatedElement Java.lang.Process Class The java.lang.Process class provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process. Class declaration Following is the declaration for java.lang.Process class: public abstract class Process extends Object
  • 10. Java.lang.ProcessBuilder Class The java.lang.ProcessBuilder class is used to create operating system processes.This class is not synchronized. Class declaration Following is the declaration for java.lang.ProcessBuilder class: public final class ProcessBuilder extends Object Java.lang.Runtime Class The java.lang.Runtime class allows the application to interface with the environment in which the application is running. Class declaration Following is the declaration for java.lang.Runtime class: public class Runtime extends Object Java.lang.RuntimePermission Class The java.lang.RuntimePermission class is for runtime permissions. A RuntimePermission contains a name (also
  • 11. referred to as a "target name") but no actions list; you either have the named permission or you don't. Class declaration Following is the declaration for java.lang.RuntimePermission class: public final class RuntimePermission extends BasicPermission Java.lang.String Class The java.lang.String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.Strings are constant, their values cannot be changed after they are created Class declaration Following is the declaration for java.lang.String class: public final class String extends Object implements Serializable, Comparable<String>, CharSequence
  • 12. Java.lang.StringBuffer Class The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are the important points about StringBuffer:  A string buffer is like a String, but can be modified.  It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.  They are safe for use by multiple threads.  Every string buffer has a capacity. Class declaration Following is the declaration for java.lang.StringBuffer class: public final class StringBuffer extends Object implements Serializable, CharSequence
  • 13. oops: 1)object oriented programming system(oops) The features related to object oriented programming system are 1)class/object 2)Encapsulation 3)Abstraction 4)Inheritance 5)polymorpism class/object:Entire oops metholodogy has been derived from a single root concept called object.An object is nothing that really exists in the worldand can be distiunshed from others. string name; int age; char sex; It is possible that some object s may have similar properties and objects .such objects belong to some category a class. variables variables
  • 14. name raju age 25 sex Male methods methods talking Talk() walking walk() eating eat() A class is a modeal for creating objects and does not exit phyisically,An object is actually that exits phyisically,Both the class and objects contain variable and methods Class person //Properties of a person ---variable string Name; int age; //Action done by a person --method Void talk() { }
  • 15. void eat() { } } encapsulation:The encapsulation is achieved by combining the methods and attribute into a class.The class acts like a container. Int id; string name; Encapsulation in java: class person { //Variable _data private string name; private int age //method public void talk() { system.out.println("Hello,I am "+name); system.out.println("my age is "+age);
  • 16. } } abastraction:There me be a lot af data a class contains and the user does not need the entire data.The user requires only some part of the available data. In these case ,we can hide the unnecessary data from the user and expose only the data is of interest to the user .This is called abstraction Eg:Class bank { Privcate int accno; private string name; private float balance; private float profit; private float loan; Public void display_to_cleark() { System.out.printl=n("aCCNO="+aCCNO); System.out.printl=n("NAME="+name); System.out.printl=n("balance="+balance); }
  • 17. } Inheritance:Inheritance is the property whicH Allows a child class to inherit some properties from its parent class. class b extends a { } eg: class a { protected int a; protected int b; public void method () { } } class b extends a private int c; public void method 2() { } }
  • 18. polymorphism: The word polymorphisim came from the greek word ply means many and morphos means meaning The ability to define more than one function with the same name is called as ploymorphism Class one { Void calculate (int x)] { system .out .println("square value ="+?(x*x)); } } class two extends one { void calculate (int x) system.out.println("cute value="+(x*x*x)); } }
  • 19. collections: A collection Framework is a class library to handle goups of objects collection is a framework implemented in java.util.package A collection object or a container object is an object which can store a group of other objects. java .util collection class collection objects A group of objects stored in a single collection objects. Sets: A set represents group of elements arranged just like an array. The sets will grow dynamically when the elements are stored into it. A set will not allow duplicate elements. If we try to
  • 20. pass the same element that is already in the set, then it is not shared into the set. List: Lists are like sets ,they store a group of elements, But list allows duplicate values to be stored. Queues: A queues represents arrangement of elements in FIFO(First in first out) order. This means elements into the queue will be removed first from the queue. Maps: Maps are stored elements in the form of key and value pairs .If the key value is provided then it is corresponding value can be obtained of course ,the key should have unique value. Iterator interface: Iterator is an interface that contains methods to retrieve the elements one by one from a collection object. It has 3 methods
  • 21. Boolean has next():The method returns true if the iterator has more elements. Element next(): The method returns the next element in the itetrator. Void remove: This method removes from the collection the lost elements returned by the iterator. List Iterator Interface: List iterator is an interface that contains methods retrieve the elements from a collection object ,both in forward and reverse diretions. Enumeration interface: This interface is useful to retrieve one by one elements like the Iterator It has 2 methods Boolean has more elements():
  • 22. This method tests if the enumeration has any more elements or not. Elements next Elements():This returns the next element thats is avilable in the Enumeration. Java Exceptions :l Exception are used in Java to handle errors or any other exceptional event that occurs in the normal flow of program. There are several way Exception can occur in Java.  Data provided is not in expected format(eg. int instead of String).  DB can not connected.  Network connection Lost.  Object is null. JVM running out of memory is a type of Error which can occur at runtime.
  • 23. Overloading: Overloaded method gives you an option to use the same method name in a class but with different argument. Overloading Method Rules There are some rules associated with overloaded method. Overloaded methods  Must change the argument list  Can change the return type  Can change the access modifier(Broader)  Can declare new or broader checked exception A method can be overloaded in Class or in SubClass. Overloading Method Example 1 2 3 //Overloaded method with two argument public void add(int input1, int input2) { System.out.println("In method with two argument");
  • 24. 4 5 6 7 8 9 } //Overloaded method with one argument public void add(int input1) { System.out.println("In method with one argument"); } Java Method Override: Class inheriting the method from its super class has the option to override it. Benefit of overriding is the ability to define behaviour specific to particular class. Method Overriding Example 1 2 3 4 5 public class ParentClass { public void show() { System.out.println("Show method of Super class");
  • 25. 6 7 8 9 10 11 12 13 14 15 16 } } public class SubClass extends ParentClass { //below method is overriding the ParentClass version of show method public void show() { System.out.println("Show method of Sub class"); } } Method Override Rules  Overriding method can not have more restrictive access modifier than the method being overriden but it can be less.  The argument list must exactly match that of the overriden method, if they don’t it is more likely that you are overloading the method.  Return type must be the same as, or subtype of the return type declared in overriden method in Super class.
  • 26.  Overriding method can throw any unchecked exception(Runtime)but it can throw checked exception which is broader or new than those declared by the overriden method but it can not throw fewer or narrow checked exception.  Final method can not be overriden.  Static methods can not be overriden.  If a method cannot be inherited then it cannot be overriden. HashMap HashMap is HashTable based implementation of Map. This is the reason why interviewer always ask for difference between HashMap and HashTable. HashMap is mostly equals to HashTable except below two differences. 1. HashMap is unsynchronized while HashTable is synchronised. which means hash table can be shared between multiple threads but hash map cannot be shared. 2. HashMap permits null while HashTable doesn’t.
  • 27. 3. one more diference is that because of threads safety and synchronization hash Table is mush slower than hash map if used in single thread Example of HashMap 1. How to iterate a Map 2. Different ways of iterating a Map 3. When HashCode and Equals will get called. (Pay close attention to output of HashCode and equals method call) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class HashMapExample { public static void main(String[] args) { Map<JBT, Integer> m1 = new HashMap<JBT, Integer>(); JBT t1 = new JBT(1, 2); JBT t2 = new JBT(1, 3); JBT t3 = new JBT(2, 1);
  • 28. 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 m1.put(t1, 1); m1.put(t2, 2); m1.put(t3, 3); System.out.println("Addition Done"); /* * Below you can find 3 different ways to iterate a Map. Uncomment * different section and see the different in Output. Pay attention to * when Hashcode and Equals is called */ /* Set s = m1.entrySet(); for (Iterator i = s.iterator(); i.hasNext();) { Map.Entry me = (Map.Entry) i.next(); System.out.println(me.getKey() + " : " + me.getValue()); } */ /* for (Map.Entry<JBT, Integer> entry : m1.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } */ for (Object key : m1.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + m1.get(key)); } } } class JBT { JBT(int i, int j) { this.i = i; this.j = j;
  • 29. 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 } int i, j; @Override public int hashCode() { System.out.println("Inside HashCode Method"); int k = i + j; return k; } @Override public boolean equals(Object obj) { System.out.println("Inside Equals Method"); if (i == ((JBT) obj).i && j == ((JBT) obj).j) return true; else return false; } @Override public String toString() { return String.valueOf(i).concat(String.valueOf(j)); } } Java Hashtable class o A Hashtable is an array of list.Each list is known as a bucket.The position of bucket is identified by calling the hashcode() method.A Hashtable contains values based on the key. It implements the Map interface and extends Dictionary class. o It contains only unique elements. o It may have not have any null key or value.
  • 30. o It is synchronized. Example of Hashtable: 1. import java.util.*; 2. class TestCollection16{ 3. public static void main(String args[]){ 4. 5. Hashtable<Integer,String> hm=new Hashtable<Integer,String >(); 6. 7. hm.put(100,"Amit"); 8. hm.put(102,"Ravi"); 9. hm.put(101,"Vijay"); 10. hm.put(103,"Rahul"); 11. 12. for(Map.Entry m:hm.entrySet()){ 13. System.out.println(m.getKey()+" "+m.getValue()); 14. } 15. } 16. 17. Output:103 Rahul 18. 102 Ravi 19. 101 Vijay 20. 100 Amit What is Serialization Serialization is a process in which current state of Object will be saved in stream of bytes. As byte stream create is platform
  • 31. neutral hence once objects created in one system can be deserialized in other platform. What is the use of Serialization As written above serialization will translate the Object state to Byte Streams. This B yte stream can be used for different purpose.  Write to Disk  Store in Memory  Sent byte stream to other platform over network  Save byte stream in DB(As BLOB) Serialization and Deserialization in Java Now we know what is serialization. But in terms of Java how this serialization will work and how to make a class serializable. Java has already provided out of the box way(java.io.Serializable Interface) to serialize an Object. If you
  • 32. want any class to be serialized then that class needs to implement give interface. Note*: Serializable Interface is a Marker Interface. Hence there is no method in Serializable interface. Code for Serialization of Java Class Employee.java 1 2 3 4 5 6 7 8 9 10 11 12 package com.jbt; import java.io.Serializable; public class Employee implements Serializable { public String firstName; public String lastName; private static final long serialVersionUID = 5462223600l; }
  • 33. SerializaitonClass.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package com.jbt; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializaitonClass { public static void main(String[] args) { Employee emp = new Employee(); emp.firstName = "Vivekanand"; emp.lastName = "Gautam"; try { FileOutputStream fileOut = new FileOutputStream("./employee.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(emp); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in ./employee.txt file"); } catch (IOException i) { i.printStackTrace(); } } } DeserializationClass.java
  • 34. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.jbt; import java.io.*; public class DeserializationClass { public static void main(String[] args) { Employee emp = null; try { FileInputStream fileIn = new FileInputStream("./employee.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); emp = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserializing Employee..."); System.out.println("First Name of Employee: " + emp.firstName); System.out.println("Last Name of Employee: " + emp.lastName); } } First run “SerializaitonClass” and you will get “employee.txt” file created.
  • 35. Second run “DeserializationClass” and java will deserialize the class and value will be printed in console. Output would be 1 2 3 4 5 Deserializing Employee... First Name of Employee: Vivekanand Last Name of Employee: Gautam Java Interface Creating an Interface means defining a Contract. This Contract states what a class can do without forcing how it should do. Declaring an Interface Interface can be defined with Interface keyword.
  • 36. Java Interface Example 1 2 3 4 5 6 7 public interface MyInterface { int i=0; public void Height(int height); public abstract void setHeight(); } Rules for Declaring Interface There are some rules that needs to be followed by Interface.  All Interface methods are implicitly public and abstract. Even if you write these keyword it will not create problem as you can see in second method declaration.  Interfaces can declare only Constant. Instance variables are not allowed. It means all variables inside Interface must be public, static, final. Variables inside interface are implicitly public static final.
  • 37.  Interface methods can not be static.  Interface methods can not be final, strictfp or native.  Interface can extend one or more other interface. Note: Interface can only extend other interface. Interface vs Abstract Class Interface are like 100% Abstract Class. Interface can not have non abstract methods while abstract class can have. A Class Can implement more than one interface while Class can extend only one class. As Abstract class comes in hierarchy of Classes it can extend other classes too while Interface can only extend Interfaces. Use Interface in Class How can we take the advantage of Interface after creating it in Java. To take the advantage we need to implement or class
  • 38. with given Interface. Implement keyword can be used for this purpose. Examples of Class Implementing Interface Example 1: 1 2 3 4 5 6 7 public class InterfaceExampleOne implements interfaceOne { } interface interfaceOne { } Example 2: 1 2 3 4 /* * As implmeneted Interface have any abstract method so this class * need to implement any method. */
  • 39. 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class InterfaceExampleTwo implements interfaceTwo { @Override public void methhod() { System.out.println(var); } } /* * Below interface has an abstract method so implemented class needs to * implement this method unless and untill it is abstract itself */ interface interfaceTwo { public final int var = 9; public abstract void methhod(); } Example 3: 1 /* * As below class is not abstract class and it is extending
  • 40. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 abstract class which * has not yet implemented the method from interface so this class is FORCED to * implement method from Interface in hierarachy(interfaceTwo). */ class InterfaceExampleTwo extends InterfaceExampleThree { @Override public void methhod() { System.out.println(var); } } /* * Below interface has an abstract method so implemented class needs to * implement this method unless and untill it is abstract itself */ interface interfaceTwo { public final int var = 9;
  • 41. 24 25 26 27 28 29 30 31 32 33 34 public abstract void methhod(); } /* * Even if Interface has abstract method ABSTRACT CLASS is not forced to * implement it. Abstract class may/may not navigate this responsibility of * implementing abstract method to class which is not abstract. */ abstract class InterfaceExampleThree implements interfaceTwo { // Method from Interface is not implemented here } Java Thread : Thread term can be used in two ways  An instance of class java.lang.Thread
  • 42.  A Thread of Execution An Instance of Thread is an object like any other object in Java, it contains variables and methods which lives and dies on the heap. But a Thread of Execution is an individual process which has its ownstack call. Even if you don’t create any thread in your program, thread will be running there and main() method will start that. Note: In case of thread most of thing is unpredictable. Type of Thread Thread can be of two types.  User Thread  Daemon Thread Difference between these two type of thread is that JVM exit an application only when all User Thread are complete. JVM doesn’t care about the status of Daemon Thread.
  • 43. Thread Definition A thread can be defined in two ways  Extend the java.lang.Thread class.  Implement the Runnable interface. Extending Java Thread class: Class need to extend the Thread class & Override the run()method. 1 2 3 4 5 6 7 class MyThread extends Thread { public void run() { System.out.println("Important job running in MyThread"); } } But the problem with this approach is that class can not extend any more class.
  • 44. Note : run method can be overloaded in class. but only run() method(without argument) will be consider by JVM. Any other overridden method will needs to be called explicitly. Implements runnnable interface Class needs to implement runnable interface and override the run() method. Creating Thread in this way gives you flexibility to extend any class you like. 1 2 3 4 5 6 7 class MyRunnable implements Runnable { public void run() { System.out.println("Important job running in MyRunnable"); } } Instantiating Thread : Every thread of execution begins as an instance of class Thread. In any case Thread objects needs to be created before creating Thread of Execution. Creating Thread object is different for both the cases. In case of
  • 45. Extending Thread class you can directly initiate class with new keyword as it has extended Thread class itself. 1 MyThread t = new MyThread() In case of implimenting Runnable interface. First created runnable class needs to be instatiated. 1 MyRunnable r = new MyRunnable(); Now pass this runnable object to Thread. 1 Thread t = new Thread(r); If you create a thread using the no-arg constructor, the thread will call its own run(). This happened in first case(Extending Thread class) But in case of Runnable Thread class needs to know that run method from class implementing runnnable interface needs to be invoked instead of run() from Thread class. So we need to pass the class as argument to Thread. Single runnable instance can be passed to multiple Thread object. 1 2 public class TestThreads {
  • 46. 3 4 5 6 7 8 9 10 11 12 public static void main (String [] args) { MyRunnable r = new MyRunnable(); Thread foo = new Thread(r); Thread bar = new Thread(r); Thread bat = new Thread(r); }} Giving the same target to multiple threads means that several threads of execution will be running the very same job (and that the same job will be done multiple times). Note : The Thread class itself implements Runnable. (After all, it has a run() method that we were overriding.) This means that you could pass a Thread to another Thread’s constructor. Overloaded constructor in Thread class: 1 2 Thread() Thread(Runnable target)
  • 47. 3 4 Thread(Runnable target, String name) Thread(String name) Till now we have created Thread object and it knows what to do in form of run() method. But till now it is still an object. It does not have its own call stack. In other words Thread of execution has not been started. A Thread object will have its own stack only when start() method will be called on Thread. Till now Thread has 2 states.  New state (Thread object created but Start method not invoked)  runnable(alive) state (start method is invoked ) Note : Calling run() method from java code directly mean that you are invoking a method and stack will not be created. When a Thread is in runnable state means Thread is created but it’s run method is not yet executed and thread is waiting for his turn. Once Thread got selected thread’s run method will execute and that state will called running state.
  • 48. Thread Scheduler : The thread scheduler is the part of the JVM that decides which thread should run at any given moment, and also takes threads out of the run state. Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread. If a thread is not in a runnable state, then it cannot be chosen to be the currently running thread. Some method that can influence scheduler to some extent(Note*: We can’t control the behavior of Thread scheduler) These methods are from Thread class 1 2 3 4 * public static void sleep(long millis) throws InterruptedException * public static void yield() * public final void join() throws InterruptedException * public final void setPriority(int newPriority) Methods from Object class. 1 2 3 * public final void wait() throws InterruptedException * public final void notify() * public final void notifyAll()
  • 49. Till now we come across 3 state of Thread  New  Runnable  Running There are some more state of thread in which Thread will not be eligible to run.  Waiting/blocked/sleeping  Dead A thread is in Dead state when its run method completed its execution. Sleeping The sleep() method is a static method of class Thread. (where it still has to beg to be the currently running thread). as it is static method only currently running Thread will sleep. Syntax would be : Thread.sleep() yield: yield method is related with the priority of Thread. It is also static method so it works only on currently running thread.
  • 50. Scheduler make it sure that If a thread enters the runnable state, and it has a higher priority than any of the threads in the pool and a higher priority than the currently running thread, the lower-priority running thread usually will be bumped back to runnable and the highest-priority thread will be chosen to run. at any given time the currently running thread usually will not have a priority that is lower than any of the threads in the pool. yield() is supposed to do is make the currently running thread head back to runnable to allow other threads of the same priority to get their turn. Join() Join is a non static method. It lets one thread “join onto the end” of another thread. If you join Thread B to Thread A Thread B will not start untill Thread A complets. Syntax : 1 2 3 Thread t = new Thread(); t.start(); t.join();
  • 51. takes the currently running thread and joins it to the end of the thread referenced by t There are several other way in which Thread can leave running state and can return to Runnable state. run methods completes a call to wait() Synchronize: It works with Lock. Lock is of two type. Static lock Non static lock Note: There is only one lock per object. Once a thread got the lock of an object no other thread can enter the synchronise block/method of given object. Only methods/block can be synchronised not variable or class. A class can have both synchronised / non synchronised method. Thread can access non synchronised block even if one Thread got the lock of give object.
  • 52. If a thread goes to sleep, it holds any locks it has. A thread can have Lock of different object at the same time. Syntax : 1 2 3 4 5 6 7 8 9 10 11 class SyncTest { public void doStuff() { System.out.println("not synchronized"); synchronized(this) { System.out.println("synchronized"); }}} Synchronised Static method : There is only one copy of the static data, so you only need one lock per class to synchronize static methods—a lock for the whole class. There is such a lock; every class loaded in Java has a corresponding instance of java.lang.Class representing
  • 53. that class. It’s that java.lang.Class instance whose lock is used to protect the static methods of the class. Syntax: 1 2 3 4 5 public static synchronized int getCount() { return count; } MyClass.class thing is called a class literal. It tells the compiler (who tells the JVM): go and find me the instance of Class that represents the class called MyClass. Note : Threads calling non-static synchronized methods in the same class will only block each other if they’re invoked using the same instance. As there is only one lock per instance. Threads calling static synchronized methods in the same class will always block each other— As there is only one lock per class.
  • 54. A static synchronized method and a non-static synchronized method will not block each other. As they need lock for different thing(Object & class) Note : join(), sleep(), yield() these methods keep locks. while wait release Lock. What are mutable objects and immutable objects? An Immutable object is a kind of object whose state cannot be modified after it is created. This is as opposed to a mutable object, which can be modified after it is created. In Java, objects are referred by references. If an object is known to be immutable, the object reference can be shared. For example, Boolean, Byte, Character, Double, Float, Integer,Lo ng, Short, and String are immutable classes in Java, but the class StringBuffer is a mutable object in addition to the immutable String. class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); str.toLower(); System.out.println(str); } } The output result is HELLO HELLO
  • 55. From the above example, the toLower() method does not impact on the original content in str. What happens is that a new String object "hello" is constructed. The toLower() method returns the new constructed String object's reference. Let's modify the above code: class Program { public static void main(String[] args) { String str = "HELLO"; System.out.println(str); String str1 = str.toLower(); System.out.println(str1); } } The output result is HELLO hello The str1 references a new String object that contains "hello". The String object's method never affects the data the String object contains, excluding the constructor. "Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, you should still limit its mutability as much as possible."