You are on page 1of 67

Lab Manual PCS 408

“Java Programming”
(B-tech CSE IV Semester)
2021-2022

Submitted in fulfillment of the requirement for the IV semester Bachelor of


Technology(CSE) by:-
Submitted to: Name –Aryan Panwar
Mr. Mahesh Manchanda Roll No. -2018230
Student Id- 200111123
Sec- J(13)

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q1: Write a program to display any message without refer to main method.

public class Main {


static {
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
}
public static void main(String[] args) {

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q2: Write a program to demonstrate static variables, methods, and blocks.

class StaticExamplee
{
static String university;
int Rollno;
static
{
System.out.println("initialising static variable in static block");
university="GEHU";
}
StaticExamplee(int x)
{
Rollno=x;
}
static void StaticDisplay()
{
System.out.println("it will only print static
variable:\nuniversity="+university);
}

void display()
{
System.out.println("Roll no= "+Rollno);

}
}
public class Q2 {

public static void main(String args[])


{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
StaticExamplee ex=new StaticExamplee(13);
StaticExamplee.StaticDisplay();
ex.display();

}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q3: A cloth showroom has announced the following seasonal discounts on purchase of items:

import java.util.*;

public class Q3 {
public static void main(String args[])
{
int PurchaseAmount;
int choice;
float DiscountMill=0;
float DiscountHandl=0;
float totalHandl=0;
float totalMill = 0;
Scanner input= new Scanner(System.in);
float finalAmount;
float totalDiscount;

do
{
System.out.println("enter yout choice 1. to purchase mill cloth 2. to
purchase handloom items 3. to calculate bill");
choice= input.nextInt();
switch(choice)
{
case 1:
System.out.println(" enter purchase amount:");
PurchaseAmount=input.nextInt();
if(PurchaseAmount<=100)
{
DiscountMill=0;
totalMill=PurchaseAmount-DiscountMill;
}
else if(PurchaseAmount<=200)
{
DiscountMill=(PurchaseAmount)*0.05f;
totalMill=PurchaseAmount-DiscountMill;
}
else if(PurchaseAmount<=300)
{
DiscountMill=(PurchaseAmount)*0.075f;
totalMill=PurchaseAmount-DiscountMill;

}
else
{
DiscountMill=(PurchaseAmount)*0.1f;
totalMill=PurchaseAmount-DiscountMill;

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
break;
case 2:
System.out.println(" enter purchase amount:");
PurchaseAmount=input.nextInt();
if(PurchaseAmount<=100)
{
DiscountHandl=(PurchaseAmount)*0.05f;
totalHandl=PurchaseAmount-DiscountHandl;
}
else if(PurchaseAmount<=200)
{

DiscountHandl=(PurchaseAmount)*0.075f;
totalHandl=PurchaseAmount-DiscountHandl;
}
else if(PurchaseAmount<=300)
{
DiscountHandl=(PurchaseAmount)*0.1f;
totalHandl=PurchaseAmount-DiscountHandl;
}
else
{
DiscountHandl=(PurchaseAmount)*0.15f;
totalHandl=PurchaseAmount-DiscountHandl;
}
break;

}while(choice!=3);
finalAmount= totalHandl+totalMill;
totalDiscount=DiscountHandl+DiscountMill;
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
System.out.println("finalamount="+finalAmount);
System.out.println("totalDiscount="+(float)totalDiscount);

input.close();

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q4: Write a program using switch and if statements to compute the net amount to be paid by a customer.

import java.util.*;

public class Q4 {
public static void main(String args[]){
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner in = new Scanner(System.in);
String str;
String strcount;
System.out.println("enter string:");
str=in.nextLine();
System.out.println("enter substring:");
strcount=in.nextLine();
int count = ( str.split(strcount).length );
System.out.println("Total occurrences: " + count);
in.close();
}
}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q5: Write a Java program to count the occurrences of a given string in another given string.

public class Q5 {
public static void main(String[] args) {
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
String str1 = "Graphic Era";
System.out.println("The given string is: " + str1);
System.out.println("After removing duplicates characters the new
string is: " + removeDuplicateChars(str1));
}
private static String removeDuplicateChars(String sourceStr) {
char[] arr1 = sourceStr.toCharArray();
String targetStr = "";
for (char value: arr1) {
if (targetStr.indexOf(value) == -1) {
targetStr += value;
}
}
return targetStr;
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q6: Write a java program to find the duplicate characters in the given paragraph using either String or
StringBuffer class methods.

import java.util.*;

public class Q6 {
public static void main(String[] args) {
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
String str1 = "Graphic Era";
System.out.println("The given string is: " + str1);
System.out.println("After removing duplicates characters the new
string is: " + removeDuplicateChars(str1));
}
private static String removeDuplicateChars(String sourceStr) {
char[] arr1 = sourceStr.toCharArray();
String targetStr = "";
for (char value: arr1) {
if (targetStr.indexOf(value) == -1) {
targetStr += value;
}
}
return targetStr;
}
}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q7: Create a Java program to perform survey on four different model of Maruti (Maruti -K10, Zen-Astelo,
Wagnor, Maruti- SX4) owned by person living in four metro cities(Delhi, Mumbai, Chennai & Kolkatta).
Display tabulated report like format given below:

import java.util.*;

public class Q7 {

public static void main(String Args[])


{
int [][]arr=new int [4][4];
String[]city= {"Delhi ","Mumbai ","Chennai","Kolkata"};
int citychoice;
int carchoice;
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner input=new Scanner(System.in);

do
{
System.out.println("enter your
choice:\n1.Delhi\n2.Mumbai\n3.Chennai\n4.Kolkata\n5.to exit");
citychoice=input.nextInt();
switch (citychoice)
{
case 1:
do
{
System.out.println("enter your
choice:\n1.Maruti-k10\n2.Zen-Astelo\n3.WagonR\n4.Maruti-SX4\n5.reset\n");
carchoice=input.nextInt();
switch (carchoice)
{
case 1:
arr[citychoice-1][carchoice-1]++;
break;
case 2:
arr[citychoice-1][carchoice-1]++;
break;
case 3:
arr[citychoice-1][carchoice-1]++;
break;
case 4:
arr[citychoice-1][carchoice-1]++;
break;
default:

Prepared by – Aryan Panwar Roll no.-13 Sec-J


break;

}
}while(carchoice==5);
break;
case 2:
do
{
System.out.println("enter your
choice:\n1.Maruti-k10\n2.Zen-Astelo\n3.WagonR\n4.Maruti-SX4\n5.reset city\n");
carchoice=input.nextInt();
switch (carchoice)
{
case 1:
arr[citychoice-1][carchoice-1]++;
break;
case 2:
arr[citychoice-1][carchoice-1]++;
break;
case 3:
arr[citychoice-1][carchoice-1]++;
break;
case 4:
arr[citychoice-1][carchoice-1]++;
break;
default:
break;

}
}while(carchoice==5);
break;
case 3:
do
{
System.out.println("enter your choice:\n1.Maruti-k10\n2.Zen-
Astelo\n3.WagonR\n4.Maruti-SX4\n5.exit\n");
carchoice=input.nextInt();
switch (carchoice)
{
case 1:
arr[citychoice-1][carchoice-1]++;
break;
case 2:
arr[citychoice-1][carchoice-1]++;
break;
case 3:
arr[citychoice-1][carchoice-1]++;
break;
case 4:
arr[citychoice-1][carchoice-1]++;
Prepared by – Aryan Panwar Roll no.-13 Sec-J
break;
default:
break;
}
}while(carchoice==5);
break;
case 4:
do
{
System.out.println("enter your choice:\n1.Maruti-k10\n2.Zen-
Astelo\n3.WagonR\n4.Maruti-SX4\n5.exit\n");
carchoice=input.nextInt();
switch (carchoice)
{
case 1:
arr[citychoice-1][carchoice-1]++;
break;
case 2:
arr[citychoice-1][carchoice-1]++;
break;
case 3:
arr[citychoice-1][carchoice-1]++;
break;
case 4:
arr[citychoice-1][carchoice-1]++;
break;
default:
break;

}
}while(carchoice==5);
break;
default:
break;
}

}while(citychoice!=5);

System.out.println(" Maruti-k10 Zen-Astelo WagonR Maruti-


SX4");
for(

int i = 0;i<arr.length;i++)
{
System.out.println("--------------------------------------------------
---------------");
System.out.print(city[i] + " ");
for (int j = 0; j < arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
Prepared by – Aryan Panwar Roll no.-13 Sec-J
}
System.out.println();

} System.out.println("-----------------------------------------------
------------------");
input.close();

}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q8: The annual examination result of 100 students are tabulated as follows:
Write a program to read the data and determine the following:
i) Total marks obtained by each students.
ii) The highest marks in each subject and the rollno. Of that student who
secured it
iii) The student who obtained the highest total marks

import java.util.*;

public class Q8 {
public static void main(String Args[]) {
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
int[][] arr = new int[12][12];

int[] total = new int[10];

Scanner input = new Scanner(System.in);

for (int i = 0; i < arr.length - 2; i++) {


System.out.println("enter for rollno " + (i + 1));
for (int j = 0; j < arr[i].length - 9; j++) {
arr[i][j] = input.nextInt();
}

}
int i = 0, j = 0;

for (i = 0; i < arr.length - 2; i++)


{
total[i] = 0;
for (j = 0; j < arr[i].length - 9; j++)
{
total[i] = total[i] + arr[i][j];
arr[i][3] = total[i];

}
}

for (i = 0; i < arr.length - 2; i++) {


int subjectheighest = arr[0][i];

for (j = 0; j < arr[i].length -2; j++) {


if (arr[j][i] >= subjectheighest) {
subjectheighest = arr[j][i];
arr[10][i] = subjectheighest;
arr[11][i] = j+1;

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
}
}

System.out.println("Roll no sub1 sub2 sub3 total");


for (i = 0; i < arr.length-2; i++) {
System.out.println("-------------------------------------------------
----------------");
System.out.print(" " + (i + 1) + " ");
for (j = 0; j < arr[i].length - 8; j++) {
System.out.print(arr[i][j] + " ");

}
System.out.println();

}
System.out.println("-----------------------------------------------------
------------");

System.out.println("------------highest marks in each subject and roll no--------


----");

System.out.println(" sub1 sub2 sub3");


for(i=10;i<arr.length;i++)
{System.out.println("------------------------------------------------------------
---------------");

if(i==10)
{
System.out.print("marks ");
}
if(i==11)
{

System.out.print("roll no ");
}

for(j=0;j<arr[i].length-9;j++)
{
System.out.print(arr[i][j]+" ");

}
System.out.println();

}
Prepared by – Aryan Panwar Roll no.-13 Sec-J
System.out.print("student who obtained heighest total marks:"+arr[11][3]);
input.close();

}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q9: The daily maximum temperatures recorded in 5 cities during the month of January (for all 31days) have
been tabulated as follows:
Write a program to read the table elements into a two-dimensional array temperature, and to find the city and
day corresponding to (a) the highest temperature and (b) the lowest temperature.

import java.util.*;

public class Q9 {
public static void main(String[] args)
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
int[][] city = new int[10][5];
String[] name = { "delhi", "mumbai", "chennai", "kolkata",
"dehradun"};
String cityname;
Scanner input = new Scanner(System.in);
System.out.println("enetr day-wise temp of all cities");
for (int i = 0; i < city.length; i++)
{
System.out.println(" day"+(i+1));

for (int j = 0; j < city[i].length; j++)


{
city[i][j] = input.nextInt();
}

System.out.println("enter the city name:");


cityname = "chennai";
int min=0, max=0, minday=0, maxday=0;
int column=0;

for (int i = 0; i < name.length; i++)


{
if (name[i] == cityname)
{
System.out.println(name[i]+i);
column = i;
min = city[0][i];
max = city[0][i];

Prepared by – Aryan Panwar Roll no.-13 Sec-J


for (int i =0; i < city.length; i++)
{
if (city[i][column]<=min)
{
min = city[i][column];
minday=i+1;

}
if(city[i][column]>=max)
{
max = city[i][column];
maxday=i+1;
}

System.out.println("min temp : " + min+ "day:"+minday);


System.out.println("max temp : " + max+ "day:"+maxday);

System.out.println("Day Delhi Mumbai Chennai kolkata


Dehradun");
for (int i = 0; i < city.length; i++) {
System.out.println("--------------------------------------------
---------------------");
if(i>=9)
{
System.out.print((i + 1) + " ");
}
else
{
System.out.print((i+ 1) + " ");
}
for (int j = 0; j < city[i].length; j++)
{if(city[i][j]<10)
{

System.out.print(city[i][j] + " ");


}
else
{
System.out.print(city[i][j] +" ");
}

}
System.out.println();
Prepared by – Aryan Panwar Roll no.-13 Sec-J
}
System.out.println("------------------------------------------------
-----------------");
input.close();

}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q10: An election is contested by 5 candidates. The candidates are numbered 1 to 5 and voting is done by
marking the candidate number on the ballot paper. Write a program to read the ballots and count the votes cast
for candidate using an array variable count. In case a number read is outside the range 1 to 5, the ballot should
be considered as ‘NOTA’ and the program should also count the number of NOTA ballots.

import java.util.*;

public class Q10 {


public static void main(String[] args)
{
int choice;
int []arr=new int[6];
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner input = new Scanner(System.in);
for(int i=0; i<arr.length; i++)
{
arr[i]=0;
}

do
{
System.out.println("enter choice\n1.to vote candidate1\n2.to
candidate2\n3.to vote candidate3\n4.to vote candidate4\n5.to vote
candidate5\nelse NOTA");
choice=input.nextInt();
switch(choice)
{
case 1:
arr[0]++;
break;
case 2:
arr[1]++;
break;
case 3:
arr[2]++;
break;
case 4:
arr[3]++;
break;
case 5:
arr[4]++;
break;
default:
arr[5]++;
break;

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
}while(choice!=0);
System.out.println("candidat1 candidate2 candidate3 candidate4
candidate5 NOTA");
for(int i=0; i<arr.length; i++)
{
System.out.print(" "+arr[i]+" ");
}
input.close();

}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q11: Write the static Java int method, longestRun(), which takes an array of numbers and returns the length of
the longest run in the array. A run is a sequence of one or more occurrences of the same value all next to each
other. An array with no elements has a longest run of 0.

import java.util.*;

public class Q11 {


public static void main(String[] args)
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner input = new Scanner(System.in);
int size;
System.out.println("enter the size of array:");
size=input.nextInt();
int arr[]=new int[size];
int Arrcount[]=new int[size];
if(size==0)
{
System.out.println("longest run is: 0");

}
else{

System.out.println("Enter the array elements:");


for(int i=0; i<arr.length; i++)
{
arr[i]=input.nextInt();
Arrcount[i]=1;

}
int j=1;
for(int i=1; i<arr.length; i++)
{
if(arr[i-1]==arr[i])
{
Arrcount[j]++;
}
else
j++;

int max=Arrcount[0];
for(int i=1; i<Arrcount.length; i++)
{
if(Arrcount[i]>max)

Prepared by – Aryan Panwar Roll no.-13 Sec-J


{
max=Arrcount[i];
}
}
System.out.println("longest run in array: " +max);
input.close();

}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q12: A class Telcall calculates the monthly phone bill of a consumer. Some of the members of the class are
given below:
Class name:
Data members/instance variable : phno(phone Number), sname(subscriber Name ) n(number of calls made) and
amt (bill amount).

import java.util.*;

class Telcall{
long phno;
String sname;
int n;
float amt;
void compute()
{
if(n<100)
{
amt=500;
}
else if(n<200){
amt=500+1*(n-100);
}
else if(n<300)
{
amt=600+1.20f*(n-200);
}
else
{
amt=720+1.50f*(n-300);
}
System.out.println("amount:"+amt);
}
Telcall(String cust_name,long contact,int nocall)
{
phno =contact;
sname=cust_name;
n=nocall;
}
}
public class Q12 {
public static void main(String[] args)
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner input = new Scanner(System.in);
String cust_name;
long contact;

Prepared by – Aryan Panwar Roll no.-13 Sec-J


int nocall;
System.out.println("customer name:");
cust_name=input.nextLine();
System.out.println("contact:");
contact=input.nextLong();
System.out.println(" no of calls:");
nocall=input.nextInt();
Telcall T1=new Telcall(cust_name,contact,nocall);
T1.compute();
input.close();

}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q13: Write a Java Program to implement array of object.

import java.util.*;
class ObjArray
{
String name;
int RollNo;
ObjArray(String S, int R)
{
name = S;
RollNo = R;
}
void show()
{

System.out.println( name +" "+RollNo);

}
}
public class Q13 {
public static void main(String[] args)
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Scanner input = new Scanner(System.in);
ObjArray []arr=new ObjArray[5];
int RollNo;
String name;
for(int i=0;i<arr.length;i++)
{
RollNo=input.nextInt();
name=input.nextLine();
arr[i]=new ObjArray(name, RollNo);

}
System.out.println(" name " + " Rollno");
for(int i=0;i<arr.length;i++)
{System.out.println("---------------");
arr[i].show();

}
System.out.println("---------------");
input.close();
}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q14: Package act as a container for classes & other subordinate packages. Because of the interplay between
packages & classes, JAVA addresses four categories of visibility for class members given below. What are
these categories. Also demonstrate each category with example.

class A
{
public void show()
{
System.out.println(" hi i am public method");
}
protected void print()
{
System.out.println(" hi i am protected method");
}

private void display()


{
System.out.println(" hi i am protected method i can only be accessed only
with in class");
}
void test()
{
System.out.println(" hi i am defualt method");
}
void privateprint()
{
A a=new A();
a.display();
}
}
public class Q14 {
public static void main(String[] args)
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
A obj=new A();
obj.show();
obj.print();
obj.privateprint();// since private can not be accessed outside
class so it has been accessed indirectly//
obj.test();
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q15: Demonstrate the use of this & super keyword in a single program.

class parent
{

String name;
int age;

parent(String s, int n)
{
name = s;
age = n;
}
}

class child extends parent


{
String name;
int age;

child(String s, int n, String name,int age)


{
super(s, n);
this.name=name;
this.age=age;
}

void display()
{
System.out.println("parent info");
System.out.println("age=" + super.age);
System.out.println("name=" + super.name);
System.out.println("child info");
System.out.println("age=" + age);
System.out.println("name=" + name);

}
public class Q15 {
public static void main(String args[])
{
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
child ch1=new child("mohan",65,"rohan",34);
ch1.display();
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q16: Write a program in java to demonstrate multiple inheritance using interface.

interface Speedclass{
int speed=90;
public void distance();
}

interface Distanceclass{
int distance=100;
}

class Vehicle implements Speedclass, Distanceclass{

public void distance(){


int distance=speed*100;
System.out.println("distance travelled is "+distance);
}
}
public class Q16 {
public static void main(String args[]){
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
Vehicle obj = new Vehicle();
obj.distance();
}
}
Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q17: Solve the following problem by using runtime polymorphism:
Following tables outlines the major credit cards you might want to validate, along with their allowed prefixes
and lengths. Major Credit Cards, Their Prefixes, and Lengths

abstract class CreditCard {


abstract void CheckCard();
}
class MasterCard extends CreditCard
{
String CardNumber;

MasterCard(String S) {
CardNumber = S;
}

void CheckCard()
{

if (CardNumber.length() == 16 && CardNumber.charAt(0)== 5 &&


CardNumber.charAt(1)<=53||CardNumber.charAt(1)>=49)
{
System.out.println("valid ");

}
else
System.out.println("invalid");

}
}
class Visa extends CreditCard
{

String CardNumber;

Visa(String S) {
CardNumber = S;
}

void CheckCard()
{
if ((CardNumber.length() == 16||CardNumber.length() ==
13)&&CardNumber.charAt(0)==52)
{
System.out.println("valid ");

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
else
{
System.out.println("invalid");
}
}
}
class AmericanExpress extends CreditCard
{

String CardNumber;

AmericanExpress(String S) {
CardNumber = S;
}

void CheckCard()
{

if (CardNumber.length() == 15 && CardNumber.charAt(0)== 3&&


CardNumber.charAt(1)==54||CardNumber.charAt(1)==52)

{
System.out.println("valid ");

}
else
System.out.println(" invaild");
}
}

public class Q17 {


public static void main(String[] args) {
System.out.println("************************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("*************************************");
CreditCard c1=new MasterCard("5123677834896789");
CreditCard c2= new Visa("4111111111111111");
CreditCard c3= new AmericanExpress("320000000000000");
c1.CheckCard();
c2.CheckCard();
c3.CheckCard();
}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


SOURCE CODE
Q18. Define an exception called “MyNation” that is thrown when a string is not
equal to “jai hind” or “JAI HIND”. Write a program that implements this
exception.
import java.util.*;
public class Q18 {
public static void main(String[] args) {
System.out.println("topic :exceptional handeling ");
String salute;
Scanner input = new Scanner(System.in);
try {
System.out.println("say jai hind :");
salute = input.nextLine();
if (!salute.equalsIgnoreCase("jai hind"))
{
India I = new India(salute);
throw I;
}
else
{
System.out.println("output:jai hind");
}
} catch (India e)
{
System.out.println(e);
}
finally {
input.close();
}
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
Prepared by – Aryan Panwar Roll no.-13 Sec-J
System.out.println("****************");
}
}
class India extends Exception {
String Greeting;
India(String Greeting) {
this.Greeting = Greeting;
}
public String toString()
{
return "MyNation";
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q19. Demonstrate Checked & Unchecked Exception Propagation .
import java.io.*;
public class Q19 {
void a() {
int x = 50 / 0;
}
void b() {
a();
}
void c() {
try {
b();
} catch (Exception e) {
System.out.println(e + " unchecked exception");
}
}
void m() throws IOException {
throw new java.io.IOException("device error");
}
void n() throws IOException {
m();
}
void p() {
try {
n();
} catch (Exception e) {
System.out.println(e + " checked exception");
}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


public static void main(String args[]) {
System.out.println("topic: exeception propogation");
Q19 obj = new Q19();
obj.p();
obj.c();
System.out.println("normal flow");
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
System.out.println("****************");
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q20. Write a program to calculate the sum of command line argument and also find the invalid integers
entered.
public class Q20
{

public static void main(String[] args) {


System.out.println("topic: command line arguments");
int sum = 0;
System.out.println("Calculates Sum for below Integers");
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
sum = sum + Integer.parseInt(args[i]);
}
System.out.println("Sum :" + sum);
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
System.out.println("****************");
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q21. Create a program to generate two threads, one thread will print odd numbers and second thread will
print even numbers between 1 to 20 numbers.
public class Q21 {
public static void main(String[] args)
{
System.out.println("topic: Multithreading ");
PrintOddEven num1=new PrintOddEven("even");
PrintOddEven num2=new PrintOddEven("odd");
num1.start();
num2.start();
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
System.out.println("****************");
}

}
class PrintOddEven extends Thread {
String num;
PrintOddEven(String num)
{
this.num = num;
}
public void run(){
if(num.equalsIgnoreCase("even"))
{

for(int i =0;i<=500;i=i+2)
{
System.out.println("even"+i);

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
}
if(num.equalsIgnoreCase("odd"))
{
for(int i =1;i<=5000;i=i+2)
{
System.out.println("odd:"+i);
}
}
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q22.Write a program to find the solution (in context of multithreading) of a problem when two customers
(having joint account) accessing the same account and try to withdraw Rs.500 and Rs.1000 at same time from
different ATM, but the balance in the account is only Rs.1200 .
import java.util.*;
class Account
{
int balance;
public Account() {
balance = 1200;
}
public synchronized void withdraw(int bal) {
if(bal<=balance)
{
try {

balance = balance - bal;


System.out.println("wait request is processing...");
System.out.println("amount withdrawn:"+bal);
System.out.println("Balance remaining:::" + balance);
Thread.sleep(4000);

} catch (Exception ex) {


System.out.println("EXCEPTION OCCURED.." + ex);
}
}
else
System.out.println(" not enough balance");
}
}
class Amtthread1 implements Runnable {
Prepared by – Aryan Panwar Roll no.-13 Sec-J
Scanner input = new Scanner(System.in);
Account obj;
public Amtthread1(Account a)
{
obj = a;
}
public void run()
{
int i;
System.out.println("enter the amount to withdraw:");
i=input.nextInt();
obj.withdraw(i);

}
public class Q22 {
public static void main(String args[]) {
System.out.println("topic: Synchronisation ");

Account a1 = new Account();


Amtthread1 c1 = new Amtthread1(a1);
Amtthread1 c2 = new Amtthread1(a1);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c2);
t1.start();
t2.start();
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
System.out.println("****************");

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q23. Suppose there is only one berth available in a train and two passengers (threads) are asking for that
berth in two different counters. The clerks at different counters sent a request to the server to allot that berth
to their passengers. Now write a java code to see to whom that berth is allotted (Using thread
synochronization).
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve(int i)
{
wanted = i;
}
public synchronized void run()
{
System.out.println ("Number of berths available: " +
available);
if ( available >= wanted)
{
String name = Thread.currentThread ().getName ();
System.out.println (wanted + " berths alloted to: " +
name);
try
{
System.out.println("wait requesting progress");
Thread.sleep (2000);
available = available - wanted;
} catch (InterruptedException ie){ }
}
else
{ System.out.println ("Sorry, no berths available");

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
}
}
public class Q23
{
public static void main(String args[])
{
System.out.println("topic: Synchronisation ");
Reserve obj = new Reserve (1);
Thread t1 = new Thread (obj);
Thread t2 = new Thread (obj);
t1.setName ("First Person");
t2.setName ("Second Person");
t1.start ();
t2.start ();
System.out.println("****************");
System.out.println("Written By:Aryan Panwar 13 CSE(4)J");
System.out.println("****************");
}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source code
Q24. Demonstrate the Producer-Consumer problem using the concept of inter thread communication (i.e.
multi-threading).
class Buffer{
int a;
boolean produced = false;
public synchronized void produce(int x){
if(produced){
System.out.println("Producer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
a=x;
System.out.println("Product" + a + " is produced.");
produced = true;
notify();
}
public synchronized void consume(){
if(!produced){
System.out.println("Consumer is waiting...");
try{
wait();
}catch(Exception e){
System.out.println(e);
}
}
System.out.println("Product" + a + " is consumed.");

Prepared by – Aryan Panwar Roll no.-13 Sec-J


produced = false;
notify();
}
}
class Producer extends Thread{
Buffer b;
public Producer(Buffer b){
this.b = b;
}
public void run(){
System.out.println("Producer start producing...");
for(int i = 1; i <= 10; i++){
b.produce(i);
}
}
}
class Consumer extends Thread{
Buffer b;
public Consumer(Buffer b){
this.b = b;
}
public void run(){
System.out.println("Consumer start consuming...");
for(int i = 1; i <= 10; i++){
b.consume();
}
}
}
public class Q24 {
public static void main(String args[]){

Prepared by – Aryan Panwar Roll no.-13 Sec-J


System.out.println("topic: Inter-Thread communication ");
Buffer b = new Buffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.start();
c.start();
System.out.println("****************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J");
System.out.println("****************");
}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source code
Q25. Calculate shipment cost for an order which may either be placed by a wholesaler or a retailer. For a
customer, the cost is calculated as :

import java.awt.*;
import java.awt.event.*;
class Shipment extends Frame implements ActionListener, ItemListener
{
Panel p1,p2,p3,p4;
Label l1,l2,l3;
TextField txt1,txt2;
Button btncal;
Checkbox chkDiscount,chkWholesaler,chkRetailer;
CheckboxGroup cbg;
double cost=0.0;
double temp=0.0;
Shipment()
{
setLayout(new FlowLayout());
setTitle("Company");
setVisible(true);
setSize(500,200);
l1=new Label("Unit Nos");
l2=new Label("Customer Type");
l3=new Label("Cost total", Label.RIGHT);
txt1=new TextField(20);
txt2=new TextField(20);
txt2.setEditable(false);
cbg=new CheckboxGroup();
chkDiscount=new Checkbox("Special Discount");
Prepared by – Aryan Panwar Roll no.-13 Sec-J
chkDiscount.setEnabled(false);
chkWholesaler=new Checkbox("Wholesaler",cbg,true);
chkRetailer=new Checkbox("Retailer",false,cbg);

p1=new Panel(new GridLayout(3,1));


p2=new Panel(new GridLayout(3,1));
p3=new Panel(new GridLayout(1,3));
btncal=new Button("Calculate Cost");
p1.add(l1);
p1.add(txt1);
p1.add(chkDiscount);

p2.add(l2);
p2.add(txt2);
p2.add(chkRetailer);
p2.add(chkWholesaler);

p3.add(btncal);
p3.add(l3);
p3.add(txt2);

add(p1);
add(p2);
add(p3);
btncal.addActionListener(this);
chkDiscount.addItemListener(this);
addWindowListener(new WindowAdapter()
{
@Override
Prepared by – Aryan Panwar Roll no.-13 Sec-J
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);

}
public static void main(String[] args)
{
new Shipment();
}
@Override
public void actionPerformed(ActionEvent arg0)
{
int i=Integer.parseInt(txt1.getText());
chkDiscount.setEnabled(true);
if(i>0&&i<=15)
{
if(chkWholesaler.getState())
cost=50*i;
else
cost=60*i;
}
if(i>15&&i<=20)
{
if(chkWholesaler.getState())
cost=45*i;
else
cost=55*i;
Prepared by – Aryan Panwar Roll no.-13 Sec-J
}
if(i>20&&i<=30)
{
if(chkWholesaler.getState())
cost=40*i;
else
cost=50*i;
}
if(i>50)
{
if(chkWholesaler.getState())
cost=30*i;
else
cost=40*i;
}

txt2.setText(cost+"");
temp=cost;
}
@Override
public void itemStateChanged(ItemEvent e)
{
if(chkDiscount.getState())
{
cost=cost-(cost*0.1);
}
else
cost=temp;

txt2.setText(cost+"");
Prepared by – Aryan Panwar Roll no.-13 Sec-J
}

OUTPUT

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q26. Store some country names and their capitals. Ask the user to select a country and its capital from given
two lists. If the match is correct, display “Correct answer”, otherwise display error message and tell the
correct answer.

import java.awt.*;
import java.awt.event.*;
class Match extends Frame implements ActionListener {
String[] country={"INDIA","CANADA","AFGANISTAN","ALBANIA","ALGERIA"};
String[] capital={"NEW DELHI","OTTAWA","Kabul","Tirane","Algiers"};
Choice co=new Choice();
Choice ca=new Choice();
Button b=new Button("Check");
TextField t1=new TextField();
Match() {
for (String s : country) {
co.add(s);
}
for (String s : capital) {
ca.add(s);
}
co.setBounds(40,80,150,50);
ca.setBounds(300,80,150,50);
b.setBounds(180,150,60,50);
t1.setBounds(50,120,300,20);
add(co);
add(ca);
add(b);
add(t1);

setSize(500,250);
setTitle("This is our basic AWT example");
setLayout(null);
setVisible(true);
b.addActionListener(this);

addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
public void actionPerformed(ActionEvent e) {
if(co.getSelectedIndex()==ca.getSelectedIndex()){
t1.setText("COrrect answer");
}else{
t1.setText("!!!Wrong answer!!!\nCapital of "+country[co.getSelectedIndex()]+" is
"+capital[co.getSelectedIndex()]+".");
}
}

class Q26 {
public static void main(String[] args) {
new Match();
}
}
OUTPUT

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source Code
Q27. Demonstrate the use of all layout managers supported by java in a single program.

import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
System.out.println("*****************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J ");
Prepared by – Aryan Panwar Roll no.-13 Sec-J
System.out.println("*****************************");
new Border();
}
}

OUTPUT

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source code
Q29. Create a Program to demonstrate Object Serialization and Object De-serialization.
import java.io.*;

class Demo implements java.io.Serializable


{
public int a;
public String b;

// Default constructor
public Demo(int a, String b)
{
this.a = a;
this.b = b;
}

class Test
{
public static void main(String[] args)
{
System.out.println("**********************************");
System.out.println("Written By: Aryan Panwar 13 CSE(4)J ");
System.out.println("**********************************");
Demo object = new Demo(1, "javaprogramming");
String filename = "file.ser";

// Serialization
try
{
//Saving of object in a file
FileOutputStream file = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file);

// Method for serialization of object


out.writeObject(object);

out.close();
file.close();

System.out.println("Object has been serialized");

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}

catch(IOException ex)
{
System.out.println("IOException is caught");
}

Demo object1 = null;

// Deserialization
try
{
// Reading the object from a file
FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file);

// Method for deserialization of object


object1 = (Demo)in.readObject();
in.close();
file.close();
System.out.println("Object has been deserialized ");
System.out.println("a = " + object1.a);
System.out.println("b = " + object1.b);
}
catch(IOException ex)
{
System.out.println("IOException is caught");
}

catch(ClassNotFoundException ex)
{
System.out.println("ClassNotFoundException is caught");
}

}
}

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Source code
Q30.Create a program to display the records from employees table who were working in the department
which is entered by the user.

import java.sql.*;
import java.util.*;

public class JDBCDemo


{
Connection con=null;
Statement stmt=null;

JDBCDemo() throws ClassNotFoundException, SQLException


{
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/employeeid","root","");
System.out.println("Enter Department number:");
stmt=con.createStatement();
int vardno = sc.nextInt();
ResultSet rs=stmt.executeQuery("select * from pers where dno =" + vardno);
System.out.println("Below is the list of employee working in Deptt No."+ vardno);
System.out.println("Employee Code\t Employee Name\t Designation \t Department No.");
while(rs.next())
{
System.out.print(rs.getInt("empcode") + " \t");
System.out.print(rs.getString("empname")+ " \t");
System.out.print(rs.getString("designation")+ " \t");
System.out.println(rs.getInt("dno"));

Prepared by – Aryan Panwar Roll no.-13 Sec-J


}
con.close();
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
try{
new JDBCDemo();
}catch(Exception e){ e.printStackTrace();}
}

Output

Prepared by – Aryan Panwar Roll no.-13 Sec-J


Prepared by – Aryan Panwar Roll no.-13 Sec-J

You might also like