Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 121

Introduction to java

• What is programming language?


• Why in the computer we have 2 types of memory?
• How the c file is get executed?
• Difference between compiler and interpreter?
• What is platform?
• How java program get executed?
• Which is best c or java?
• What is JRE?
• Java’s architecture ? jdk?
• What is WORA concept?
John backus(1957) FORTRAN-formula HLL Less operations,
translation Unstructured
Grace hopper(1959) COBOL-common HLL, unstructured
business oriented more operator
lang

Mortin ritchards BCPL- basic HLL, Occupies More


(1962) combined more operations, memory
programming Structred
language
Ken thompson B Less memory Typeless PL
(1969)
Dennis ritchie(1972) c Typed PL Not oop lang
Bjarne Stroustrup(1982) C++ Oop lang Not
portable/platform
dependent
Green team -11 C++++-- , green PL , Platform
members (1985-1995) oak independent
What is Java?

Java was developed by Sun


Microsystems (which is now the subsidiary of
Oracle) in the year 1995.
 James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was
already a registered company, so they
changed it as Java.
Application of Java
It is used for:
• Mobile applications (specially Android apps) :
Netflix,tinder,google earth,uber
• Desktop applications :
acrobat reader, thinkfree
• Web applications :
amazon,broad lead,wayfair
• Enterprise application :
enterprise resource planning systems(ERP)
• Scientific application :
matlab
• Gaming application
• Database connection
• Business application
• Web servers and application servers :
tomcat
Features of java
• Simple –Easy to understand
• Open source –free
• Object oriented
• Platform independent
• Portable-Ability to run on different Systems
• Secure and Distributed
• Multithreaded
• Robust
• High performance
• Compiled and then interpreted
Types of Java
• Java SE (Java Standard Edition) - It is a Java
programming platform.
• Java EE (Java Enterprise Edition) - used to
develop web and enterprise applications.
• Java ME (Java Micro Edition) - used to develop
mobile applications.
• JavaFX - It is used to develop rich internet
applications. It uses a light-weight user interface
API(application programming interface).
OOP’S Concept
Class
Objects
Data encapsulation
Data abstraction
Inheritance
Polymorphism
Dynamic binding
Objects:
• An Object can be defined as an instance of a class
•  A Java object is a combination of data and procedures
working on the available data.
• An object has a state and behavior. The state of an object is
stored in fields (variables), while methods (functions) display
the object's behavior.
• Objects are created from templates known as classes
Creating Objects
The new keyword is used to create object
Syntax:
Classname objectname=new Classname
Class:
 Collection of objects is called class.
