SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Unit-1
The program Creation
The Java program can be written using a Text Editor (Notepad++ or NotePad or other editors will also do the job.)
or IDE (Eclipse, NetBeans, etc.).
FileName: [Link]
public class TestClass
{
// main method
public static void main(String []args)
{
// print statement
[Link]("Hello World is my first Java Program.");
}
}
Operators in Java
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
Example 1:
Let's consider the following example to understand how to define a class in Java and implement it with the object of
class.
[Link]
// class definition
public class Calculate {
// instance variables
int a;
int b;
// constructor to instantiate
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}
// method to add numbers
public int add () {
int res = a + b;
return res;
}
// method to subtract numbers
public int subtract () {
int res = a - b;
return res;
}
// method to multiply numbers
public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);
// calling the methods of Calculate class
[Link]("Addition is :" + [Link]());
[Link]("Subtraction is :" + [Link]());
[Link]("Multiplication is :" + [Link]());
[Link]("Division is :" + [Link]());
}
Constructors in Java
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
Output: Bike is created
Java Parameterized Constructor
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output
111 Karan
222 Aryan
Constructor Overloading in Java
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){[Link](id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}
Output
111 Karan 0
222 Aryan 25
Method
class Student
{
int rollno;
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
[Link](rollno+" "+name+" "+college);
}
}
public class TestStaticVariable1
{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//[Link]="BBDIT";
[Link]();
[Link]();
}
}
When a member is declared static, it can be accessed before any objects of its class are created, and without
reference to any object. For example, in the below java program, we are accessing static method m1() without
creating any object of the Test class.
class Test
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
// static method
static void m1()
{
[Link]("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating any object of class Test
m1();
}
}
Output:
From m1
final Keyword in Java
In Java, we cannot change the value of a final variable. For example,
class Main {
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
[Link]("Age: " + AGE);
}
}
OUTPUT:
ERROR!
/tmp/yyyEAaOvI5/[Link]: error: cannot assign a value to final variable AGE
AGE = 45;
^
1 error
Java Control Statements | Control Flow in Java
Simple if statement:
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} } }
Output:
x + y is greater than 20
if-else statement
public static void main(String[] args) {
int x = 10;
int y = 12;
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
}
}
}
if-else-if ladder:
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
[Link]("city is meerut");
}else if (city == "Noida") {
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
} } }
Output:
Delhi
Nested if-statement
public class Student
{
public static void main(String[] args)
{
String address = "Delhi, India";
if([Link]("India")) {
if([Link]("Meerut")) {
[Link]("Your city is Meerut");
}else if([Link]("Noida")) {
[Link]("Your city is Noida");
}else {
[Link]([Link](",")[0]);
}
}else {
[Link]("You are not living in India");
} } }
Switch Statement:
Syntax
switch (expression){
case value1:
statement1;
break;
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
} } }
Output: 2
Loop Statements
for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}
Output:
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
The sum of first 10 natural numbers is 55
for-each loop
for(data_type var : array_name/collection_name){
//statements
}
Example
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for(String name:names) {
[Link](name);
} } }
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
while loop
The syntax of the while loop is given below.
while(condition){
//looping statements
}
Example:
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
while(i<=10) {
[Link](i);
i = i + 2;
} } }
Output:
Printing the list of first 10 even numbers
0
2
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
4
6
8
10
do-while loop
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements - Break and Continue
Java break statement
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
} } } }
Output:
0
1
2
3
4
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
5
6
continue statement
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
[Link](j);
} } } }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
new keyword in Java
int id;
String name;
public static void main(String args[]){
Student s1=new Student();
[Link]([Link]);
[Link]([Link]);
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Output:
0
Null
Object and Class Example: main outside the class
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
[Link]([Link]);
[Link]([Link]);
}
}
Output:
0
Null
Object / Class Example
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){[Link](length*width);}
}
class TestRectangle1{
public static void main(String args[]){
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}
Output:
55
45
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
Example
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]); } }
Programmer salary is:40000.0
Bonus of programmer is:10000
Single Inheritance Example
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}
Output
barking...
eating...
Multilevel Inheritance Example
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}}
Output
weeping...
barking...
eating...
Hierarchical Inheritance Example
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}
Output
meowing...
eating...
Why multiple inheritance is not supported in java?
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
public static void main(String args[]){
C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}
Output
Compile time error
Java interfaces
interface Character {
void attack();
}
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
[Link]("Warrior attacks with a sword.");
}
public void use() {
[Link]("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
[Link]("Mage attacks with a wand.");
}
public void use() {
[Link]("Mage uses a wand.");
}
}
public class MultipleInheritance {
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
public static void main(String[] args) {
Warrior warrior = new Warrior();
Mage mage = new Mage();
[Link](); // Output: Warrior attacks with a sword.
[Link](); // Output: Warrior uses a sword.
[Link](); // Output: Mage attacks with a wand.
[Link](); // Output: Mage uses a wand.
}
}
Output:
Warrior attacks with a sword.
Warrior uses a sword.
Mage attacks with a wand.
Mage uses a wand.
Method Overloading in Java
class Vehicle{
void run(){[Link]("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){[Link]("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
[Link](); }
}
Output: Bike is running safely
Usage of Java super Keyword
class Bike2 extends Vehicle
{
void run()
{
[Link]("Bike is running safely");
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
[Link]();
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
[Link]();
}
}
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
Polymorphism in Java
class Bike{
void run(){[Link]("running");}
}
class Splendor extends Bike{
void run(){[Link]("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
[Link]();
}
}
Output:
running safely with 60km.
Unit-2
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Java Exception Handling
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
Java Scanner Class
import [Link].*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner([Link]); //[Link] is a standard input stream
[Link]("Enter first number- ");
int a= [Link]();
[Link]("Enter second number- ");
int b= [Link]();
[Link]("Enter third number- ");
int c= [Link]();
int d=a+b+c;
[Link]("Total= " +d);
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
BufferedReader Class
The input is buffered for efficient reading.
The wrapping code is hard to remember.
import [Link].*;
public class CalcArea
{
public static void main ( String args[] ) throws IOException
{
[Link] ( "Enter the radius: " );
BufferedReader input = new BufferedReader ( new InputStreamReader ( [Link] ) );
String inputString = [Link]();
double radius = [Link] ( inputString );
double area = 3.14159 * radius * radius;
[Link] ( "Area is: " + area );
}
}
import [Link];
import [Link];
import [Link];
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader( new InputStreamReader([Link]));
// Reading data using readLine
String name = [Link]();
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
// Printing the read line
[Link](name);
}}
Flow control in a try catch finally in Java
File Name : [Link]
import [Link].*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
[Link]("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}
[Link]("Out of the block"); }}
This will produce the following result −
Output
Exception thrown :[Link]: 3
Multiple Catch Blocks
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
=== Code Execution Successful ===
The Finally Block
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
[Link]("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
} finally {
a[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
}
}
}
This will produce the following result −
Output
Exception thrown :[Link]: 3
First element value: 6
The finally statement is executed
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Java throw
[Link]
public class TestThrow {
//defining a method
public static void checkNum(int num)
{
if (num < 1)
{
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
[Link]("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args)
{
TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the code..");
}
}
Output:
ERROR!
Exception in thread "main" [Link]:
Number is negative, cannot calculate square
at [Link]([Link])
at [Link]([Link])
=== Code Exited With Errors ===
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Java throws Example
[Link]
public class TestThrows
{
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
[Link]([Link](45, 0));
}
catch (ArithmeticException e)
{
[Link]("\nNumber cannot be divided by 0");
}
[Link]("Rest of the code..");
}
}
Output
Number cannot be divided by 0
Rest of the code..
=== Code Execution Successful ===
Character Stream:
FileName: [Link]
import [Link];
import [Link];
public class CharacterStreamExample
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
{
public static void main(String[] args)
{
// Creates an array of characters
char[] array = {'H','e','l','l','o'};
try
{
CharArrayReader reader=new CharArrayReader(array);
[Link]("The characters read from the reader:");
int charRead;
while ((charRead=[Link]())!=-1)
{
[Link]((char)charRead+",");
}
[Link]();
}
catch (IOException ex)
{
[Link]();
}
}
}
Output:
The characters read from the reader:H,e,l,l,o,
Example code for Byte Stream:
FileName: [Link]
import [Link];
public class ByteStreamExample
{
public static void main(String[] args)
{
// Creates the array of bytes
byte[] array = {10,20,30,40};
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
try {
ByteArrayInputStream input=new ByteArrayInputStream(array);
[Link]("The bytes read from the input stream:");
for (int i=0;i<[Link];i++)
{
// Reads the bytes
int data=[Link]();
[Link](data+",");
}
[Link]();
} catch (Exception ex)
{
[Link]();
}
}
}
Output:
The bytes read from the input stream:10,20,30,40.
import [Link].*;
class A
{
public static void main(String args[])
{
File f =new File("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
try
{
if([Link]())
{
[Link]("File Created Successfully");
}
else
{
[Link]("File already exists");
}
}
catch(IOException e)
{
[Link]("Exception handled");
}
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Compile: Java [Link]
Run: Java A
Optput:
File Information
import [Link].*;
class B
{
public static void main(String args[])
{
File f =new File("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
if([Link]())
{
[Link]("File Name: "+[Link]());
[Link]("File Location: "+[Link]());
[Link]("File Writable: "+[Link]());
[Link]("File Readable: "+[Link]());
[Link]("File Size: "+[Link]());
}
else
{
[Link]("File doesnot exists");
}
}
}
Compile java [Link]
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Run java B
Output:
Now write something in the abc,txt file located on the desktop.
For eg Lucknow is the capital of Uttar Pradesh.
import [Link].*;
class B
{
public static void main(String args[])
{
File f =new File("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
if([Link]())
{
[Link]("File Name: "+[Link]());
[Link]("File Location: "+[Link]());
[Link]("File Writable: "+[Link]());
[Link]("File Readable: "+[Link]());
[Link]("File Size: "+[Link]());
[Link]("File Removed"+[Link]());
}
else
{
[Link]("File doesnot exists");
}
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Output:
import [Link].*;
// File Writer
class C
{
public static void main(String args[])
{
try
{
FileWriter f=new FileWriter("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
try
{
[Link]("Java Prog");
}
finally
{
[Link]();
}
[Link]("Successfully data wrote in the file");
}
catch(IOException e)
{
[Link](e);
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
}
}
Output:
import [Link].*;
// File Reader
class D
{
public static void main(String args[])
{
try
{
FileReader f=new FileReader("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
try
{
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
}
finally
{
[Link]();
}
}
catch(IOException e)
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
[Link]("Exception handled");
}
}
}
Output:
This Keyword
class A
{
public void show()
{
[Link](this);
}
public static void main(String args[])
{
A ob =new A();
[Link](ob);
[Link]();
}
}
Output:
java -cp /tmp/O2d0QwJFRF/A
A@379619aa
A@379619aa
=== Code Execution Successful ===
Point 2. Whenever the name of the instance and the local variable both are same then our runtime environment
(JVM) get confused that which one is local and which one is instance variable, to avoid this problem we use this
keyword.
This keyword refers the current object of the class
Current object is always the instance variable.
class A
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
int a; //instance variable
A(int a) //local variable
{
a=a;
}
public void show()
{
[Link](a);
}
public static void main(String args[])
{
A ob=new A(100);
[Link]();
}
}
Output
java -cp /tmp/9t74zYhdd7/A
0
=== Code Execution Successful ===
Because the default value of integer is 0
class A
{
int a; //instance variable
A(int a) //local variable
{
this.a=a;
}
public void show()
{
[Link](a);
}
public static void main(String args[])
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
A ob=new A(100);
[Link]();
}
}
Output:
java -cp /tmp/TGwICOI1M5/A
100
=== Code Execution Successful ===
Instance variable is always the part of the object so in this case the value of instance variable is 100 and we get the
output as 100.
Point 3. It is also used when we want to call the default constructor of its own class.
Syntax:
class A
{
A() // default constructor
{
}
A(int x) // parameterize constructor
{
this() // this keyword automatically calls the default constructor of the same class
}
}
Example:
class A
{
A() // default constructor
{
[Link]("Hello World!");
}
A(int x) // parameterize constructor
{
this(); // this kewyword automatically calls the default constructor of the same class.
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
[Link](x);
}
public static void main(String args[])
{
A ob=new A(100);
}
}
Output:
java -cp /tmp/H9Rba6d4O1/A
Hello World!
100
=== Code Execution Successful ===
Point 4. It also calls the parameterize constructor of its own class.
Syntax:
class A
{
A() // default constructor
{
this(10)
}
A(int x) // parameterize constructor
{
}
}
Here this keyword will call the parameterized constructor.
class A
{
A() // default constructor
{
this(10);
}
A(int x) // parameterize constructor
{
[Link](x);
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
public static void main(String args[])
{
A ob=new A();
}
}
Output:
java -cp /tmp/n7kZJAZTsW/A
10
=== Code Execution Successful ===
File Writer
import [Link].*;
class Filewriter
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
[Link]("Welcome to javaTpoint.");
[Link]();
}
catch(Exception e)
{
[Link](e);
}
[Link]("Success...");
}
}
Output:
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
File Reader
import [Link].*;
public class Filereader
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();
}
}
Output:
FileInputStream
import [Link].*;
public class Fileinputstream
{
public static void main(String args[])
{
try
{
FileInputStream f=new FileInputStream("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
int i=0;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
FileOutputStream: Java FileOutputStream is an output stream used for writing data to a file.
import [Link].*;
class Fileoutputstream
{
public static void main(String args[])
{
try
{
FileOutputStream fw=new FileOutputStream("C:\\Users\\MY COMPUTER\\Desktop\\[Link]");
String s="Welcome to java.";
byte b[]=[Link]();//converting string into byte array
[Link](b);
[Link]();
}
catch(Exception e)
{
[Link](e);
}
[Link]("Success...");
}
}
Output:
Multithreading in Java
FileName: [Link]
// ABC class implements the interface Runnable
class ABC implements Runnable
{
public void run()
{
// try-catch block
try
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
{
// moving thread t2 to the state timed waiting
[Link](100);
}
catch (InterruptedException ie)
{
[Link]();
}
[Link]("The state of thread t1 while it invoked the method join() on thread t2 -"+ [Link]
e());
// try-catch block
try
{
[Link](200);
}
catch (InterruptedException ie)
{
[Link]();
}
}
}
// ThreadState class implements the interface Runnable
public class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;
// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();
t1 = new Thread(obj);
// thread t1 is spawned
// The thread t1 is currently in the NEW state.
[Link]("The state of thread t1 after spawning it - " + [Link]());
// invoking the start() method on
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
// the thread t1
[Link]();
// thread t1 is moved to the Runnable state
[Link]("The state of thread t1 after invoking the method start() on it - " + [Link]());
}
public void run()
{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);
// thread t2 is created and is currently in the NEW state.
[Link]("The state of thread t2 after spawning it - "+ [Link]());
[Link]();
// thread t2 is moved to the runnable state
[Link]("the state of thread t2 after calling the method start() on it - " + [Link]());
// try-catch block for the smooth flow of the program
try
{
// moving the thread t1 to the state timed waiting
[Link](200);
}
catch (InterruptedException ie)
{
[Link]();
}
[Link]("The state of thread t2 after invoking the method sleep() on it - "+ [Link]() );
// try-catch block for the smooth flow of the program
try
{
// waiting for thread t2 to complete its execution
[Link]();
}
catch (InterruptedException ie)
{
[Link]();
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
[Link]("The state of thread t2 when it has completed it's execution - " + [Link]());
}
}
Output:
java -cp /tmp/OF7Bm3u9Gz/ThreadState
The state of thread t1 after spawning it - NEW
The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED
=== Code Execution Successful ===
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Output:
thread is running...
=== Code Execution Successful ===
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
}
}
Output:
thread is running..
Using the Thread Class: Thread(String Name)
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");
// the start() method moves the thread to the active state
[Link]();
// getting the thread name by invoking the getName() method
String str = [Link]();
[Link](str);
}
}
Output:
My first thread
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Using the Thread Class: Thread(Runnable r, String name)
Observe the following program.
FileName: [Link]
public class MyThread2 implements Runnable
{
public void run()
{
[Link]("Now the thread is running ...");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
[Link]();
// getting the thread name by invoking the getName() method
String str = [Link]();
[Link](str);
}
}
Output:
My new thread
Now the thread is running ...
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
class A extends Thread
{
public void run()
{
for(inti=1;i<=5;i++)
{
[Link]("ABC");
}
}
}
class BT
{
public static void main(String args[])
{
A ob=new A();
[Link]();
for(inti=1;i<=5;i++)
{
[Link]("XYZ");
}
}
}
Output:
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
Use of sleep()
class A extends Thread
{
// This run method is the override method.
// we cannot handle the exception in override method using throws keyword we have to use the try and catch
statement.
// This program will get executed in 5 seconds.
public void run()
{
try
{
for(inti=1;i<=5;i++)
{
[Link]("ABC");
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link]("Exception handled");
}
}
}
class BT
{
public static void main(String args[]) throws InterruptedException
{
A ob=new A();
[Link]();
for(inti=1;i<=5;i++)
{
[Link]("XYZ");
[Link](1000);
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
Output:
If we are chaning the name of run method to fun. Now in the code there is only one thread main that is
executiong. So it will call fun methods for 5 times and the total time taken here is 10 seconds.
class A extends Thread
{
// This run method is the override method.
// we cannot handle the exception in override method using throws keyword we have to use the try and catch
statement.
public void fun()
{
try
{
for(inti=1;i<=5;i++)
{
[Link]("ABC");
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link]("Exception handled");
}
}
}
class BTT
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
{
public static void main(String args[]) throws InterruptedException
{
A ob=new A();
[Link]();
for(inti=1;i<=5;i++)
{
[Link]("XYZ");
[Link](1000);
}
}
}
Output:
By implementing runnable interface
class A implements Runnable
{
public void run()
{
for(inti=1;i<=5;i++)
{
[Link]("Child Thread");
}
}
public static void main(String args[])
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
A ob=new A();
Thread t1 =new Thread(ob); // Using the constructor Thread(Runnable r)
[Link]();
for(inti=1;i<=5;i++)
{
[Link]("Main Thread");
}
}
}
Output:
java -cp /tmp/muljl24eZP/A
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
=== Code Execution Successful ===
Thread Priority
class A extends Thread
{
public void run()
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
}
}
class TB
{
public static void main(String args[])
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
{
A t1=new A();
A t2=new A();
A t3=new A();
[Link]("Thread1");
[Link]("Thread2");
[Link]("Thread3");
[Link]();
[Link]();
[Link]();
}
}
Output:
// The order of the output may change.
Setting the priority
class A extends Thread
{
public void run()
{
[Link]([Link]().getName());
[Link]([Link]().getPriority());
}
}
class SP
{
public static void main(String args[])
{
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
A t1=new A();
A t2=new A();
A t3=new A();
[Link]("Thread1");
[Link]("Thread2");
[Link]("Thread3");
[Link](2);
[Link](5);
[Link](8);
[Link]();
[Link]();
[Link]();
}
}
Output:
Output may change on each execution
The range of priority is between 1 to 10
If we set the priority to 11 or 12 or anything other than the range value then it will give the error.
Synchronization
class Table
{
public void printtable(int n)
{
for(inti=1;i<=10;i++)
{
[Link](n*i);
}
}
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
class thread1 extends Thread
{
Table t;
thread1(Table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class thread2 extends Thread
{
Table t;
thread2(Table t)
{
this.t=t;
}
public void run()
{
[Link](7);
}
}
classATable
{
public static void main(String args[])
{
Table obj=new Table();
thread1 t1=new thread1(obj);
thread2 t2=new thread2(obj);
[Link]();
[Link]();
SRMS CET R- Shri Ram Murti Smarak College Of Engineering, Technology & Research,Bareilly
}
}
Output: Mix Output
Now we will synchronizedthe thread using synchronizedkeyword.
class Table
{
publicsynchronized void printtable(int n)
{
for(inti=1;i<=10;i++)
{
[Link](n*i);
}
}
}
Output: