You are on page 1of 51

Student Record

importjava.util.Scanner;
class Record1
{
String name;
int age;
String course;
voidgetdata(String n,inta,String c)
{
name=n;
age=a;
course=c;
}
void show()
{
System.out.println("Name="+name);
System.out.println("age="+age);
System.out.println("coursee="+course);
}
}
class Record
{
public static void main(String args[])
{
Record1 r1=new Record1();
Record1 r2=new Record1();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the First Student record: ");
String n1=sc.next();
int a1=sc.nextInt();
String s1=sc.next();
r1.getdata(n1,a1,s1);
System.out.println("Enter the Second Student record: ");
String n2=sc.next();
int a2=sc.nextInt();
String s2=sc.next();
r2.getdata(n2,a2,s2);
System.out.println("Student Record 1: ");
r1.show();
System.out.println("Student Record 2: ");
r2.show();
}
}

Sum and product of digits

importjava.util.*;

classDigitsOpr
{
privateintnum;

//function to get value of num


public void getNum(int x)
{
num=x;
}/*End of getNum()*/

//function to calculate product of all digits


publicintproductDigits()
{
intn,pro;
n=num; //keep value of num safe
pro=1;
while(n>0)
{
pro *=(n%10); //find digit using n=n%10
n/=10;
}
return pro;
}//End of productDigits()
}

publicclass number1
{
publicstatic void main(String []s)
{
DigitsOpr dig=newDigitsOpr();
int n;

Scanner sc=newScanner(System.in);

//read number
System.out.print("Enter an +ve integer number:");
n=sc.nextInt();

dig.getNum(n);
System.out.println("SUM of all digits: " + dig.sumDigits());
System.out.println("PRODUCT of all digits: " + dig.productDigits());

}
}

Area and perimeter of a circle

importjava.util.*;

classAreaOfCircle
{
private float radius=0.0f;
private float area=0.0f;
private float perimeter=0.0f;

//function to read radius


public void readRadius()
{
//Scanner class - to read value from keyboard
Scanner sc=newScanner(System.in);
System.out.print("Enter radius:");
radius=sc.nextFloat(); //to read float value from keyboard
}

//funtction to calculate area


//return value - will return calculated area
public float getArea()
{
area= Math.PI *radius*radius;
return area;
}

//funtction to calculate perimeter


//return value - will return calculated perimeter
public float getPerimeter()
{
perimeter = 2* Math.PI *radius;
return perimeter;
}
}
publicclass circle
{
publicstatic void main(String []s)
{
AreaOfCircle area=newAreaOfCircle();

area.readRadius();
System.out.println("Area of circle:" + area.getArea());
System.out.println("Perimeter of circle:" + area.getPerimeter());
}
}

Method overloading

Volume of cube is 27
Volume of cylinder is 113.03999999999999
Volume of cuboid is 84
TO find area and perimeter of a circle
importjava.util.*;

//class Distance to read, print and add distance


class Distance
{
privateint feet;
privateint inches;

public void getDistance()


{
Scanner sc=newScanner(System.in);

System.out.print("Enter feet: ");


feet=sc.nextInt();
System.out.print("Enter inches: ");
inches=sc.nextInt();
}
public void showDistance()
{
System.out.println("Feet: "+ feet + "\tInches: "+ inches);
}

public void addDistance(Distance D1, Distance D2)


{
inches=D1.inches+D2.inches;
feet=D1.feet+D2.feet+(inches/12);
inches=inches%12;
}
}

publicclassAddTwoDistance
{
publicstatic void main(String []s)
{
try
{

Distance D1=newDistance();
Distance D2=newDistance();
Distance D3=newDistance();

//read first distance


System.out.println("Enter first distance: ");
D1.getDistance();

//read second distance


System.out.println("Enter second distance: ");
D2.getDistance();

//add distances
D3.addDistance(D1,D2);
//print distance
System.out.println("Total distance is:" );
D3.showDistance();
}
catch (Exception e)
{
System.out.println("Exception occurred :"+ e.toString());
}
}
}

Nesting of methods