Local inner class:
class outer{
void outermeth(){
class inner{
void innermeth()
{ System.out.println("inner
display"); } } inner obj=new inner();
obj.innermeth();}}
public class Main{
public static void main(String[] args) { outer
obj1=new outer(); obj1.outermeth(); }}
Innerclass:
class outer{ int a=12;
class inner{ int b=23;
void innermeth(){
System.out.println("a "+a); System.out.println("b "+b);
} }
void outermeth(){
inner i=new inner();
i.innermeth();
System.out.println("b ---"+i.b); }}
public class Main{ public static void main(String[] args) { outer
obj=new outer(); obj.outermeth();
outer.inner obj1=new outer().new inner();
obj1.innermeth(); }}
Comment statement

•Comments within source code exist for the


convenience of human programmers.
•There are two kinds of comments:
• // comment
• /* comment */
Data types in java
1. Primitive data type/standard data
types
2. Non primitive data type/derived
data types
datatype Size range
byte 8 bit -128 to 127
short 16 bit -32768 to 32767
int 32bit -2^31to 2^ 31-1
long 64 bit -2^63 to 2^63-1
float 32 bit +/- about 10^39
double 64 bit +/- about 10^ 317
char 16 bit
boolean 8 bit
Non primitive data type
• Class, object, array, string, and
interface are called non-primitive
data types in Java.
• These data types are not predefined
in Java.
• They are created by programmers.
Type casting
• One type of data is getting converted into
another type of data.
1.Implicit type casting or widening
2.Explicit type casting or narrowing
Control statements in
java
If statement
•  if statement to specify a block of Java code to
be executed if a condition is true.
Syntax:
• if (condition) {
// block of code to be executed if the condition is
true }
If else statement
• else statement to specify a block of code to be
executed if the condition is false.
• Syntax:
if (condition) {
// block of code to be executed if the condition is true}
else {
// block of code to be executed if the condition is false
}
Else if statement
• else if statement to specify a new condition if the first condition
is false.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is true } else if
(condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true }
else {
// block of code to be executed if the condition1 is false and
condition2 is false }
Ternary Operator

• There is also a shortened if else, which is known as


the ternary operator because it consists of three
operands
Syntax:
variable = (condition) ? expressionTrue : expressionFalse;
Example :
• int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
switch statement
• switch statement to select one of many code blocks to be
executed.
• Syntax
switch(expression) {
case x:
// code block break;
case y:
// code block break;
default:
// code block }
•int day = 4;
switch (day) {
case 1: System.out.println("Monday");
break;
case 2:System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break; }
// Outputs "Thursday" (day 4)
while loop
• The while loop loops through a block of code as long as a
specified condition is true:
Syntax:
while (condition) {
// code block to be executed }
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++; }
The Do/While Loop
• this loop will execute the code block once, before
checking if the condition is true.
Syntax
do {
// code block to be executed
} while (condition);
Example
int i = 0;
do { System.out.println(i);
i++; }
while (i < 5);
for loop
• When you know exactly how many times you want
to loop through a block of code, use the for loop
• Syntax
for (initialization; condition; incre/decrement) {
// code block to be executed }
example  
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i); }
break statement
• public class Main{
• public static void main(String[] args) {
for(int i=0;i<10;i++){
• if(i==5){
• continue; }
• else if(i==8){ break; } else{
• System.out.println(i); } } }}
Types of operators
Unary operator- (post incre/decre)(pre incre/decre)
Arithmetic – (+ , - , * , / , % )
Relational operator – (< , > ,<= ,>= ,== ,!=)
Bitwise operator – (& ,| , ^)
Logical – (&& ,||)
Ternary operator –( ? :)
Assignment –( =,+=,-=,&=,|=,^=)
Array
• An array is a collection of similar type of
elements which has contiguous memory
location.
Types of Array
• Single Dimensional Array
• Multidimensional Array
Syntax:
• Datatype arrayname[ ]=new datatype[ ];
Single dimensional array
int a[]=new int[5];//declaration and instantiation  
a[0]=10;//initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;    
for(int i=0;i<a.length();i++)
System.out.println(a[i]);  
Multi dimensional array

class Testarray3{  
public static void main(String args[]){  
//declaring and initializing 2D array  
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
//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();  
}   } }  
Java modifiers
Access
non –access modifiers
Access modifiers:
 Public –access within its own and other
package
 Private-access with in the class
 Protected-access within a package and
subclasses
 Default-with in a package
Non access modifiers
• final -we can use class, variable, method ,object.
• static-we can use class, variable ,method ,object.
• abstract - we can use class, variable, method.
• Synchronized -it is used in threads
Variables
• Variables are memory locations which are
reserved to store values.
1.Local variable – inside the method.static
keyword(cant)
2.Instance variable – inside the class outside the
method.
3.static variable – using static keyword
Constructor
• Constructor is used in the creation of an object
• It is the block of code used to initialize an
object
• Constructor gets executed when an object of a
class is being created
• A constructor always has the same name as the
class name
• Constructor doesn’t have any return type
constructor method

• Constructor must not have • Method must have return


return type type
• Constructor name must be • Method name must not be
same as the class same
• Constructor is used to • Method is used to expose
initialize the state of an the behavior of an object
object • Method is not invoked
• Constructor is invoked implicitly
implicitly
//
Java Program to create and call a default construct
or  
class Bike1{  
//creating a default constructor  
Bike1( ){
System.out.println("Bike is created");}  
//main method  
public static void main(String args[]){  
//calling a default constructor  
Bike1 b=new Bike1();  }  }  
Parameterized constructor
class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
    id = i;  
    name = n;  }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");   
    s1.display();  
    s2.display();   }  }  
