Notes of Advance Java
Notes of Advance Java
Object-oriented
Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java code can be run on multiple platforms e.g. Windows, Linux, Sun
Solaris, Mac/OS etc. Java code is compiled by the compiler and converted
into bytecode. This bytecode is a platform-independent code because it can
be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).
Secured
These security are provided by java language. Some security can also be
provided by application developer through SSL, JAAS, Cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There
are lack of pointers that avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking mechanism
in java. All these points makes java robust.
Architecture-neutral
Portable
High-performance
Java is faster than traditional interpretation since byte code is "close" to
native code still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the
methods from any machine on the internet.
Multi-threaded
C++ vs Java
Pointers C++ supports pointers. You Java supports pointer internally. But
can write pointer program you can't write the pointer program
in C++. in java. It means java has restricted
pointer support in java.
Compiler and C++ uses compiler only. Java uses compiler and interpreter
Interpreter both.
Call by Value and C++ supports both call by Java supports call by value only.
Call by reference value and call by reference. There is no call by reference in java.
Structure and C++ supports structures Java doesn't support structures and
Union and unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It
relies on third-party
libraries for thread support.
Virtual Keyword C++ supports virtual Java has no virtual keyword. We can
keyword so that we can override all non-static methods by
decide whether or not default. In other words, non-static
override a function. methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same like
>> operator.
Inheritance Tree C++ creates a new Java uses single inheritance tree
inheritance tree always. always because all classes are the
child of Object class in java. Object
class is the root of inheritance tree in
java.
Creating hello java example
Let's create the hello java program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To compile the above program, execute the compiler JAVAC , specifying the name of
source file on command line as in:
The javac compiler creates a file called Example.class that contains a bytecode version
of the program. Java Bytecode is a intermediate representation of program that contains
instructions JVM will execute. Thus, output of javac is nor code that can be directly
executed.
To run the program, you must use command line argument as in:
Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
Interpreter: read bytecode stream then execute the instructions.
Q) Can you save a java source file by other name than the class
name?
Yes, if the class is not public. It is explained in the figure given below:
o Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It
physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
VARIABLES:
Variable is a name of memory location.
Variable
1. int data=50;//Here data is variable
Types of Variable
1) Local Variable
A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
3) Static variable
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
OPERATORS:
There are many types of operators in java which are given below:
o Unary Operator,
o Arithmetic Operator,
o shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
prefix ++expr --expr +expr -expr ~
!
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive ^
OR
bitwise inclusive |
OR
logical OR ||
Ternary ternary ? :
All Operators:
class operator2
{
The bitwise & operator always checks both conditions whether first condition is true or false.
SCANNER CLASS:
PROGRAM 1:
import java.util.*;
class ScannIP
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter two nos.");
int a=s.nextInt();
int b=s.nextInt();
int c=a+b;
System.out.println("Sum:"+c);
}
}
PROGRAM 2:
import java.util.*;
class ScanIP2
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the name:");
String user=s.next();
System.out.println("Enter the age:");
int age=s.nextInt();
System.out.println(user+" "+age);
}
}
WAP to read an integer and display whether it is an even or odd using scanner class.
ARRAYS:
Array in java is index based, first element of the array is stored at 0 index.
Program 2:
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
class Testarray3{
public static void main(String args[]){
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Control Statements:
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false.
There are various types of if statement in java.
if statement
if-else statement
nested if statement
if-else-if ladder
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
if statement in java
Example:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Java IF-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else statement in java
Example:
odd number
Java IF-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
if-else-if ladder statement in java
Example:
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
flow of switch statement in java
Example:
The java switch statement is fall-through. It means it executes all statement after first match if
break statement is not used with switch cases.
Example:
The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop.
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
}
for loop in java flowchart
Example:
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
Syntax:
while(condition){
//code to be executed
}
flowchart of java while loop
Example:
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}
Example:
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
flowchart of do while loop in java
Example:
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Example:
The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;
java break statement flowchart
Java Break Statement with Loop
Example:
It breaks inner loop only if you use break statement inside the inner loop.
Example:
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it continues
only inner loop.
Syntax:
jump-statement;
continue;
Java Continue Statement Example
Example:
In this example, we have created a Student class that have two data members id and name. We
are creating the object of the Student class by new keyword and printing the objects value.
File: Student.java
class Student{
int id;//field or data member or instance variable
String name;
In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main() method in
another class.
We can have multiple classes in different java files or single java file. If you define multiple
classes in a single java source file, it is a good idea to save the file name with the class name
which has main() method.
File: TestStudent1.java
class Student{
int id;
String name;
}
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
3 Ways to initialize object
By reference variable
By method
By constructor
1) Object and Class Example: Initialization through reference
Initializing object simply means storing data into object. Let's see a simple example where we
are going to initialize object through reference variable.
File: TestStudent2.java
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
File: TestStudent3.java
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
3) Object and Class Example: Initialization through constructor
File: TestEmployee.java
class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}
INHERITANCE:
The idea behind inheritance in java is that you can create new classes that
are built upon existing classes. When you inherit from an existing class, you
can reuse methods and fields of parent class, and you can add new methods
and fields also.
The extends keyword indicates that you are making a new class that derives
from an existing class. The meaning of "extends" is to increase the
functionality.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
When a class extends multiple classes i.e. known as multiple inheritance. For
Example:
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
class TestInheritance{
d.bark();
d.eat();
}}
Multilevel Inheritance Example
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A
and B classes have same method and you call it from child class object, there will be ambiguity
to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
1. abstract class A{}
1. abstract void printStatus();//no method body and abstract
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
EXAMPLE 2:
In this program,
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape
() method
s.draw();
}
}
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Interface in Java
An Interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
Syntax:
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The Java compiler adds public and abstract keywords before the interface method. Moreover, it
adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
2nd PROGRAM:
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}
Q) Multiple inheritance is not supported through class in java, but
it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation
class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Interface inheritance
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
EXCEPTION HANDLING:
The exception handling in java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of
the application. Exception normally disrupts the normal flow of the
application that is why we use exception handling. Let's take a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
1. Checked Exception
2. Unchecked Exception
3. Error
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Keywor Description
d
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the important code of the program. It
is executed whether an exception is handled or not.
Java try block is used to enclose the code that might throw an exception. It must be used within
the method.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
Java catch block is used to handle the Exception. It must be used after the
try block only.
1. int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException
If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.
class TestMultipleCatchBlock1{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output: Error
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Java nested try example
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
Java finally block
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Test it Now
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
By the help of custom exception, you can have your own exception and message.
MULTITHREADING:
1) It doesn't block the user because threads are independent and you can
perform multiple operations at same time.
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5
states.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to
run.
5) Terminated
Thread class:
Thread class provide constructors and methods to create and perform
operations on a thread.Thread class extends Object class and implements
Runnable interface.
Runnable interface:
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface
have only one method named run().
1. public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It
performs following tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method
will run.
1) Java Thread Example by extending Thread class
Thread scheduler in java is the part of the JVM that decides which thread
should run.
There is no guarantee that which runnable thread will be chosen to run by
the thread scheduler.
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
t1.start();
t2.start();
}
}
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}