0% found this document useful (0 votes)
11 views93 pages

Unit 3

Java is a simple, class-based, object-oriented programming language developed by James Gosling in 1995, designed for platform independence and ease of use. It features a Java Virtual Machine (JVM) that executes bytecode, making it versatile across different operating systems. Key characteristics include robustness, security, multithreading, and a rich set of libraries for developers.

Uploaded by

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

Unit 3

Java is a simple, class-based, object-oriented programming language developed by James Gosling in 1995, designed for platform independence and ease of use. It features a Java Virtual Machine (JVM) that executes bytecode, making it versatile across different operating systems. Key characteristics include robustness, security, multithreading, and a rich set of libraries for developers.

Uploaded by

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

Introduction to Java

JAVA was developed by James Gosling at Sun Microsystems Inc in


the year 1995, later acquired by Oracle Corporation. It is a simple
programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and
modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few
implementation dependencies as possible. A general-purpose
programming language made for developers to write once run
anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can
run on any Java Virtual Machine. The syntax of Java is similar to
c/c++.
History

It is a programming language created in 1991. James Gosling,
Mike Sheridan, and Patrick Naughton, a team of Sun engineers
known as the Green team initiated the Java language in 1991.
Sun Microsystems released its first public implementation in 1996
as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to
strictly comply with its specifications. With the arrival of Java 2,
new versions had multiple configurations built for different types
of platforms.
Java programming language is named JAVA. Why?

After the name OAK, the team decided to give a new name to it and the
suggested words were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all
names were easy to spell and fun to say, but they all wanted the name to
reflect the essence of technology. In accordance with James Gosling, Java
the among the top names along with Silk, and since java was a unique
name so most of them preferred it.

Java is the name of an island in Indonesia where the first coffee(named java
coffee) was produced. And this name was chosen by James Gosling while
having coffee near his office. Note that Java is just a name, not an acronym.
Java Terminology

1:- Java Virtual Machine(JVM): This is generally referred to as JVM.

There are three execution phases of a program. They are written, compile and run the program.

Writing a program is done by a java programmer like you and me.

The compilation is done by the JAVAC compiler which is a primary Java compiler included in the
Java development kit (JDK). It takes the Java program as input and generates bytecode as output.

In the Running phase of a program, JVM executes the bytecode generated by the compiler.

Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced
by the compiler. Every Operating System has a different JVM but the output they produce after the
execution of bytecode is the same across all the operating systems. This is why Java is known as
a platform-independent language.
2:- Bytecode in the Development process

As discussed, the Javac compiler of JDK
compiles the java source code into bytecode so
that it can be executed by JVM. It is saved
as .class file by the compiler. To view the
bytecode, a disassembler like javap can be
used.
3. Java Development Kit(JDK)

While we were using the term JDK when we learn about
bytecode and JVM. So, as the name suggests, it is a
complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE),
java debuggers, java docs, etc. For the program to
execute in java, we need to install JDK on our computer
in order to create, compile and run the java program.
4: Java Runtime Environment (JRE)

JDK includes JRE. JRE installation on our
computers allows the java program to run,
however, we cannot compile it. JRE includes a
browser, JVM, applet supports, and plugins. For
running the java program, a computer needs
JRE.
Garbage Collector

In Java, programmers can’t delete the objects. To delete or
recollect that memory JVM has a program called Garbage
Collector. Garbage Collectors can recollect the objects that are
not referenced. So Java makes the life of a programmer easy
by handling memory management. However, programmers
should be careful about their code whether they are using
objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.
6: ClassPath

The classpath is the file path where the java
runtime and Java compiler look for .class files
to load. By default, JDK provides many
libraries. If you want to include external libraries
they should be added to the classpath.
Primary/Main Features of Java

Platform Independent

Object-Oriented Programming Language

Simple

Robust

Secure

Distributed

Multithreading

Portable

High Performance

Dynamic flexibility

Sandbox Execution

Write Once Run Anywhere

Power of compilation and interpretation
1: Platform Independent

Compiler converts source code to bytecode and then the
JVM executes the bytecode generated by the compiler. This
bytecode can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows,
then we can run it on Linux and vice versa. Each operating
system has a different JVM, but the output produced by all
the OS is the same after the execution of bytecode. That is
why we call java a platform-independent language.
2: Object-Oriented Programming Language

Organizing the program in the terms of collection of objects is a way of
object-oriented programming, each of which represents an instance of
the class.

The four main concepts of Object-Oriented programming are:

Abstraction

Encapsulation

Inheritance

Polymorphism
3: Simple

Java is one of the simple languages as it does
not have complex features like pointers,
operator overloading, multiple inheritances, and
Explicit memory allocation.
4: Robust