1. import java.util.Scanner;
2. public class Nesting_Methods
3. {
4. int perimeter(int l, int b)
5. {
6. intpr = 12 * (l + b);
7. return pr;
8. }
9. int area(int l, int b)
10. {
11. intpr = perimeter(l, b);
12. System.out.println("Perimeter:"+pr);
13. intar = 6 * l * b;
14. return ar;
15. }
16. int volume(int l, int b, int h)
17. {
18. intar = area(l, b);
19. System.out.println("Area:"+ar);
20. intvol ;
21. vol = l * b * h;
22. return vol;
23. }
24. public static void main(String[] args)
25. {
26. Scanner s = new Scanner(System.in);
27. System.out.print("Enter length of cuboid:");
28. int l = s.nextInt();
29. System.out.print("Enter breadth of cuboid:");
30. int b = s.nextInt();
31. System.out.print("Enter height of cuboid:");
32. int h = s.nextInt();
33. Nesting_Methodsobj = new Nesting_Methods();
34. intvol = obj.volume(l, b, h);
35. System.out.println("Volume:"+vol);
36. }
37. }

Create a class Account with two overloaded constructors. The first


constructor is used for initializing, the name of account holder, the account
number and the initial amount in the account. The second constructor is used
for initializing the name of the account holder, the account number, the
addresses, the type of account and the current balance. The Account class is
having methods Deposit (), Withdraw (), and Get_Balance(). Make the
necessary assumption for data members and return types of the methods.
Create objects of Account class and use them.

class account
{
String name,address,type;
intaccno,bal;
account(String n,intno,int b)
{ name=n; accno=no; bal=b; }
account(String n,intno,Stringaddr,Stringt,int b)
{
name=n; accno=no;
address=addr;
type=t; bal=b;
}
void deposite(int a) { bal+=a; }
void withdraw(int a) { bal-=a; }
intgetbalance() { return(bal); }
void show()
{
System.out.println("________________________");
System.out.println(" ACCOUNT DETAILS");
System.out.println("------------------------");
System.out.println("Name : "+name);
System.out.println("Account No : "+accno);
System.out.println("Address : "+address);
System.out.println("Type : "+type);
System.out.println("Balance : "+bal);
System.out.println("------------------------");
}
}
class s03_02
{
public static void main(String arg[])throws Exception
{
account a1=new account("Anil",555,5000);
account a2=new account("Anil",666,"Tirur","Current account",1000);
a1.address="Calicut";
a1.type="fixed deposite";
a1.deposite(5000);
a2.withdraw(350);
a2.deposite(a2.getbalance());
a1.show();
a2.show();
}
}
//SavingsAccount.java - Jimmy Kurian

public class SavingsAccount

private double balance;

private double interest;

public SavingsAccount()

balance = 0;

interest = 0;

public SavingsAccount(double initialBalance, double initialInterest)