keywords

• Keywords have special meaning within the


programming language. Here is the list of keywords:
1. Abstract 8.final
2. Boolean 9.if
3. do 10.double
4. Break 11.long
5. Byte 12.int
6. Char 13.interface
7. Class 14.import
Strings in java
 string is basically an object that represents
sequence of char values.
 String is immutable.
 Multiple thread can access the same
string ,since its immutable . Thread safe.
How to create String
• String s="welcome";  
• String s=new String("Welcome");
• Char a[]={‘p’,’r’,’I’}
String pool

• String pool is a pool of string which is stored in


javas heap memory.
• String pool is possible only because strings are
immutable
• Once it created it cant be change
String s1="java v";
Char ch[]={‘c’,’a’,’t’};
String s2=new String(ch);
System.out.println(s1.concat(“ course”));
System.out.println(s1.compareto(s2));  //false
System.out.println(s1.isempty());  //false
System.out.println(s1.substring(2));//va 
System.out.println(s1.length());
Int a=50;
a+3;//53
String s=String.valueOf(a)  
System.out.println(s+3);//503
String r=s1.replace(‘d’,’I’);
System.out.println(r);
System.out.println(r.contains(“d”));//false
S.o.p(s1.charAt(3));//returns the index value
System.out.println(s1.endswith(“u”));//false
• toCharArray() ---- Used to convert String to characters
• equalsIgnoreCase() ---- Used to compare two strings
Ignoring Case
• indexOf() ---- Used to find out the index of the given String
• lastIndexOf() ---- Used to find out the last index of given
String
• replace() ---- Used to replace a particular String in given
String
• trim() ---- Used to remove the white spaces20
• Package xya;
• public class Sample {

• public static void main(String []args)


• {
• Integer a=12;
• String b="python";
• System.out.println(a.toString());
• System.out.println(b.startsWith("p"));
• System.out.println(b.toCharArray());
• System.out.println(b.getBytes());}
• }
String example-1

