Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views84 pages

Unit - III

The document covers key concepts related to arrays and strings in Java, including array declaration, initialization, and operations on single and multidimensional arrays. It also discusses the String class, its immutability, various methods for string manipulation, and the use of StringBuffer for mutable strings. Additionally, it highlights string comparison methods and provides examples for better understanding.

Uploaded by

haruoyoshida0731
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views84 pages

Unit - III

The document covers key concepts related to arrays and strings in Java, including array declaration, initialization, and operations on single and multidimensional arrays. It also discusses the String class, its immutability, various methods for string manipulation, and the use of StringBuffer for mutable strings. Additionally, it highlights string comparison methods and provides examples for better understanding.

Uploaded by

haruoyoshida0731
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

Unit III

Arrays, Strings – Interfaces: Multiple Inheritance –


Packages: Putting Classes together – Multithreaded Programming
Arrays
• Collection of similar data types
• Static data structure - size of an array must be specified at the time of
its declaration
• Array starts from zero index and goes to n-1 where n is length of the
array
• treated as an object and stores into heap memory
• Array can be single dimensional or multidimensional
3 step process
1) Declaring your Array
2) Constructing your Array
3) Initialize your Array
Features of Array
• It is always indexed. Index begins from 0.
• It is a collection of similar data types.
• It occupies a contiguous memory location.
• It allows to access elements randomly.

• Single Dimensional Array


• use single index to store elements

Array Declaration Syntax

datatype[] arrayName;
or
datatype arrayName[];
• The arrayName can be any valid array name and datatype can be any
like: int, float, byte etc.
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr;
• Initialization of Array
• Initialization is a process of allocating memory to an array.
• At the time of initialization, we specify the size of array to reserve memory
area.

• Initialization Syntax
arrayName = new datatype[size]
• The arrayName is the name of array, new is a keyword used to allocate memory and
size is length of array.

both declaration and initialization


• Datatype[] arrayName = new datatype[size]
Example
class arraycreation {
public static void main (String[] args) {
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the elements of the array
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
• Output
• Element at index 0 : 10
• Element at index 1 : 20
• Element at index 2 : 30
• Element at index 3 : 40
• Element at index 4 : 50
Multidimensional Arrays
• array containing one or more arrays.

Example
int[][] intArray = new int[10][20];

class multiDimensional {
public static void main(String args[]) {
// declaring and initializing 2D array
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
// 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();
}
}
Addition of 2 Matrices in Java

class Testarray5{
public static void main(String args[]){
//creating matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
• Output
Compile by: javac Testarray5.java
Run by: java Testarray5
268
6 8 10
Matrix multiplication
Example
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++) {
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}
Output
String

• string is an object that represents sequence of char values.


Declaration
char[] ch={'j','a','v','a'};

String s=new String(ch);

String s="java";

• String class - > methods to perform operations on strings such as


• compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
• The java.lang.String class
implements Serializable, Comparable and CharSequence interfaces.

• CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer and StringBuilder classes implement it.
• Java String is immutable which means it cannot be changed.
There are two ways to create String object:
• By string literal
• By new keyword

• 1) String Literal
• Java String literal is created by using double quotes.
Example
String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool"
first.
• If the string already exists in the pool, a reference to the pooled instance is
returned.
• If the string doesn't exist in the pool, a new string instance is created and placed
in the pool.
Example
• String s1="Welcome";
• String s2="Welcome";//It doesn't create a new instance
class Main {
public static void main(String[] args) {
// create a string using new
String name = new String("Java String");
System.out.println(name); // print Java String
}
}
2) By new keyword
• String s=new String("Welcome"); //creates two objects and one reference variable.
• JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool.
• The variable s will refer to the object in a heap (non-pool).

public class StringExample{


public static void main(String args[]){
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
• Output
java
strings
Example

Java String class provides a lot of methods to perform operations on strings


such as

compare(), concat(), equals(), split(), length(), replace(),

compareTo(), intern(), substring() etc


• Get Length of a String
• To find the length of a string, we use the length() method of the String.
class Main {
public static void main(String[] args) {
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet
int length = greet.length();
System.out.println("Length: " + length);
}
}

Output
String: Hello! World
Length: 12
• Join two Strings
• We can join two strings in Java using the concat() method.
class Main {
public static void main(String[] args) {
// create first string
String first = "Java ";
System.out.println("First String: " + first);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// join two strings
String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output
First String: Java
Second String: Programming
• String Concatenation in Java
• There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method

By + (string concatenation) operator

• By concat() method
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin“ + " Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}

• Output
• Sachin Tendulkar
• 2) String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}

• Output
• Sachin Tendulkar
• Compare two Strings
• In Java, we can make comparisons between two strings using the equals() method.
class Main {
public static void main(String[] args) {
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
// compare first and second strings
boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);
// compare first and third strings
boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}

Output
• Strings first and second are equal: true
• There are three ways to compare string in java:
• By equals() method
• By = = operator
• By compareTo() method

1) String compare by equals() method


• The String equals() method compares the original content of the string.
• It compares values of string for equality. String class provides two methods

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

Output
True
• String compare by == operator
• The = = operator compares references not values.
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//
false(because s3 refers to instance created in nonpool)
}
}

Output :
True
False
• String compare by compareTo() method
• The String compareTo() method compares values lexicographically and
returns an integer value.
• it describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:


s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Output
0, 1 ,-1
• Methods of Java String
Methods Description
substring() returns the substring of the string
replaces the specified old character with the specified new
replace()
character
charAt() returns the character present in the specified location
getBytes() converts the string to an array of bytes
indexOf() returns the position of the specified character in the string
compareTo() compares two strings in the dictionary order
trim() removes any leading and trailing whitespaces
format() returns a formatted string
split() breaks the string into an array of strings
toLowerCase() converts the string to lowercase
toUpperCase() converts the string to uppercase
returns the string representation of the specified
valueOf()
argument
• Substring in Java
• A part of string is called substring.
• substring is a subset of another string.
• In case of substring startIndex is inclusive and endIndex is exclusive.
• Index starts from 0.

String s="hello";
System.out.println(s.substring(0,2));//he

• public String substring(int startIndex):


• This method returns new String object containing the substring of the given
string from specified startIndex (inclusive).

• public String substring(int startIndex, int endIndex):


• This method returns new String object containing the substring of the given
string from specified startIndex to endIndex.
public class TestSubstring{
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}

Java String toUpperCase() and toLowerCase() method


The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)

Output
SACHIN
sachin
Sachin
• Java String trim() method
• The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";


System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

• Output
Sachin
Sachin
• Java String charAt() method
• The string charAt() method returns a character at specified index.

String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Output
• S
• h
• Java String valueOf() method
• The string valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into string.

int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output
1010
• Java String replace() method
• The string replace() method replaces all occurrence of first sequence of
character with second sequence of character.

String s1="Java is a programming language. Java is a platform independent.”


String replaceString=s1.replace("Java",“C++");
System.out.println(replaceString);

• Output
C++ is a programming language. C++ is a platform independent.
• The java.lang.StringBuffer
• The StringBuffer and StringBuilder classes are used when there is a necessity
to make a lot of modifications to Strings of characters.

• objects of type StringBuffer and String builder can be modified over and over
again without leaving behind a lot of new unused objects.

• class is a thread-safe, mutable sequence of characters.


• 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.
public class Test {
public static void main(String args[]) {
StringBuffer sBuffer = new StringBuffer("test");
sBuffer.append(" String Buffer");
System.out.println(sBuffer);
}
}
Output
test String Buffer
StringBuffer Methods
1 public StringBuffer append(String s)Updates the value of the object that invoked the
method.
The method takes boolean, char, int, long, Strings, etc.

2 public StringBuffer reverse()The method reverses the value of the StringBuffer object
that invoked the method.

3 public delete(int start, int end)Deletes the string starting from the start index until the
end index.

4 public insert(int offset, int i)This method inserts a string s at the position mentioned by
the offset.

5 replace(int start, int end, String str)This method replaces the characters in a substring
of this StringBuffer with characters in the specified String.
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.
• An interface is used to group related methods with empty bodies
Syntax
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

Declaring Interfaces
import java.lang.*;
public interface NameOfInterface {
// Any number of final, static fields
// Any number of abstract method declarations
}
• Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important details
of an object (interface).

2) Java does not support "multiple inheritance" (a class can only inherit from
one superclass). However, it can be achieved with interfaces, because the class
can implement multiple interfaces.
Note: To implement multiple interfaces, separate them with a comma
• The relationship between classes and interfaces
• Multiple inheritance in Java by interface
• Extending Interfaces
• An interface can extend another interface in the same way that a class can extend another class.
• The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent
interface.

// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
• Extending Multiple Interfaces
• A Java class can only extend one parent class.
• Multiple inheritance is not allowed.
• Interfaces are not classes, however, and an interface can extend more than
one parent interface.
• Example
• public interface Hockey extends Sports, Event
• Interfaces have the following properties −
• An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is
not needed.
• Methods in an interface are implicitly public.

Example
interface Animal {
public void eat();
public void travel();
}
• Implementing Interfaces
• A class uses the implements keyword to implement an interface.
• The implements keyword appears in the class declaration following the extends portion of the declaration.