{
balance = initialBalance;

interest = initialInterest;

public void deposit(double amount)

balance = balance + amount;

public void withdraw(double amount)

balance = balance - amount;

public void addInterest()

{
balance = balance + balance * interest;

public double getBalance()

return balance;

}
SavingsAccountTester.java

//SavingsAccountTester.java - Jimmy Kurian

public class SavingsAccountTester

public static void main(String[] args)

{
SavingsAccountjimmysSavings = new SavingsAccount(1000, 0.10);

jimmysSavings.withdraw(250);

jimmysSavings.deposit(400);

jimmysSavings.addInterest();

System.out.println(jimmysSavings.getBalance());

System.out.println("Expected: 1265.0");

//1000-250=750 => 750+400=1150 => 1150+1150*0.10=1265.0

1. public class Student {


2.
3. String name;
4. int age;
5. String email;
6.
7. public void setData(String name,int age)
8. {
9. this.name=name;
10. this.age=age;
11. }
12.
13. public void setData(String name,int age, String email)
14. {
15. this.name=name;
16. this.age=age;
17. this.email=email;
18. }
19.
20. public void display()
21. {
22. System.out.println(name);
23. System.out.println(age);
24. System.out.println(email);
25. }
26.
27. public static void main(String[] args) {
28. Student s1=new Student();
29. s1.setData("Shanthi", 20);
30. Student s2=new Student();
31. s1.setData("Veera", 25,"veera@candidjava.com");
32.
33. }
34. }

importjava.util.Scanner;

class Employee
{
int age;
String name, address, gender;
Scanner get = new Scanner(System.in);
Employee()
{
System.out.println("Enter Name of the Employee:");
name = get.nextLine();
System.out.println("Enter Gender of the Employee:");
gender = get.nextLine();
System.out.println("Enter Address of the Employee:");
address = get.nextLine();
System.out.println("Enter Age:");
age = get.nextInt();
}

void display()
{
System.out.println("Employee Name: "+name);
System.out.println("Age: "+age);
System.out.println("Gender: "+gender);
System.out.println("Address: "+address);
}
}

classfullTimeEmployees extends Employee


{
float salary;
int des;
fullTimeEmployee()
{
System.out.println("Enter Designation:");
des = get.nextInt();
System.out.println("Enter Salary:");
salary = get.nextFloat();
}
void display()
{
System.out.println("=============================="+"\n"+"Full
Time Employee Details"+"\n"+"=============================="+"\n");
super.display();
System.out.println("Salary: "+salary);
System.out.println("Designation: "+des);
}
}

classpartTimeEmployees extends Employee


{
intworkinghrs, rate;
partTimeEmployees()
{
System.out.println("Enter Number of Working Hours:");
workinghrs = get.nextInt();
}
voidcalculatepay()
{
rate = 8 * workinghrs;
}

void display()
{
System.out.println("=============================="+"\n"+"Part
Time Employee Details"+"\n"+"=============================="+"\n");
super.display();
System.out.println("Number of Working Hours: "+workinghrs);
System.out.println("Salary for "+workinghrs+" working hours is: $"+rate);
}
}

class Employees
{
public static void main(String args[])
{
System.out.println("================================"+"\n"+"Ent
er Full Time Employee
Details"+"\n"+"================================"+"\n");
fullTimeEmployees ob1 = new fullTimeEmployees();
partTimeEmployeesob = new partTimeEmployees();
System.out.println("================================"+"\n"+"Ent
er Part Time Employee
Details"+"\n"+"================================"+"\n");
ob1.display();
ob.calculatepay();
ob.display();
}
}

1. import java.util.Scanner;
2.
3. public class Employee {
4.
5. intempid;
6. String name;
7. float salary;
8.
9. public void getInput() {
10.
11. Scanner in = new Scanner(System.in);
12. System.out.print("Enter the empid :: ");
13. empid = in.nextInt();
14. System.out.print("Enter the name :: ");
15. name = in.next();
16. System.out.print("Enter the salary :: ");
17. salary = in.nextFloat();
18. }
19.
20. public void display() {
21.
22. System.out.println("Employee id = " + empid);
23. System.out.println("Employee name = " + name);
24. System.out.println("Employee salary = " + salary);
25. }
26.
27. public static void main(String[] args) {
28.
29. Employee e[] = new Employee[5];
30.
31. for(int i=0; i<5; i++) {
32.
33. e[i] = new Employee();
34. e[i].getInput();
35. }
36.
37. System.out.println("**** Data Entered as below ****");
38.
39. for(int i=0; i<5; i++) {
40.
41. e[i].display();
42. }
43. }
44. }

1. import java.lang.*; // import language package


2.
3. interface Gross // interface declaration
4. {
5. double ta=800.0;
6. double da=1500.0; // final variable
7. void gross_sal();
8. }
9.
10. class Employee // super class declaration
11. {
12. String name; // data member declaration
13. float basic_sal;
14.
15. Employee(String n, float b) // super class constructor
16. {
17. name=n;
18. basic_sal=b;
19. }
20.
21. void display() // method to display value of data member
22. {
23. System.out.println("Name of Employee : "+name);
24. System.out.println("Basic Salary of Employee : "+basic_sal);
25. }
26. }
27.
28. class Salary extends Employee implements Gross // sub class constructor
29. {
30. float hra;
31.
32. Salary(String n, float b, float h) // sub class constructor
33. {
34. super(n,b);
35. hra=h;
36. }
37.
38. void disp()
39. {
40. display();
41. System.out.println("HRA of Employee : "+hra);
42. }
43.
44. public void gross_sal() // method to calculate gross salary
45. {
46. double gross_sal=basic_sal + ta + da + hra;
47. System.out.println("TA of Employee : "+ta);
48. System.out.println("DA of Employee : "+da);
49. System.out.println("Gross Salary of Employee : "+gross_sal);
50. }
51. }
52.
53. public class EmpDetails {
54.
55. public static void main(String args[]) // main method
56. {
57. Salary s = new Salary("Sachin",8000,3000); // initiating Sub class
58. s.disp(); // invoke method of sub class
59. s.gross_sal();
60. }
61. }

class students
{
privateintsno;
private String sname;
public void setstud(intno,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protectedint mark1,mark2;
public void setmarks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
public void putmarks()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}
}
classfinaltot extends marks
{
privateint total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}

Write a Java program for creating one base class for student personal details
and inherit those details into the sub class of student Educational details to
display complete student information.

Description:

Inheritance is one of the cornerstones of object-oriented programming because it


allows the creation of hierarchical classifications. Using inheritance, you can create
a general class that defines traits common to a set of related items. This class can
then be inherited by other, more specific classes, each adding those things that are
unique to it. In the terminology of Java, a class that is inherited is called a
superclass. The class that does the inheriting is called a subclass. Therefore, a
subclass is a specialized version of a superclass. It inherits all of the instance
variables and methods defined by the superclass and add its own, unique elements.
//PROGRAM

class Personal
{
String name=new String();
String fname=new String();
String add=new String();
String phno=new String();
Personal(String a,Stringb,Stringc,String d)
{
name=a;
fname=b;
add=c;
phno=d;
}

void display()
{
System.out.println("Name is "+name);
System.out.println("Address "+add);
System.out.println("Father's Name is "+fname);
System.out.println("Contact number "+phno);
}
}
class Education extends Personal
{
introll,age;
char section;
String branch=new String();
Education(String a, String b, String c, String d, int e, int f, char g, String h)
{
super(a,b,c,d);
roll=e;
age=f;
section=g;
branch=h;
}
void display2()
{
super.display();
System.out.println("Roll Number="+roll);
System.out.println("AGE="+age);
System.out.println("SECTION="+section);
System.out.println("Branch is "+branch);

class Hello
{
public static void main(String args[])
{
Education e=new
Education("KRISH","RAM","VIZAG","9885098850",10,19,'B',"IT");
e.display2();
}
}

EMPLOYEE DETAILS USING PACKAGE in java


EMPLOYEE DETAILS USING PACKAGE

package Employee1;

public class Emp

String name,empid,cty;

int bpay;

double hra ,da,npay,pf;

public Emp(String n,String id,String c,int b)

{
name=n;

empid=id;

cty=c;

bpay=b;

public void call()

da=bpay*0.05;

hra=bpay*0.05;

pf=bpay*0.08;

npay=bpay+da+hra-pf;

public void display()

System.out.println("\n\t\t EMPLOYEE DETAILS");

System.out.println("\n Name : "+name);

System.out.println("\n Employee ID : "+empid);

System.out.println("\n Category : "+cty);

System.out.println("\n bpay : "+bpay);

System.out.println("\n hra : "+hra);

System.out.println("\n da : "+da);

System.out.println("\n pf: "+pf);

System.out.println("\n npay: "+npay);

}
import java.io.*;

import java.util.*;

import Employee1.Emp;

class Emppay

public static void main(String args[]) throws IOException

Emp e=new Emp("Rama","IT101","Female",10000);

e.call();

e.display();

Multithreading in Java

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.

filter_none

edit

play_arrow

brightness_4

// 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<8; 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 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.current
Thread().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<8; i++)

Thread object = new Thread(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 Class vs Runnable Interface

1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can still
extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.

Predefined Exceptions

class Ex1{
public static void main (String [] args)
{
try
{
String s1=args[0];
String s2=args[1];
int n1=Integer.parseInt (s1);
int n2=Integer.parseInt (s2);
int n3=n1/n2;
System.out.println ("DIVISION VALUE = "+n3);
}
catch (ArithmeticException Ae)
{
System.out.println ("DONT ENTER ZERO FOR DENOMINATOR...");
}
catch (NumberFormatException Nfe)
{
System.out.println ("PASS ONLY INTEGER VALUES...");
}
catch (ArrayIndexOutOfBoundsException Aioobe)
{
System.out.println ("PASS DATA FROM COMMAND PROMPT...");
}
finally
{
System.out.println ("I AM FROM FINALLY...");
}
}};
User Defined Exceptions

public class UserDefinedException {

public static void main(String args[]) {


Account acct = new Account();
System.out.println("Current balance : " + acct.balance());
System.out.println("Withdrawing $200");
acct.withdraw(200);
System.out.println("Current balance : " + acct.balance());
acct.withdraw(1000);

}
/** * Java class to represent a Bank account which holds your balance and
provide wi */ public class Account {

private int balance = 1000;

public int balance() {


return balance;
}

public void withdraw(int amount) throws NotSufficientFundException {


if (amount > balance) {
throw new NotSufficientFundException(String.format("Current
balance %d is less than requested amount %d", balance, amount));
}
balance = balance - amount;
}

public void deposit(int amount) {


if (amount <= 0) {
throw new IllegalArgumentException(String.format("Invalid deposit
amount %s", amount));
}
}

/** * User defined Exception class in Java */ public class


NotSufficientFundException extends RuntimeException {

private String message;

public NotSufficientFundException(String message) {


this.message = message;
}

public NotSufficientFundException(Throwable cause, String message) {


super(cause);
this.message = message;
}

public String getMessage() {


return message;
}

Output
Current balance : 1000
Withdrawing $200
Current balance : 800
Exception in thread "main" NotSufficientFundException: Current balance 800 is
less than requested amount 1000
at Account.withdraw(Testing.java:68)
at Testing.main(Testing.java:51)

That's all about how to create a user-defined exception in Java. You can see
here use of NotSufficientFundException not only help you to show a more
meaningful message to the user but also helps in debugging and logging. If you
look at this exception in the log file you will immediately find the cause of
error. Little bit difficult part is choosing between checked and unchecked
exception to create a custom Exception. You should by default use
RuntimeException to make your user define exception unchecked mainly to avoid
clutter, but if you want to ensure that client must handle that exception then
make sure to inherit from Exception to create a user defined checked
exception.

Multithreading

Using Runnable Interface

class MyThread implements Runnable {


String name;
Thread t;
MyThread String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

List of Java Programs and Code Examples on


Multithreading covered here
The Java programs covered in this section range from basic to advance and
tricky. They cover:

1. Program to implement thread using runnable interface


2. Program to creating multiple thread
3. Program for producer consumer problem
4. Program to set priorities of thread
5. Program to display all running thread
6. Program for Synchronization block
7. Program to stop thread execution with ctrl+c
8. Program to print Fibonacci & reverse series

How to implement thread using runnable interface in Java.

Answer:

Runnable Interface:
The runnable interface is designed to provide a common procedure objects that
wish to execute code while they are active.
MyThread.java

class MyThread implements Runnable


{
String message;
MyThread(String msg)
{
message = msg;
}
public void run()
{
for(int count=0;count<=5;count++)
{
try
{
System.out.println("Run method: " + message);
Thread.sleep(100);
}
catch (InterruptedException ie)
{
System.out.println("Exception in thread: "+ie.getMessage());
}
}
}
}

MainThread.java

public class MainThread


{
public static void main(String[] args)
{
MyThread obj1 = new MyThread("MyThread obj1");
MyThread obj2 = new MyThread("MyThread obj2");
Thread t1 = new Thread(obj1);
Thread t2 = new Thread(obj2);
t1.start();
t2.start();
}
}

Output:
Q. Write a Java program to create multiple thread in Java.

Answer:

Multithreading is the process of executing multiple thread simultaneously.


There are two ways to create multiple thread in java. First is by using
runnable interface and second is by using Thread class. The Thread class
extends to creates the multiple thread in java.

MultipleThread.java

class ThreadTest extends Thread


{
private Thread thread;
private String threadName;

ThreadTest( String msg)


{
threadName = msg;
System.out.println("Creating thread: " + threadName );
}
public void run()
{
System.out.println("Running thread: " + threadName );
try
{
for(int i = 0; i < 5; i++)
{
System.out.println("Thread: " + threadName + ", " + i);
Thread.sleep(50);
}
}
catch (InterruptedException e)
{
System.out.println("Exception in thread: " + threadName);
}
System.out.println("Thread " + threadName + " continue...");
}
public void start ()
{
System.out.println("Start method " + threadName );
if (thread == null)
{
thread = new Thread (this, threadName);
thread.start ();
}
}
}
public class MultipleThread
{
public static void main(String args[])
{
ThreadTest thread1 = new ThreadTest( "First Thread");
thread1.start();

ThreadTest thread2 = new ThreadTest( "Second Thread");


thread2.start();
}
}

Output:
Q. Write a Java program using Synchronized Threads, which demonstrates
Producer Consumer concept.

Answer:

Producer Consumer problem:


The producer-consumer problem is the classical concurrency of a multi process
synchronization problem. It is also known as bound-buffer problem.

The problem describes two processes, the producer and the consumer, who
share a common, fixed-size buffer used as a queue. The producer generates a
piece of data, put it into the buffer and starts again.

ProducerConsumer.java

public class ProducerConsumer


{
public static void main(String[] args)
{
Shop c = new Shop();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Shop
{
private int materials;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException ie)
{
}
}
available = false;
notifyAll();
return materials;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
materials = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private Shop Shop;
private int number;
public Consumer(Shop c, int number)
{
Shop = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = Shop.get();
System.out.println("Consumed value " + this.number+ " got: " + value);
}
}
}
class Producer extends Thread
{
private Shop Shop;
private int number;

public Producer(Shop c, int number)


{
Shop = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{
Shop.put(i);
System.out.println("Produced value " + this.number+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}

Output:
Q. Write a program to set the priorities of the thread.

Answer:

Thread priorities:
In Java, each thread has a priority. Priorities are represented by number from
0 to 10. The default priority of NORM_PRIORITY is 5, MIN_PRIORITY is 1 and
MAX_PRIORITY is 10.

In this example, we calculate the priority of each thread. The setPriority()


method is used to set the priority of the thread.

ThreadPriority.java

public class ThreadPriority extends Thread


{
public void run()
{
System.out.println("run() method");
String threadName = Thread.currentThread().getName();
Integer threadPrio = Thread.currentThread().getPriority();
System.out.println(threadName + " has priority " + threadPrio);
}
public static void main(String[] args) throws InterruptedException
{
ThreadPriority t1 = new ThreadPriority();
ThreadPriority t2 = new ThreadPriority();
ThreadPriority t3 = new ThreadPriority();

t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);

t1.start();
t2.start();
t3.start();
}
}

Output:
Q. Write a program to display all running threads in Java.

Answer:

Thread class have some methods to count the current running thread.

RunningThread.java

class RunningThread extends Thread


{
public static void main(String[] args)
{
System.out.println("Main methods");
RunningThread obj = new RunningThread();
//set the thread name2
obj.setName("\nThreadName ");
//calling run () method
obj.start();

ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();


int numThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[numThreads];
currentGroup.enumerate(lstThreads);
//System.out.println(currentThread);
for (int i =1;i< numThreads ; i++)
{
System.out.println("Number of thread: "+i + " " + lstThreads[i].getName());
}

//checking the current running thread


Thread currentThread = Thread.currentThread();
System.out.println("Current running thread: "+currentThread);
}
}

Ouput:

Q. Write a program to demonstrate the Synchronization block.

Answer:

Synchronization:
Synchronization is the process of allowing threads to execute one after
another. It provides the control to access multiple threads to shared
resources. When we want to allow one thread to access the shared resource,
then synchronization is the better option.

In this example, the synchronized block prevents to create the random thread.
The threads are executed sequentially.

SynchTest.java

class SynchTest
{
void printNumber(int n)
{
synchronized(this)
{
System.out.println("Table of "+n);
System.out.println("==========");
for(int i=1;i<=10;i++)
{
System.out.println(n+" * "+i+" = "+(n*i));
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}

MyThread1.java

class MyThread1 extends Thread


{
SynchTest t;
MyThread1(SynchTest t)
{
this.t=t;
}
public void run()
{
t.printNumber(7);
}
}

SynchronizedBlock.java

public class SynchronizedBlock


{
public static void main(String args[])
{
SynchTest obj = new SynchTest();
MyThread1 t1=new MyThread1(obj);
t1.start();
}
}

Output:

Write a program that creates 2 threads - each displaying a message (Pass the
message as a parameter to the constructor). The threads should display the
messages continuously till the user presses ctrl+c.

Answer:

If any application threads (daemon or nondaemon) are still running at shutdown


time, then the user just presses the ctrl+c to stop thread execution.

Thread1.java

class Thread1 extends Thread


{
String msg = "";
Thread1(String msg)
{
this.msg = msg;
}
public void run()
{
try
{
while (true)
{
System.out.println(msg);
Thread.sleep(300);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Thread2.java

class Thread2 extends Thread


{
String msg = "";
Thread2(String msg)
{
this.msg = msg;
}
public void run()
{
try
{
while (true)
{
System.out.println(msg);
Thread.sleep(400);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
ThreadDemo.java

class ThreadDemo
{
public static void main(String[] args)
{
Thread1 t1 = new Thread1("Running Thread1....");
Thread1 t2 = new Thread1("Running Thread2....");
t1.start();
t2.start();
}
}

Output:

Run the ThreadDemo.java. Press ctrl+c to stop the execution of the running
thread.

Write a JAVA program which will generate the threads:

- To display 10 terms of Fibonacci series.


- To display 1 to 10 in reverse order.

Answer:

We develop two classes, one for finding Fibonacci series and other is for the
reverse number.
Fibonacci.java

import java.io.*;
class Fibonacci extends Thread
{
public void run()
{
try
{
int a=0, b=1, c=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the Limit for fabonacci: ");

int n = Integer.parseInt(br.readLine());
System.out.println("\n=================================");
System.out.println("Fibonacci series:");
while (n>0)
{
System.out.print(c+" ");
a=b;
b=c;
c=a+b;
n=n-1;
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Reverse.java

class Reverse extends Thread


{
public void run()
{
try
{
System.out.println("\n=================================");
System.out.println("\nReverse is: ");
System.out.println("=================================");
for (int i=10; i >= 1 ;i-- )
{
System.out.print(i+" ");
}
System.out.println("\n=================================\n\n");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

MainThread.java

class MainThread
{
public static void main(String[] args)
{
try
{
Fibonacci fib = new Fibonacci();
fib.start();
fib.sleep(4000);
Reverse rev = new Reverse();
rev.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Output:
Create a class Student with attributes roll no, name, age and course.
Initialize values through parameterized constructor. If age of student is not
in between 15 and 21 then generate user-defined exception
"AgeNotWithinRangeException". If name contains numbers or special symbols
raise exception "NameNotValidException". Define the two exception classes.

Answer:

Student class with the parameterized constructor to initialize the student


record. If the inserted record is not valid, it generates user defined
exception.

AgeNotWithInRangeException.java

class AgeNotWithInRangeException extends Exception


{
public String toString()
{
return ("Age is not between 15 and 21. please ReEnter the Age");
}
}

NameNotValidException.java
class NameNotValidException extends Exception
{
public String validname()
{
return ("Name is not Valid..Please ReEnter the Name");
}
}

Student.java

class Student
{
int roll,age;
String name,course;
Student()
{
roll=0;
name=null;
age=0;
course=null;
}
Student(int r,String n,int a,String c)
{
roll=r;
course=c;
int l,temp=0;
l = n.length();
for(int i=0;i<l;i++)
{
char ch;
ch=n.charAt(i);
if(ch<'A' || ch>'Z' && ch<'a' || ch>'z')
temp=1;
}
/*———-Checking Name——————–*/
try
{
if(temp==1)
throw new NameNotValidException();
else
name=n;
}
catch(NameNotValidException e2)
{
System.out.println(e2);
}
/*———-Checking Age——————–*/
try
{
if(a>=15 && a<=21)
age=a;
else
throw new AgeNotWithInRangeException();
}
catch(AgeNotWithInRangeException e1)
{
System.out.println(e1);
}
}
void display()
{
System.out.println("roll Name Age Course");
System.out.println("---------------------");
System.out.println(roll+" "+name+" "+age+" " +course);
}
}

StudentDemo.java

import java.io.*;
class StudentDemo
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter roll number: ");


int roll = Integer.parseInt(br.readLine());
System.out.print("\nEnter name: ");
String name = br.readLine();
System.out.print("\nEnter age: ");
int age = Integer.parseInt(br.readLine());
System.out.print("\nEnter course: ");
String course = br.readLine();
Student s = new Student(roll,name,age,course);
s.display();
}
}
Output:

i. When we enter invalid name or age

ii. Enter valid name as well as age

You might also like