• public class Main{


• public static void main(String[] args) { char
chars[]={'a','b','c','d','e','f','g'};
• String s=new String(chars);
• System.out.println(s);
• String s1=new String(chars,2,5);
• System.out.println(s1);
• String n="1003";
• System.out.println(12+n);
• String s4="The Employee number is "+ n ;
• System.out.println(
• "String Concatenation:"+" "+s4);}}
String example-2
public class Main{
public static void main(String[] args) {
char ch; ch="abcd".charAt(1);
System.out.println(ch);
String s="This is a demo of the getChars method";
int start=10, end=14;
char buf[]=new char[end-start];
s.getChars(start, end, buf, 0); System.out.println(buf);
String s1="This is demo of the getChars method.";
String s2="THIS IS DEMO OF THE GETCHARS METHOD.";
System.out.println("s is equal to s1:"+s.equals(s1));
• System.out.println("s1 is equal to s2:"+s1.equals(s2));
• System.out.println("s1 is equal to s2:“ +
s1.equalsIgnoreCase(s2));
System.out.println("StartsWith:"+s1.startsWith("This"
));
System.out.println("EndsWith:"+s1.endsWith("thod."
)); System.out.println("IndexOf:"+s1.indexOf("o"));
String s3="hello".replace('l','w');
System.out.println(s3);
• String s4=" hello world " .trim();
• System.out.println(s4);
System.out.println(s2.toLowerCase());
System.out.println(s.toUpperCase());}}
String buffer class
• Java String buffer is used to create mutable
string.
• Memory allocated to a string is not fixed , it
can change.
• It is synchronous in nature .thread safe
StringBuffer s=new StringBuffer(“live wire”);
S.o.p(s);//live wire
s.append(“salem ”); S.o.p(s);
S.insert(0,’w’);
System.out.println(s);
S.replace(0,3,”hire”);
System.out.println(s);
S.delete(0,2);
System.out.println(s.reverse());
System.out.println(s.capacity());
• length()-Used to find out the length of a given String.
• capacity()- Used to find out total allocated capacity of
the buffer ensure
• ensureCapacity() -Used to set the size of the buffer
•setLength() - Used to set the length of the buffer within
a StringBuffer object
•charAT()- Used to obtain a single character value from
a StringBuffer
•setCharAt() -Used to set the value of character within
a StringBuffer
•getChars()- Used to copy a substring of a StringBuffer
into an array
String buffer example
• public class StringBufferDemo
• {
• public static void main(String args[])
• {
• StringBuffer sb=new StringBuffer("hello");
• System.out.println("buffer before= "+sb);
• System.out.println("length"+sb.length());
• System.out.println("Capacity"+sb.capacity());
• StringBuffer ss=new StringBuffer("My India");
• ss.ensureCapacity(30);
• System.out.println(ss.capacity());
• System.out.println("charAt(1) before="+sb.charAt(1));
• sb.setCharAt(1,'I');
• sb.setLength(2);
• System.out.println("buffer after"+sb);
• System.out.println("charAt(1)before="+sb.charAt(1));
• String s;
• int a=14;
• StringBuffer sss=new StringBuffer(44);
• s=sss.append(a).append("!").toString();
• System.out.println(s);
• }}
String Builder
• The java stringBuilder class is used to create
mutable string.
• But, String builder class is non synchronized
i.e.it is not thread safe.
• Therefore string builder is faster than string
buffer.
• StringBuilder s=new StringBuilder(“java”);
• System.out.println(s);
StringBuilder sb=new StringBuilder(“I India!”);
sb.insert(2,”love”);
System.out.println(sb);
S.o.p(sb.reverse());
StringBuffer ss=new StringBuffer(“This is a
test”); S.o.p(ss.delete(3,7));
S.o.p(ss.deleteCharAt(0));
StringBuffer a=new StringBuffer(“This is a
test”); S.o.p(a.replace(5,7,”was”));
S.o.p(s.insert(1,”welcome”));//Iwelcome
india
When to use string buffer and string builder

• String buffer –String buffer can be accessed by


multiple threads at a time.
• Slower as compared to string builder.
• String builder – string builder can be accessed
by a single thread at a time.
• Faster than sting buffer.
Object oriented
programming concepts
Java Inheritance

• In Java, it is possible to inherit attributes and methods


from one class to another. We group the "inheritance
concept" into two categories:
• subclass (child) - the class that inherits from another
class
• superclass (parent) - the class being inherited from
• the extends keyword.
• For Method Overriding (so runtime polymorphism can
be achieved).
• For Code Reusability.
Inheritance
Inheritance
Polymorphism