Java language is robust which means reliable. It is
developed in such a way that it puts a lot of effort into
checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not
easy to detect by another programming language. The
main features of java that make it robust are garbage
collection, Exception Handling, and memory allocation.
5: Secure

In java, we don’t have pointers, so we cannot access out-
of-bound arrays i.e it shows ArrayIndexOutOfBound
Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are
impossible to exploit in Java. Also java programs run in an
environment that is independent of the os(operating
system) environment which makes java programs more
secure .
6:Distributed

We can create distributed applications using the
java programming language. Remote Method
Invocation and Enterprise Java Beans are used
for creating distributed applications in java. The
java programs can be easily distributed on one or
more systems that are connected to each other
through an internet connection.
7: Multithreading

Java supports multithreading. It is a Java
feature that allows concurrent execution of two
or more parts of a program for maximum
utilization of the CPU.
8: Portable

As we know, java code written on one machine
can be run on another machine. The platform-
independent feature of java in which its
platform-independent bytecode can be taken to
any platform for execution makes java portable.
9: High Performance

Java architecture is defined in such a way that it
reduces overhead during the runtime and at
some time java uses Just In Time (JIT) compiler
where the compiler compiles code on-demand
basics where it only compiles those methods that
are called making applications to execute faster.
10: Dynamic flexibility

Java being completely object-oriented gives us
the flexibility to add classes, new methods to
existing classes and even create new classes
through sub-classes. Java even supports
functions written in other languages such as C,
C++ which are referred to as native methods.
11: Sandbox Execution

Java programs run in a separate space that
allows user to execute their applications without
affecting the underlying system with help of a
bytecode verifier. Bytecode verifier also
provides additional security as its role is to
check the code for any violation of access.
12: Write Once Run Anywhere

As discussed above java application generates a
‘.class’ file which corresponds to our
applications(program) but contains code in binary
format. It provides ease t architecture-neutral ease
as bytecode is not dependent on any machine
architecture. It is the primary reason java is used
in the enterprising IT industry globally worldwide.
13: Power of compilation and interpretation

Most languages are designed with purpose either
they are compiled language or they are
interpreted language. But java integrates arising
enormous power as Java compiler compiles the
source code to bytecode and JVM executes this
bytecode to machine OS-dependent executable
code.

Now lets take an example of Java Program and discuss the components of Java
Program

// Importing classes from packages

import java.io.*;

// Main class

public class Myclass {

// Main driver method

public static void main(String[] args)

{

// Print statement

System.out.println("Welcome to Java Class");

}

}
Comments

Comments are used for explaining code and are used in a similar
manner in Java or C or C++. Compilers ignore the comment entries and
do not execute them. Comments can be of a single line or multiple lines.

Single line Comments:
 Syntax:

// Single line comment

Multi-line comments:
 Syntax:

/* Multi line comments*/
import java.io.*

This means all the classes of io package can be
imported. Java io package provides a set of
input and output streams for reading and writing
data to files or other input or output sources.
class

The class contains the data and methods to be
used in the program. Methods define the
behavior of the class. Class Myclass has only
one method Main in JAVA.
static void Main()

static keyword tells us that this method is
accessible without instantiating the class.
void

keywords tell that this method will not return
anything. The main() method is the entry point
of our application.
System.in

This is the standard input stream that is used to
read characters from the keyboard or any other
standard input device.
System.out

This is the standard output stream that is used
to produce the result of a program on an output
device like the computer screen
println()

This method in Java is also used to display text
on the console. It prints the text on the console
and the cursor moves to the start of the next
line at the console. The next printing takes
place from the next line.
String []args

This is the argument passed to the main
function which is an array of strings with the
array name args. One can choose their own
flexible name but this name is used by many
developers.
Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:


Unary Operator,

Arithmetic Operator,

Shift Operator,

Relational Operator,

Bitwise Operator,

Logical Operator,

Ternary Operator and

Assignment Operator.
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:


incrementing/decrementing a value by one

negating an expression

inverting the value of a boolean


example :
public class OperatorExample{

public static void main(String args[]){

int x=10;

System.out.println(x++);//10 (11)

System.out.println(++x);//12

System.out.println(x--);//12 (11)

System.out.println(--x);//10

}}
Arithmetic Operator
Java arithmetic operators are used to perform addition, subtraction, multiplication,
and division. They act as basic mathematical operations.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right
by the number of bits specified by the right operand.

public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Relational Operator
Java has 6 relational operators.


== is the equality operator. This returns true if both the operands are referring to
the same object, otherwise false.

!= is for non-equality operator. It returns true if both the operands are referring to
the different objects, otherwise false.