public class MammalInt implements Animal {


public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
} Output
Mammal eats
Mammal travels
Java Package
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• A package in Java is used to group related classes.
• Package in java can be categorized in two form,
• Built-in package
• User-defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

• Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
• import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.
Advantages of using a package in Java
• Reusability:
• While developing a project in java, we often feel that there are few things
that we are writing again and again in our code.
• Using packages, you can create such things in form of classes inside a package
and whenever you need to perform that same task, just import that package
and use the class.
• Better Organization:
• Again, in large java projects where we have several hundreds of classes, it is
always required to group the similar types of classes in a meaningful package
name so that you can organize your project better and when you need
something you can quickly locate it and use it, which improves the efficiency.
• Name Conflicts:
• We can define two classes with the same name in different packages so to
avoid name collision, we can use packages.
• Types of packages in Java
1) User defined package:
The package we create is called user-defined package.
2) Built-in package:
The already defined package like java.io.*, java.lang.* etc are
known as built-in packages.
• Built-in Packages
• These packages consist of a large number of classes which are a part of Java API.
• Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support , for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus etc).

6) java.net: Contain classes for supporting networking operations


• User-defined packages
• These are the packages that are defined by the user.
• First we create a directory myPackage (name should be same as the name of
the package).
• Then create the MyClass inside the directory with the first statement being
the package names.

public class MyClass


{
public void getNames(String s) {
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
• Syntax
• import package.name.Class; // Import a single class
• import package.name.*; // Import the whole package

• Example
• import java.util.Scanner;

• In the example above, java.util is a package, while Scanner is a class of the


java.util package.
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable with a value
String name = “Hello";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
obj.getNames(name);
}
}
MyClass.java must be saved inside the myPackage directory since it is a part of the package.
Creating our first package:
• To create a package, use the package keyword
• File name – ClassOne.java

package package_name;
public class ClassOne {
public void methodClassOne() {
System.out.println("Hello there its ClassOne");
}
}
• Creating our second package:
• File name – ClassTwo.java

package package_one;
public class ClassTwo {
public void methodClassTwo(){
System.out.println("Hello there i am ClassTwo");
}
}
• Making use of both the created packages:
• File name – Testing.java

import package_one;
import package_name.ClassOne;

public class Testing {


public static void main(String[] args){
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}

Output:

Hello there i am ClassTwo


Hello there its ClassOne
• Key points:

• Every class is part of some package.


• If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
• All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
• If package name is specified, the file must be in a subdirectory called name
(i.e., the directory name must match the package name).
• We can access public classes in another (named) package using: package-
name.class-name
• How to Create a package?

• Creating a package is a simple task as follows


• Choose the name of the package
• Include the package command as the first line of code in your Java Source File.
• The Source file contains the classes, interfaces, etc you want to include in the package
• Compile to create the Java packages.

1. Consider the following package program in Java:

package p1;
class c1(){
public void m1(){
System.out.println("m1 of c1");
}
public static void main(string args[]){
c1 obj = new c1();
obj.m1();
}
• To put a class into a package, at the first line of code define package
p1
• Create a class c1
• Defining a method m1 which prints a line.
• Defining the main method
• Creating an object of class c1
• Calling method m1
Step 2) In next step, save this file as demo.java
Step 3) In this step, we compile the file.
• The compilation is completed.
• A class file c1 is created. no package is created

Step 4) Now we have to create a package, use the command


• javac –d . demo.java

• This command forces the compiler to create a package.


• The "." operator represents the current working directory.
Step 5) When you execute the code, it creates a package p1. When you open the
java package p1 inside you will see the c1.class file.

Step 6) Compile the same file using the following code.


javac –d .. demo.java

Here ".." indicates the parent directory.


In our case file will be saved in parent directory which is C Drive
• File saved in parent directory when above code is executed.
• Step 7) Now let's say you want to create a sub package p2 within our
existing java package p1. Then we will modify our code as

package p1.p2;
class c1{
public void m1() {
System.out.println("m1 of c1");
}
}
• Step 8) Compile the file

• As seen in below screenshot, it creates a sub-package p2 having class


c1 inside the package.
• Step 9) To execute the code mention the fully qualified name of the
class i.e. the package name followed by the sub-package name
followed by the class name –

java p1.p2.c1
• This is how the package is executed and gives the output as "m1 of
c1" from the code file.
• The package keyword is used to create a package in java.
Syntax
package nameOfPackage;

Example