Types:
1.Compile time polymorphism(overloading)
2.Run time polymorphism(overriding)
Types of overloading:
1.Constructor overloading
2.Method overloading
Method overloading
method name same for all and different parameter
Example:
class testadd{
void sum(int a,int b){
System.out.println(a+b);}
void sum(int c,int d,int e){
System.out.println(c+d+e);
}}
public class JavaApplication5{
public static void main(String args[]){
testadd obj=new testadd();
obj.sum(10, 10);
obj.sum(10, 20, 30); } }
Constructor overloading
Class s{
s(){
s.o.p(“default”);}
s(int x,float y);{
s.o.p(“x= “+x);
s.o.p(“y= “+y);
}
s(float a,int b){
s.o.p(“a =“+a);
s.o.p(“b= ”+b);
}}
Public class java{
p.s.v.m(){
s obj1=new s();
s obj2=new s(5,10.5f);
s obj3=new s(10.5f,3);
Method overriding
• Method overriding must be used in case of
inheritance.
• Method must have the same name as in
parent class
• Method must have the same parameters as in
parent class.
Over riding
Same name with same parameter
Class A{
Void msg(){
System.out.println(“hello”);}
Class B{
Void msg(){
System.out.println(“welcome”);}
Class C extends B{
Public static void main(String args[]){
C obj=new C();
Obj.msg();//now which msg()method would be invoked?
Super keyword
• It is a reference variable that is used to refer
parent class objects
• parent class instance variable
• Used to invoke parent class method
• Used to invoke parent class constructor
class tree1{
String fruits="I have 2 fruits";
}
class tree2 extends tree1{
String fruits="I have 2 leaves";
void printfruits(){
System.out.println(fruits);//prints fruits of tree2
System.out.println(super.fruits);//prints fruits of tree1}}
public class JavaApplication5 {
public static void main(String args[]){
tree2 obj=new tree2();
obj.printfruits();}}
Java final keyword
class Bike9{  
 final int speedlimit=90   
 void run(){  
  speedlimit=400;  }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  }
This keyword
In Java, this is a reference variable 
that refers to the current object.
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
• public class example{
• int a=12;
• void display() {
• int a=34;
• System.out.println(this.a);
• }
• public static void main(String args[]) {
• example obj=new example();
• obj.display();
• }
• }
binding in java
• Connecting a method call to the method
body is known as binding.
• Static Binding (also known as Early
• Binding) – when type of the object is
determined at compiled time
• Dynamic Binding (also known as Late Binding)
– when type of the object is determined at run
time
Static binding
If there is any private, final or static method in a
class, there is static binding.
Example:
class Dog{  
 private void eat()
{System.out.println("dog is eating...");}  
  public static void main(String args[]){  
  Dog d1=new Dog();  
  d1.eat();  }  }  
Dynamic binding
class Animal{  
 void eat()
{System.out.println("animal is eating...");}  }  
class Dog extends Animal{  
 void eat()
{System.out.println("dog is eating...");}  
  
 public static void main(String args[]){  
  Animal a=new Dog();  
  a.eat();  }  }  //dog is eating
Abstraction
• Hiding implementation details .only providing
the functionality to the user.
• Abstraction lets you focus on what the object
does instead of how it does it.
• There are two ways to achieve abstraction in
java
• Abstract class(0 to 100% abstraction)
• Interface(100% abstraction)
Abstract class
• A class which is declared as abstract is known as an abstract
class.
• It can have abstract and non-abstract methods.
• It needs to be extended and its method implemented. It
cannot be instantiated
Syntax:
abstract class a{
Abstract method();}
Class b extends class a{
Public method(){ }}
Abstract method
• A method which is declared as abstract and
does not have implementation is known as an
abstract method.
abstract class a{
abstract void fun();
void display(){
System.out.println("abstract a");}
}
class b extends a{
public void fun(){
System.out.println("functions");}}
public class example{
public static void main(String args[]){
b obj=new b();
obj.display();
obj.fun();
}}
Encapsulation
• Encapsulation is the methodology of binding
code and data together into single unit.
• To achieve encapsulation in java:
• Declare the variables of a class as private

• Abstraction+datahiding
Interface
The interface in Java is a mechanism to
achieve abstraction.
There can be only abstract methods in the Java
interface, not method body.
Uses of interface:
• It is used to achieve abstraction.
• By interface, we can support the functionality
of multiple inheritance.
• Class to class  extends
• class to interface  implements
• Interface to interface  extends
Interface transactionl{
Void withdrawamt(int amtTowithdraw);}
Class Transactionlmpl implements transactional{
Void withdrawamt(int amtTowithdraw){
//logic of withdraw
}}
//Amazon side
Transactionl ti=new transactionlmpl();
Ti.withdrawamt(500);
• Syntax
Interface interface-name
{
Method declaration;
}
Class classname implements interfacename{ }
Example-1
interface a{
void setdata(int x);}
interface b{
void getdata();}
public class sbi implements a,b{
static int c;
public void setdata(int x){
c=x;
System.out.println(c);
}
public void getdata(){
System.out.println(c); }
public static void main(String args[]){
sbi s=new sbi();
s.setdata(12);
s.getdata();}}
interface a{
void display1();}
interface b extends a{
void display2();}
public class sbi implements b {
public void display1(){
System.out.println("interface a");}
public void display2(){
System.out.println("interface b");}
void display(){
System.out.println("sbi class ");}
public static void main(String[] args) {
sbi s=new sbi();
s.display1();
s.display2();
s.display(); }}
Assertion
 Assertion is a statement in java. It can be used to
test your assumptions about the program.
 While executing assertion, it is believed to be
true. If it fails, JVM will throw an error named
Assertion Error. It is mainly used for testing
purpose
Syntax:
1. assert expression;
2. assert expression1 : expression2; 
import java.util.Scanner;  
    class AssertionExample{  
 public static void main( String args[] ){  
  Scanner scanner = new Scanner( System.in );  
  System.out.print("Enter your age ");  
    int value = scanner.nextInt();  
  assert value>=18:" Not valid";  
  System.out.println("value is "+value);  } }  
Exception
Handling

1
Exception
Handling
Exceptionisaproblemthatarise during the execution time
Anabnormaleventwhichstopstheprogram abruptly.
Errors:
• unpredictable
• Errors are of unchecked type
• Happen at run time
• Caused by the environment on which application is running
• Eg : out of memory error.
Exception:
• Predictable
• It can be of checked or unchecked
• Can happen at compile time & runtime
• Caused by application
Checked exception:
• An exception that is checked by the compiler at compilation
time.
• These exceptions cannot simply be ignored , the programmer
should handle these exceptions.
Unchecked exceptions:
• Runtime exception is the superclass of those exceptions that
can be thrown during the normal operation of the jvm.
• Runtime exception and its subclasses are unchecked
exceptions.
Exception handling
• Exception handling is a mechanism to handle errors in the
runtime
• So that the normal flow of the application is maintained
Keywords for Exception Handling
1.Try 2.Catch 3.Finally 4.Throw 5.Throws
Throw:
• Used to explicitly throw an exception
• Checked exceptions cannot be propagated using throw only.
• Followed by an instance
• Cannot throw multiple exceptions
Throws:
• Used to declare an exception
• Checked exceptions can be propagated
• Followed by a class
• Used with a method signature
• Can declare multiple exceptions
• Final –keyword
• Applies restrictions on class , methods and variable.
• Final class cant be inherited , method cant be overridden &the
variable value cant be changed
• Finally-block
• Used to place an important code
• It will be executed whether the exception is handled or not
• Finalize-method
• Used to perform clean up processing just before the object is
garbage collected
Exception Handling using throw

class Test{
static void avg() {
int a=10,b=0,c;
try {
c=a/b;
System.out.println(c);
throw new
ArithmeticException("d
emo");}
catch(ArithmeticException e)
{ System.out.println("Exception caught");
}}
public static void main(String args[]) {
avg(); }}
Exception Handling using try ,catch, finally

class ExceptionTest{
public static void main(String …as){ try{
Int a=10,b=0,c;
C=a/b;
System.out.println(c);}
catch(Exception e)
{ System.out.println(e);}
finally{
System.out.println(“am from
finally”);
}}}
Exception Handling using throws

class Test1{
static void check() throws Exception {
int a=10,b=0,c;
c=a/b; System.out.println(c);
System.out.println("Inside check
function");
}
public static void main(String args[]) {
try {
check();
}
catch(ArithmeticException e)
{ System.out.println("caught" + e); } }}
Types of exceptions
• Built in exception
• User defined exception
• Built in exceptions:
• Arithmetic exception
• Array index out of bound exception
• Class not found exception
• Io exception
• Interrupt exception
• No such field exception
• No such method exception
• Number format exception
• Runtime exception
• String index out of bounds exception
User defined

• class MyException extends Exception{


• }
• public class Main{
• public static void main(String args[]) {
• try {
• throw new MyException(); }
• catch (MyException ex)
• {
• System.out.println("Caught");
• System.out.println(ex.getMessage());
• } }}
Thread

9
THREAD AND MULTITHREADING
Thread: Definition
• A Thread is similar to a Sequential program. Collection of thread
is called as process.
• It is a part of execution
• A thread is not a program on its own but runs within a
program.
• Every program has at least one thread that is called the Primary
Thread.
• We can create more threads when necessary.
• Threads are very useful when you have large computations that
take several seconds to complete, and the user should not
perceive the delay.
• Animation is another area where threads are used.
• A thread is also known as a lightweight process or execution
context.
Example
• Most computer games use graphics and sound.
• The graphics and audio go on simultaneously.
• A single game has all these elements being processed at the same
time.
• In other words, the program has been divided into three sub units,
each sub units handled by a thread. The microprocessor allocates
memory to the processes that
you execute.
• Each process occupies its own address space (memory).
• However, all the threads in a process share the same address
space.
• Resources like memory, devices, data of a program, and
environment of a program are
available to all the threads of that program.
Multitasking

Process based
Thread based
Process based
Collection of
thread is
known Tas
process.
T Process
T
T
Thread based

Individual thread working on a single


program.
Multithreading

• Java is a multithreaded programming language which means we can develop


multithreaded programs using Java.
• A multithreaded program contains two or more parts that can run concurrently and
each part can handle different task at the same time making optimal use of the
available resources, especially when your computer has multiple CPUs.
• By definition multitasking is when multiple processes share common processing
resources such as a CPU.
• Multithreading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads.
• Each of the threads can run in parallel.
• The OS divides processing time not only among different applications, but also
among each thread within an application.
Life Cycle of a Thread
• A thread goes through various stages in its life
cycle.
• For example, a thread is born, started, it runs, and
then dies.

init->start->Runnable->Not Runnable->Dead

Above-mentioned stages are explained here:


• init: A new thread begins its life cycle in the init
state.
It remains in this state until the program starts
the thread. It is also referred to as a born
thread.
• Runnable: After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while
the thread waits for another thread to perform a task.
A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue
executing.

• Not Runnable: A runnable thread can enter the timed


waiting state for a specified interval of time.
A thread in this state transitions back to the runnable state
when that time interval expires or when the event it is
waiting for occurs.

• Terminated (Dead): A runnable thread enters the terminated


state when it completes its
Thread Priorities
• Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
• Java thread priorities are in the range between MIN_PRIORITY (a
constant of 1) and MAX_PRIORITY (a constant of 10).
• By default, every thread is given NORM_PRIORITY (a constant of
5).
• Threads with higher priority are more important to a program
and should be allocated processor time before lower-priority
threads.
• However, thread priorities cannot guarantee the order in which
threads execute and are very much platform dependent.

Create Thread by Implementing Runnable Interface:


• If your class is intended to be executed as a Thread then you
can achieve this by implementing Runnable interface.
class a implements Runnable {
private Thread t;
private String threadName;
a( String name){
threadName = name;
System.out.println(“Creating “ + threadName ); }
public void run() {
System.out.println(“Running “ + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println(“Thread: “ + threadName + “, “ + i);
// Let the thread sleep for a while.
Thread.sleep(50); }}
Thread by Runnable
catch (InterruptedException e) {
System.out.println(“Thread “ + threadName + “ interrupted.”);}
System.out.println(“Thread “ + threadName + “ exiting.”);
}
public void start (){
System.out.println(“Starting “ + threadName ); if (t ==
null){
t = new Thread (this, threadName);
t.start(); }
}}
public class TestThread {
public static void main(String args[]) {
a R1 = new a( “Thread-1”); R1.start();
a R2 = new a( “Thread-2”); R2.start();
}}
Create Thread by Extending Thread Class:

• The second way to create a thread is to create a new class that extends
Thread class using the following two simple steps.
• This approach provides more flexibility in handling multiple threads created
using available methods in Thread class.
Step 1:
• You will need to override run( ) method available in Thread class.
• This method provides entry point for the thread and you will put your
complete
business logic inside this method. Following is the simple syntax of run()
method: public void run( )
Step 2:
• Once Thread object is created, you can start it by calling start( ) method,
which executes a call to run( ) method. Following is the simple syntax of
start() method:
SYNTAX
void start( );
join method

• public class example {


• public static void main(String []args){
• ThreadDemo obj1=new ThreadDemo("thread -1");
• ThreadDemo obj2=new ThreadDemo("thread-2");
• obj1.start();
• try{
• obj1.join(5000);
• }
• catch(Exception e){
• }
• obj2.start();}}
• package javaapplication;
• public class javaapplication extends Thread{
• public void run() {
• System.out.println("running "+Thread.currentThread());
• try {for(int i=0;i<5;i++) {
• System.out.println(i);
• Thread.sleep(10);}}
• catch(Exception e) {
• System.out.println(e);}}
• public static void main(String[] args) {
• javaapplication obj1=new javaapplication();
• javaapplication obj2 =new javaapplication();
• obj1.start();obj2.start();
• System.out.println(Thread.currentThread().getNa
me());
• System.out.println("before setname
"+obj1.getName());
• System.out.println(obj2.getName());
• obj1.setName("thread");
• obj2.setName("thread 2");
• System.out.println("after set name");
• System.out.println(obj1.getName());
• System.out.println(obj2.getName());}}
Priorities

• package javaapplication;
• public class javaapplication extends Thread{
• public void run() {
• System.out.println("running "+Thread.currentThread().getName());
• System.out.println("priority "+Thread.currentThread().getPriority());
• }
• public static void main(String[] args) {
• javaapplication obj1=new javaapplication();
• javaapplication obj2 =new javaapplication();
• obj1.setPriority(Thread.MAX_PRIORITY);
• obj2.setPriority(Thread.MIN_PRIORITY);
• obj1.start();
• obj2.start();
• }}
Daemon Thread

• Daemon thread is a low priority thread that runs in background to perform tasks
such as garbage collection.
• package javaapplication;
• public class example extends Thread{
• public void run() {
• if(Thread.currentThread().isDaemon()) {
• System.out.println("daemonThread "+Thread.currentThread().getName());}
• else {
• System.out.println("user Thread "+Thread.currentThread().getName());}}
• public static void main(String[] args) {
• example t1=new example();
• example t2=new example();
• t1.setDaemon(true);
• t1.start();
• t2.start();}}
Garbage collection
• Garbage collection is a process of reclaiming the runtime unused
memory automatically.
• Its way to destroy unused objects
• Advantages : memory is efficient because garbage collector removes
the unrefferd object for, heap memory.
• It is automatically done so we don’t need to take extra efforts
• It contains finalize method by default
• Garbage collector removes the object which is created by “new”
keyword
• Finalize method is used to remove the object which is not created by
“new” keyword.
• Finalize method is automatically invoked each time before the object
is garbage collector.
• Garbage collector is a daemon thread
Garbage collection

• package javaapplication;
• public class example {
• void print() {
• System.out.println("hello");
• }
• public void finalize() {
• System.out.println("garbage collection");
• }
• public static void main(String args[]) {
• example e1=new example();
• example e2=new example();
• e1.print();
• e2=null;
• System.gc();}}
synchronization

• Synchronization block
• Synchronization method
• Static synchronization no need for object creation
• package javaapplication;
• class example extends Thread{
• synchronized public void run() {
• for(int i=0;i<5;i++) {
• int a=2;
• System.out.println(a+" "+i+" "+a*i);
• }}
• public static void main(String args[]) {
• example e=new example();
• example e1=new example();
• e.start();
• e1.start();}}
Packages

• Packages contains classes & interfaces & annotations and


these all are contains variables & methods & constants
• 14 predefined methods .java.lang is a default package
• Java.lang Java.io
• Java.util Java.awt
• Java.beans Java.net
• Java.applet Java.times
• Java.text Java.nio
• Java.rmi Java.sql
• Java.math Java.security
Framework hierarchy
UTIL
PACKAGE

You might also like