Lab Ex 2 Answers
Lab Ex 2 Answers
Lab Ex 2 Answers
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();
}
}
importjava.util.*;
classDigitsOpr
{
privateintnum;
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());
}
}
importjava.util.*;
classAreaOfCircle
{
private float radius=0.0f;
private float area=0.0f;
private float perimeter=0.0f;
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.*;
publicclassAddTwoDistance
{
publicstatic void main(String []s)
{
try
{
Distance D1=newDistance();
Distance D2=newDistance();
Distance D3=newDistance();
//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. }
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 SavingsAccount()
balance = 0;
interest = 0;
{
balance = initialBalance;
interest = initialInterest;
{
balance = balance + balance * interest;
return balance;
}
SavingsAccountTester.java
{
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");
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);
}
}
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. }
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:
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();
}
}
package Employee1;
String name,empid,cty;
int bpay;
{
name=n;
empid=id;
cty=c;
bpay=b;
da=bpay*0.05;
hra=bpay*0.05;
pf=bpay*0.08;
npay=bpay+da+hra-pf;
System.out.println("\n da : "+da);
}
import java.io.*;
import java.util.*;
import Employee1.Emp;
class Emppay
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.
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
try
Thread.currentThread().getId() +
" is running");
catch (Exception e)
{
// Throwing an exception
// Main Class
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
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.
try
Thread.current
Thread().getId() +
" is
running");
catch (Exception e)
// Throwing an exception
System.out.println ("Exception is caught");
// Main Class
class Multithread
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
}
/** * Java class to represent a Bank account which holds your balance and
provide wi */ public class Account {
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
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
MainThread.java
Output:
Q. Write a Java program to create multiple thread in Java.
Answer:
MultipleThread.java
Output:
Q. Write a Java program using Synchronized Threads, which demonstrates
Producer Consumer concept.
Answer:
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
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.
ThreadPriority.java
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
Ouput:
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
SynchronizedBlock.java
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:
Thread1.java
Thread2.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.
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));
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
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:
AgeNotWithInRangeException.java
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));