< is less than operator.

> is greater than operator.

<= is less than or equal to operator.

>= is greater than or equal to operator.
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number.

1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input
values, i.e., if both bits are 1, it gives 1, else it shows 0.

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input
values, i.e., if corresponding bits are different, it gives 1, else it shows 0.
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes
every 0 to 1, and every 1 to 0.

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Home Work

Write a Java program with using the all bit wise operator.

Logical Operator

Logical operators are used to performing logical “AND”, “OR” and “NOT” operations

AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true execute else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

Logical ‘AND’ Operator (&&)


This operator returns true when both the conditions under consideration are
satisfied or are true. If even one of the two yields false, the operator results false. In
Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true

Logical ‘OR’ Operator (||):
This operator returns true when one of the two conditions under consideration is
satisfied or is true. If even one of the two yields true, the operator results true. To
make the result false, both the constraints need to return false.

Logical ‘NOT’ Operator (!):


Unlike the previous two, this is a unary operator and returns true when the condition
under consideration is not satisfied or is a false condition. Basically, if the condition is
false, the operation returns true and when the condition is true, the operation returns
false.

!(condition)
Ternary Operator

Java ternary operator is the only conditional operator that takes three operands. It’s a
one-liner replacement for the if-then-else statement and is used a lot in Java
programming. We can use the ternary operator in place of if-else conditions or even
switch conditions using nested ternary operators. Although it follows the same
algorithm as of if-else statement, the conditional operator takes less space and helps
to write the if-else statements in the shortest way possible.
Ternary Operator : Expression

variable = Expression1 ? Expression2: Expression3

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Assignment Operator

These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable, and the right side operand of the assignment
operator is a value.

A = 2;
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
1: Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2: Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Data Types: classification
Primitive data types

1)boolean data type


2)byte data type
3)char data type
4)short data type
5)int data type
6)long data type
7)float data type
8)double data type
Boolean Data Type

The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:
Boolean one = false
Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory
savings is most required. It saves space because a byte is 4 times smaller than an
integer. It can also be used in place of "int" data type.

Example:
byte a = 10, byte b = -20
Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:
short s = 10000, short r = -5000
Int Data Type

The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:
int a = 100000, int b = -200000
Long Data Type

The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)
(inclusive). Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when
you need a range of values more than those provided by int.

Example:
long a = 100000L, long b = -200000L
Float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.

float f1 = 234.5f
Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:
double d1 = 12.3
Char Data Type

The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example:
char letterA = 'A'
Non-primitive data types

Unlike primitive data types, these are not predefined. These are user-defined data
types created by programmers. These data types are used to store multiple values.

For example, consider an array that stores a group of values. Class is also a primitive
type that stores different methods and variables. Therefore, these are also called as
advanced data types in Java.

1)Class
2)Object
3)String
4)Array
5)Interface
1. Class and objects:

A class in Java is a user defined data type i.e. it is created by the user. It acts a
template to the data which consists of member variables and methods.

An object is the variable of the class, which can access the elements of class i.e.
methods and variables.
Example: Class and Object

public class ClassExample {

// defining the variables of class


int a = 20;
int b = 10;
int c;

// defining the methods of class


public void add () {
int c = a + b;
System.out.println("Addition of numbers is: " + c);
}

public void sub () {


int c = a - b;
System.out.println("Subtraction of numbers is: " + c);
}

// main method
public static void main (String[] args) {
// creating the object of class
ClassExample obj = new ClassExample();

// calling the methods


obj.add();
obj.sub();
}
}
2. Interface:

