Khyaati Sharma / 02704092021 1
Java lab assignments
Q1. Write a program to print Hello World.
Code :
public class Main
{
public static void main(String[] args) {
[Link]("Hello World");
}
}
Output :
Khyaati Sharma / 02704092021 2
Q2. Write a program for Factorial of a number
Code :
import [Link];
class Main
{
public static void main(String args[])
{
int n, c, f = 1;
[Link]("Enter an integer to calculate its factorial");
Scanner in = new Scanner([Link]);
n = [Link]();
if (n < 0)
[Link]("Number should be non-negative.");
else
{
for (c = 1; c <= n; c++)
f = f*c;
[Link]("Factorial of "+n+" is = "+f);
} } }
Output :
Khyaati Sharma / 02704092021 3
Q3. Write a program to find if a number is Even or not.
Code :
import [Link];
class Main
{
public static void main(String args[])
{
int n;
[Link]("Enter a number");
Scanner in = new Scanner([Link]);
n = [Link]();
if (n %2== 0)
[Link]("Number is even.");
else
[Link]("Number is odd.");
}
}
Output :
Khyaati Sharma / 02704092021 4
Q4. Write a program to find if number is Prime number or not
Code :
import [Link];
class Main
{
public static void main(String args[])
{
int n,i;
int flag=0;
[Link]("Enter a number");
Scanner in = new Scanner([Link]);
n = [Link]();
for(i=2;i<n/2;i++)
{
if (n %i== 0)
flag=1;
}
if(flag==1)
[Link]("Number is not prime.");
else
[Link]("Number is prime.");
} }
Output :
Khyaati Sharma / 02704092021 5
Q5. Write a program to print Fibonacci series
Code :
import [Link];
class Main
{
public static void main(String args[])
{
int f=0,s=1,n,i;
int res=0;
[Link]("Enter a number:");
Scanner input = new Scanner([Link]);
n = [Link]();
[Link](f);
for(i=1;i<n;i++)
{
f=s;
s=res;
res=f+s;
[Link](res);
}
}
}
Output :
Khyaati Sharma / 02704092021 6
Q6 . Define a class Rectangle with its length and breadth.
Provide appropriate constructor(s), which gives the facility of
constructing rectangle objects with default values of length and
breadth as 0 or passing value of length and breadth externally to
the constructor. Provide appropriate accessor & mutator methods
to Rectangle class. Provide methods to calculate area & to
display all information of Rectangle
Design a different TestRectangle class in a separate source file,
which will contain the main function. From this main function,
create Rectangle objects by taking all necessary information from
the user.
Code :
import [Link];
class Rectangle {
int length;
int breadth;
int area;
Rectangle(){
length=0;
breadth=0;
}
Rectangle(int len, int b){
length=len;
breadth=b;
}
public int area(){
area= length*breadth;
return(area);
}
public void display(){
[Link]("Length = "+length);
[Link]("Breadth = "+breadth);
[Link]("Area = "+area);
Khyaati Sharma / 02704092021 7
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter Length : ");
int length= [Link]();
[Link]("Enter Breadth : ");
int breadth= [Link]();
Rectangle rec=new Rectangle(length,breadth);
[Link]();
[Link]();
}
}
Output :
Khyaati Sharma / 02704092021 8
Q7 . Create a class Book which describes its Book_title and
Book_price. Use getter and setter methods to get & set the Books
description. Create object of Book class .Display the books along
with its description as follows:Book Title Price Java Programming
Rs.350.50 Let Us C Rs.200.00
Code :
class BookInfo {
String title;
float price;
public String GetName(){
return title;
}
public float GetPrice(){
return price; }
public void SetName(String t){
title=t; }
public void SetPrice(float p) {
price = p; }
}
public class Book
{ public static void main(String[] args){
BookInfo b1;
b1=new BookInfo();
[Link]("Java Programming");
[Link](350.50f);
[Link]("Book Title: " + [Link]());
[Link]("Price: " + [Link]());
[Link]("Let us C");
[Link](200);
[Link]("Book Title: " + [Link]());
[Link]("Price: " + [Link]());
}
}
Khyaati Sharma / 02704092021 9
Output :
Q8. Modify the program which is created in assignment 2 as
follows The class has attributes length and width, each of which
defaults to 1. It should have member functions that calculate the
perimeter and area of the rectangle. It should have set and get
functions for both length and width. The set functions should
verify that length and width are each floating-point numbers
larger than 0.0 and less than 20.0.
Code :
import [Link];
class Rect {
float length;
float width;
public void Rect() {
length = 1.0f;
width = 1.0f;
}
public float perimeter() {
return 2 * (length + width);
Khyaati Sharma / 02704092021 10
}
public float area() {
return (length * width);
}
public void setLength(float len) {
if ((len > 0.0f) && (len < 20.0f))
length = len;
else
[Link]("Invalid Length");
}
public void setWidth(float wid) {
if ((wid > 0.0f) && (wid < 20.0f))
width = wid;
else
[Link]("Invalid Width");
}
public float getLength() {
return length;
}
public float getWidth() {
return width;
}
}
public class Main {
public static void main(String[] args) {
Rect rc = new Rect();
Scanner sc = new Scanner([Link]);
[Link]("Enter Length:");
float len= [Link]();
[Link]("Enter Width:");
float wid=[Link]();
[Link](len);
[Link](wid);
[Link]("Length of Rectangle= "+[Link]());
[Link]("Breadth of Rectangle= "+[Link]());
[Link]("Area of Rectangle= "+[Link]());
[Link]("Perimeter of Rectangle= "+[Link]());
Khyaati Sharma / 02704092021 11
}
}
Output :
Khyaati Sharma / 02704092021 12
Q9. Create a class Date for manipulating dates. Provide a
constructor that enables an object of this class to be initialized
when it is declared (You can select any default values for the day,
month & year, e.g. your birth date). Provide the necessary
functionality to perform error checking on the initializer values for
data members day, month, and year.
Design a separate class Employee which will have following
information.
Employee Number Number
Employee Name Text
Joining Date Date
Provide appropriate constructor(s) & methods to this class.
Provide a main function which will create an object of Employee
class.
Code :
import [Link];
import [Link];
class Date{
int day;
int month;
int year;
public Date(){
day=24;
month=8;
year=1999;
}
public void setDate(){
Scanner sc = new Scanner([Link]);
[Link]("Day \t Month \t
Year"); int d =[Link]();
int m =[Link]();
Khyaati Sharma / 02704092021 13
int y =[Link]();
if((d>31 && m>12 && y>2022) || (m==2 && d>28)) {
[Link]("Invalid Date");
}
else {
day=d;
month=m;
year=y;
}
}
public void displayDate(){
[Link](day+"/"+month+"/"+year);
}
}
class Employee{
long EmpNum;
String EmpName;
Date DOJ;
public Employee(){
EmpName="ABC";
EmpNum=123;
DOJ=new Date();
}
public void setEmployee(long num, String name){
EmpName=name;
EmpNum=num;
DOJ=new
Date();
[Link]();
}
public void displayEmployee(){
[Link]("Employee Number : "+EmpNum);
[Link]("Employee Name : "+EmpName);
[Link]("Date of Joining : ");
[Link]();
}
}
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
Khyaati Sharma / 02704092021 14
[Link]("Enter Employee Name : ");
String empname = [Link]();
[Link]("Enter Employee Number : ");
long empnum = [Link]();
Employee e1 = new Employee();
[Link](empnum, empname);
[Link]();
}
}
Output :
Q10. Write a program that accepts two numbers in the range
from 1 to 40 from the Command Line. It then compares these
numbers against a single dimension array of five integer elements
ranging in value from 1 to 40. The program displays the message
FOUND if the two inputted values are found in the array element.
Code:
import [Link].*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("khy_027 // java assignment 3 : ");
[Link]("Enter first number- ");
Khyaati Sharma / 02704092021 15
int a= [Link]();
[Link]("Enter first number-
");
int b= [Link]();
int afound=0,bfound = 0;
int arr[]=new int[5];
[Link]("enter the array numbers : ");
for(int i=0;i<[Link];i++)
arr[i]= [Link]();
for(int i=0;i<[Link];i++){
if(a==arr[i]){afound=1;}
if(b==arr[i]){bfound=1;}
}
if(afound==1&&bfound==1)
[Link]("found both element : ");
else if(afound==1&&bfound==0)
[Link]("found first element");
else if(afound==0&&bfound==1)
[Link]("found second element");
els
e [Link]("none found");
}
}
Output:
Khyaati Sharma / 02704092021 16
Q11. Write a program that allows you to create an integer array of
18 elements with the following values: int
A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0}. The program computes
the sum of element 0 to 14 and stores it at element 15, computes
the average and stores it at element 16 and identifies the smallest
value from the array and stores it at element.
Code :
import [Link].*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("khy_027 // java assignment 3 : ");
int sum=0,avg = 0;
int arr[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0};
int smallest = arr[0],temp;
for(int i=0;i<[Link];i++)
sum+=arr[i];
for(int i=0;i<14;i++)
{
if(smallest>arr[i+1]){
temp=smallest;
smallest=arr[i+1];
arr[i+1]=temp; }
}
avg=sum/15;
arr[15]=sum;
arr[16]=avg;
arr[17]=smallest;
[Link]("sum is : ");
[Link](sum);
[Link]("average is : ");
Khyaati Sharma / 02704092021 17
[Link](avg);
[Link]("smallest is : ");
[Link](smallest);
[Link]("updated array : ");
for(int i=0;i<[Link];i++){
[Link](arr[i]);
[Link](' ');
}
}
}
Output :
Khyaati Sharma / 02704092021 18
Q12. Write a program that accepts two numbers and a operator
like (+,-,*, /) as command line arguments and perform the
appropriate operation indicated by the operator. If the user enters
any other character the appropriate message will be displayed.
The output of the program should be displayed to the user.
Code :
import [Link].*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("khy_027 // java assignment 3 : ");
int res;
[Link]("Enter first number- ");
int a= [Link]();
[Link]("Enter second number- ");
int b= [Link]();
[Link]("Enter operation symbol - ");
char op= [Link]().charAt(0);
if(op=='+'){
res=a+b;
[Link]("sum is :");[Link](res);
} else if(op=='-'){
res=a-b;
[Link]("difference is :");[Link](res);
} else if(op=='*'){
res=a*b;
[Link]("product is :");[Link](res);
} else if(op=='/'){
res=a+b;
[Link]("quotient is :");[Link](res);
} else{[Link]("invalid operation entry !!");}
}
}
Khyaati Sharma / 02704092021 19
Output:
Q13. Create a class Car which contains members speed,
noOfGear. The class has a method drive() which is responsible to
provide starting speed and noOfGears to a Car. Implement
display() method which will display all attributes of Car class. The
class SportCar is derived from the class Car which adds new
features AirBallonType. When this method is invoked, initial speed
and gear status must be displayed on the console. Override the
display method which displays all attributes of the SportCar. Make
use of the super class display() method.
Code :
class Cars {
int speed;
int noOfGear;
public void drive(){
speed=40;
noOfGear=4;
}
public void Display(){
[Link]("Speed is: "+speed);
[Link]("No. of Gear: "+noOfGear);
Khyaati Sharma / 02704092021 20
}
}
class SportCar extends Cars{
private String s ="Air Ballon
Type"; public void display() {
[Link]();
[Link]("Special Feature: "+s);
}
}
public class Main {
public static void main(String[] args) {
SportCar sc = new SportCar();
[Link]();
[Link]();
}
}
Output:
Khyaati Sharma / 02704092021 21
Q14. Create a class of Medicine to represent a drug
manufactured by a pharmaceutical company. Provide a function
displayLabel() in this class to print Name and address of the
company. Derive Tablet, Syrup and Ointment classes from the
Medicine class. Override the displayLabel() function in each of
these classes to print additional information suitable to the type of
medicine. For example, in case of tablets, it could be “store in a
cool dry place”, in case of ointments it could be “for external use
only” etc.
Create a class TestMedicine . Write main function to do the
following:
Declare an array of Medicine references of size [Link] a
medicine object of the type as decided by a randomly generated
integer in the range 1 to 3.
Check the polymorphic behavior of the displayLabel() method.
Code :
class Medicine{
public void displayLabel()
{
[Link]("Enter the Name: Apollo Pharmacy");
[Link]("Address: Delhi");
}
}
class Tablet extends Medicine{
public void displayLabel()
{
[Link]("Store in a cool place");
}
}
class Syrup extends Medicine {
public void displayLabel(){
[Link]("Consumption as directed by the Physician");
Khyaati Sharma / 02704092021 22
}
}
class Ointment extends Medicine{
public void displayLabel() {
[Link]("For external use only");
}
}
public class Main {
public static void main(String[] args) {
Medicine m[] = new Medicine[10];
double i = [Link]() * 4;
int j = (int) i;
[Link](j);
switch (j) {
case 1:
m[0] = new Medicine();
m[1] = new Tablet();
m[0].displayLabel();
m[1].displayLabel();
break;
case 2:
m[2] = new Medicine();
m[3] = new Syrup();
m[2].displayLabel();
m[3].displayLabel();
break;
case 3:
m[4] = new Medicine();
m[5] = new Ointment();
m[4].displayLabel();
m[5].displayLabel();
break;
default:
[Link]("Invalid Choice");
}
} }
Khyaati Sharma / 02704092021 23
Output:
Q15. Create an abstract class Compartment to represent a rail
coach. Provide an abstract function notice in this class. Derive
FirstClass, Ladies, General, Luggage classes from the
compartment class. Override the notice function in each of them
to print a notice suitable to the type of the compartment.
Create a class TestCompartment . Write main function to do the
following:
Declare an array of Compartment pointers of size 10.
Khyaati Sharma / 02704092021 24
Create a compartment of a type as decided by a randomly
generated integer in the range 1 to 4.
Code :
abstract class Compartment{
abstract void notice();
}
class FirstClass extends Compartment{
void notice(){
[Link]("In FIRST CLASS");
}
}
class Ladies extends Compartment{
void notice(){
[Link]("In LADIES Compartment");
}
}
class Luggage extends Compartment{
void notice(){
[Link]("In LUGGAGE Compartment");
}
}
class General extends Compartment{
void notice(){
[Link]("In GENERAL Compartment");
}
}
public class Main {
public static void main(String[] args) {
Compartment c[] = new Compartment[10];
double i = [Link]() * 5;
int x = (int) i;
[Link](x);
switch (x) {
case 1:
c[0] = new FirstClass();
c[0].notice();
Khyaati Sharma / 02704092021 25
break;
case 2:
c[1] = new Ladies();
c[1].notice();
break;
case 3:
c[2] = new General();
c[2].notice();
break;
case 4:
c[3] = new Luggage();
c[3].notice();
break;
default:
[Link]("Invalid Choice");
} } }
Output:
Khyaati Sharma / 02704092021 26
Q16. Implement Thread and Runnable.
Code :
import [Link].*;
class Main implements Runnable {
public static void main(String args[])
{
// create an object of Runnable target
Main m = new Main();
// pass the runnable reference to Thread
Thread t = new Thread(m, "thread1");
// start the thread
[Link]();
// get the name of the thread
[Link]([Link]());
}
@Override public void run() {
[Link]("thread is running.. //(run method)");
}
}
Output:
Khyaati Sharma / 02704092021 27
Q17. Change Name and priority of child thread.
Code :
import [Link].*;
class ThreadNaming extends Thread {
@Override public void run() {
[Link]("Thread is running....."+" Priority of thread
after changing is : "+[Link]().getPriority());
} }
class Main {
public static void main(String[] args) {
ThreadNaming t1 = new ThreadNaming();
ThreadNaming t2 = new ThreadNaming();
[Link]("Initial thread names and priority : ");
[Link](" ");
[Link]("Thread 1: " + [Link]());
[Link]("Thread 2: " + [Link]());
[Link](" Priority of thread 1 is:
"+[Link]().getPriority());
[Link](" Priority of thread 2 is:
"+[Link]().getPriority());
[Link](" ");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]("Thread names and priority after changing
the thread names : ");
[Link](" ");
[Link]("khy_thread1");
[Link]("khy_thread2");
[Link]();
Khyaati Sharma / 02704092021 28
[Link]();
[Link]("New Thread 1 name: "+ [Link]());
[Link]("New Thread 2 name: "+ [Link]());
}
}
Output:
Khyaati Sharma / 02704092021 29
Q18. Synchronization between Threads. Show the use of isAlive()
and join().
Code :
public class Main extends Thread {
public void run()
{ [Link]("thread is running .."); }
public static void main(String[] args) {
Main c1 = new Main();
Main c2 = new Main();
[Link]();
[Link]("[Link]() : "+ [Link]());
[Link]("making thread to sleep for 300
nano-seconds:-");
try {
[Link]("Current Thread: "+
[Link]().getName());
[Link]();
// making thread to sleep for 300 nano-seconds using sleep()
method
[Link](300); }
// Catch block to handle InterruptedException
catch (InterruptedException ie) {}
[Link]("[Link]() : "+ [Link]());
[Link](" ");
[Link]();
[Link]("khy_thread1");
[Link]("khy_thread2");
[Link]("[Link]() : "+[Link]());
[Link]("making thread to sleep for 300 nano-
seconds:-"); try {
[Link]("Current Thread: "+
[Link]().getName());
[Link]();
Khyaati Sharma / 02704092021 30
// making thread to sleep for 300 nano-seconds using sleep()
method
[Link](300); }
// Catch block to handle InterruptedException
catch (InterruptedException ie) { }
[Link]("[Link]() : "+[Link]());
}
}
Output:
Khyaati Sharma / 02704092021 31
Q19 . Write a java application that will create and start two
threads. One thread will read a number n . The second thread
should calculate factorial of the number read by the first
thread and print the message on the screen as “Factorial of x is y”
,here x is number & y is factorial of the number.
Code :
import [Link].*;
class FactorialThread extends Thread{
private int n;
public FactorialThread(int n){
this.n = n;
}
public void run(){
[Link]().setName("Factorial"); //or
[Link]("") inside main
//we can set or get priority using [Link]() 1 to 10
[Link](" Factorial of "+ n+ " is:" +
factorial(n));
}
int factorial(int n){
if(n<=1){
return n;
}
return n* factorial(n-1);
}
}
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number: ");
int n = [Link]();
Khyaati Sharma / 02704092021 32
FactorialThread factT = new FactorialThread(n);
[Link]();
}
}
Output:
Khyaati Sharma / 02704092021 33
Q20 . Handle user defined exception and any Two checked and
unchecked exceptions.
User defined exception :
Code :
class MyException extends Exception {
public MyException(String s){
super(s); // Call constructor of parent Exception
}
}
public class Main {
public static void main(String args[])
{ try {
throw new MyException(" printing Exception
message"); }
catch (MyException ex) {
[Link]("Caught Exception");
// Print the message from MyException object
[Link]([Link]());
} } }
Output:
Khyaati Sharma / 02704092021 34
Unchecked exceptions :
Khyaati Sharma / 02704092021 35
Checked exceptions :