package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
• Multitasking:
• Ability to execute more than one task at the same time is known as
multitasking.
• Multithreading:
• It is a process of executing multiple threads simultaneously.
• Multithreading is also known as Thread-based Multitasking.
• Multiprocessing:
• It is same as multitasking, however in multiprocessing more than one CPUs
are involved.
• On the other hand one CPU is involved in multitasking.
• Parallel Processing:
• It refers to the utilization of multiple CPUs in a single computer system.
MULTITHREADING
• A single thread is basically a lightweight and the smallest unit of
processing.
• Java uses threads by using a "Thread Class".
• There are two types of thread –
• user thread - When an application first begins, user thread is created.
• daemon thread - daemon threads are used when we want to clean the
application and are used in the background.
• Single Thread Example:
package demotest;
public class SingleThread {
public static void main(String[] args) {
System.out.println("Single Thread");
}
}
• Advantages of single thread:
• Reduces overhead in the application as single thread execute in the system
• Also, it reduces the maintenance cost of the application.
Multithreading
• Process of executing two or more threads simultaneously to
maximum utilization of CPU.
• Multithreaded applications execute two or more threads run
concurrently.
• Each thread runs parallel to each other.
• Multiple threads don't allocate separate memory area, hence they
save memory.
• Context switching between threads takes less time.
Advantages of multithread:
• The users are not blocked because threads are independent, and we
can perform multiple operations at times
• As such the threads are independent, the other threads won't get
affected if one thread meets an exception.

Creating a thread in Java


There are two ways to create a thread in Java:
• By extending Thread class.
• By implementing Runnable interface.
• Methods of Thread class
• getName(): It is used for Obtaining a thread’s name
• getPriority(): Obtain a thread’s priority
• isAlive(): Determine if a thread is still running
• join(): Wait for a thread to terminate
• run(): Entry point for the thread
• sleep(): suspend a thread for a period of time
• start(): start a thread by calling its run() method

• Method 1: Thread creation by extending Thread class

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
• Output: My thread is in running state.
• Method 2: Thread creation by implementing Runnable Interface
class MultithreadingDemo implements Runnable{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Output: My thread is in running state.
Thread Life Cycle in Java

• New
• Runnable
• Running
• Waiting
• Dead
• New:
• In this phase, the thread is created using class "Thread class".
• It remains in this state till the program starts the thread. It is also known as
born thread.
• Runnable:
• In this page, the instance of the thread is invoked with a start method.
• The thread control is given to scheduler to finish the execution.
• It depends on the scheduler, whether to run the thread.
• Running:
• When the thread starts executing, then the state is changed to "running"
state.
• The scheduler selects one thread from the thread pool, and it starts executing
in the application.
• Waiting:
• This is the state when a thread has to wait.
• As there multiple threads are running in the application, there is a need for
synchronization between threads.
• Hence, one thread has to wait, till the other thread gets executed.
• Dead:
• This is the state when the thread is terminated.
• The thread is in running state and as soon as it completed processing it is in
"dead state".
•Timed Waiting:
•A thread lies in timed waiting state when it calls a method with a time out
parameter.
•A thread lies in this state until the timeout is completed or until a notification
is received.
•For example, when a thread calls sleep or a conditional wait, it is moved to a
timed waiting state.
• BLOCKED
• A thread that is blocked waiting for a monitor lock is in this state.
• To get the current state of the thread, use Thread.getState() method .
• Java provides java.lang.Thread.State class that defines the ENUM
constants for the state of a thread.
Commonly used Methods
Method Description
start() This method starts the execution of the thread and JVM calls the run()
method on the thread.

Sleep(int milliseconds) This method makes the thread sleep hence the thread's execution will pause
for milliseconds provided and after that, again the thread starts executing.
This help in synchronization of the threads.

getName() It returns the name of the thread.


setPriority(int newpriority) It changes the priority of the thread.

yield () It causes current thread on halt and other threads to execute.


Example
class MultithreadingDemo extends Thread {
public void run() {
try {
// Displaying the thread that is running
System.out.println ("Thread " + Thread.currentThread().getId() +
" is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i=0; i<n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running
Thread priorities
• Thread priorities are the integers which decide how one thread
should be treated with respect to the others.
• Thread priority decides when to switch from one running thread to
another, process is called context switching
• A thread can voluntarily release control and the highest priority
thread that is ready to run is given the CPU.
• A thread can be preempted by a higher priority thread no matter
what the lower priority thread is doing.
• Whenever a higher priority thread wants to run it does.
• To set the priority of the thread setPriority() method is used which is
a method of the class Thread Class.
• In place of defining the priority in integers, we can use
MIN_PRIORITY, NORM_PRIORITY or MAX_PRIORITY.
• https://www.javatpoint.com/array-in-java
• https://beginnersbook.com/2013/03/packages-in-java/

You might also like