An interface is similar to a class however the only difference is that its methods are
abstract by default i.e. they do not have body. An interface has only the final variables
and method declarations. It is also called a fully abstract class.
interface CalcInterface {
void multiply();
void divide();
}
public class InterfaceExample implements CalcInterface {

// defining the variables of class


int a = 10;
int b = 20;
int c;

// implementing the interface methods


public void multiply() {
int c = a * b;
System.out.println("Multiplication of numbers is: " + c);
}
public void divide() {
int c = a / b;
System.out.println("Division of numbers is: " + c);
}
// main method
public static void main (String[] args) throws IOException {
InterfaceExample obj = new InterfaceExample();
// calling the methods
obj.multiply();
obj.divide();
}
3. String:

A string represents a sequence of characters for example "Javatpoint", "Hello world",


etc. String is the class of Java.

Example:
String str = "You're the best";

public class StringExample {


public static void main(String[] args) {

// creating a string and initializing it


String str = "Hello! This is example of String type";

// applying substring() on above string


String subStr = str.substring(0,14);

// printing the string


System.out.println(subStr);
}
}
4. Array:

An array is a data type which can store multiple homogenous variables i.e., variables
of same type in a sequence. They are stored in an indexed manner starting with
index 0. The variables can be either primitive or non-primitive data types.

Example:
int [ ] marks;
import java.io. * ;
import java.util. * ;

public class ArrayExample {


public static void main(String[] args) throws IOException {
int i;
Scanner sc = new Scanner(System. in );
// declaring and initializing an array
int arr[] = {1, 2, 3, 6, 9};
// defining another array arr1
int arr1[] = new int[5];
// reading values from the user
System.out.println("Enter the numbers (size = 5) :");
for (i = 0; i < 5; i++) {
arr1[i] = sc.nextInt();
}
System.out.println("Previous array with initialized size is: ");
for (i = 0; i < 5; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\nThe new array we have entered is:");
for (i = 0; i < 5; i++) {
System.out.print(arr1[i] + " ");
}
}
}
Home Work

Difference between Primitive and Non-primitive Data types in Java?


Variables

Variable in Java is a data container that saves the data values during Java program
execution. Every variable is assigned a data type that designates the type and
quantity of value it can hold. A variable is a memory location name for the data.
A variable is a name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location. All the operations done on
the variable affect that memory location.
In Java, all variables must be declared before use.
Types of Variables in Java

1)Local Variables
2)Instance Variables
3)Static Variables
Local Variable

/*package whatever //do not write package name here */


// Contributed by Shubham Jain
import java.io.*;

class GFG {
public static void main(String[] args)
{
int var = 10; // Declared a Local Variable
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}
}
Instance Variables

/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public String geek; // Declared Instance Variable

public GFG()
{ // Default Constructor

this.geek = "Shubham Jain"; // initializing Instance Variable


}
//Main Method
public static void main(String[] args)
{

// Object Creation
GFG name = new GFG();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
}
}
Static Variables

/*package whatever //do not write package name here */

import java.io.*;

class GFG {

public static String geek = "Shubham Jain"; //Declared static variable

public static void main (String[] args) {

//geek variable can be accessed without object creation


//Displaying O/P
//GFG.geek --> using the static variable
System.out.println("Geek Name is : "+GFG.geek);
}
}
Home Work

Prepare the more depth notes of Types of variable.


Method

In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code.

A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and
use it many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.

The most important method in Java is the main() method.


Method Declaration

The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header.
Access Specifier

Access specifier or modifier is the access type of the method. It specifies the visibility of the method.
Java provides four types of access specifier:


Public: The method is accessible by all classes when we use public specifier in our application.

Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.

Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Types of Method

There are two types of methods in Java:


Predefined Method

User-defined Method


In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.


The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.
Home Work

Write java program which consist at least 3 pre-defined methods.

Write java program which consist at least 2 user defined methods.


Class
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:



Fields

Methods

Constructors

Blocks

Nested class and interface


Syntax:

class <class_name>{

field;

method;

}
Multithread Programming

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.

Threads can be created by using two mechanisms :


1: Extending the Thread class
2: Implementing the Runnable Interface

Thread creation by extending the Thread class: We create a class that extends the
java.lang.Thread class. This class overrides the run() method available in the Thread class. A
thread begins its life inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on the Thread object.
// Java code for thread creation by extending
// the Thread class
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");
}
}
}

// Main Class
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();
}
}
}
Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
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");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
Commonly used methods of Thread class:


public void run(): is used to perform action for a thread.

public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.

public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

public void join(): waits for a thread to die.

public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

public int getPriority(): returns the priority of the thread.

public int setPriority(int priority): changes the priority of the thread.

public String getName(): returns the name of the thread.

public void setName(String name): changes the name of the thread.

public Thread currentThread(): returns the reference of currently executing thread.

public int getId(): returns the id of the thread.

public Thread.State getState(): returns the state of the thread.

public boolean isAlive(): tests if the thread is alive.

public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.

public void suspend(): is used to suspend the thread(depricated).

public void resume(): is used to resume the suspended thread(depricated).

public void stop(): is used to stop the thread(depricated).

public boolean isDaemon(): tests if the thread is a daemon thread.

public void setDaemon(boolean b): marks the thread as daemon or user thread.

public void interrupt(): interrupts the thread.

public boolean isInterrupted(): tests if the thread has been interrupted.

public static boolean interrupted(): tests if the current thread has been interrupted.
Java I/O

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
Stream: A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream


2) System.in: standard input stream
3) System.err: standard error stream

Example : System.out.println("simple message");


System.err.println("error message");

int i=System.in.read();//returns ASCII code of 1st character


System.out.println((char)i);//will print the character
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.
Home work

Study over the internet in depth about the input stream class and output stream class
and their methods.

You might also like