0% found this document useful (0 votes)
35 views90 pages

12th STD All Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views90 pages

12th STD All Programs

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

TM

12th STD (Practical Programs)


Hamza Sir: 88663 13412 Tasneem Ma’am: 88497 35772
hrzone_computer_classes  [email protected] /HRZONEComputerClasses

Chapter 7: Java basics

-: Textual Illustrations :-
1. Computer the cost of phone call and update the balance.

Script
public class CallCost
{
public static void main(String[] args)
{
double b;
double r;
double d;
double c;
b = 170;
r = 1.02;
d = 37;
c=d * r;
b= b - c;
System.out.println("duration:"+d+"Seconds");
System.out.println("balance: "+b+"Rupees");
}
}

Output

duration:37.0 Seconds
balance: 132.26 Rupees

HR ZONE Computer Classes TM 1


2. Compute simple interest
Script

public class interest


{
public static void main(String[] args)
{
Double p,r,n,a,i;
p=1000;
r=9.50;
n=3;

i=p*r*n/100;
a=p+i;

System.out.println(“interest=”+i);
System.out.println(“Maturity Amount=”+a);
}
}

Output
Interest=285.0
Maturity Amount=1285.0

HR ZONE Computer Classes TM 2


3. Arithmetic operators
Script

class A
{
public static void main (String[] args)
{
int x=6;
int y=4;
System.out.println("x + y = " + (x + y ));
System.out.println("x - y = " + (x - y ));
System.out.println("x / y = " + (x / y ));
System.out.println("x % y = " + (x % y ));
}
}

Output

x + y = 10
x-y=2
x/y=1
x%y=2

HR ZONE Computer Classes TM 3


4. Nested loops
Script

class Nested
{
public static void main(String[] args)
{
int age = 28;

if (age < 13)


{
System.out.println("child!");
}
else if (age < 19)
{
System.out.println("teenager.");
}
else
{
if (age < 65)
{
System.out.println("adult!");
}
else
{
System.out.println("senior");
}
}
}
}

Output

adult!

HR ZONE Computer Classes TM 4


5. if and else (even number) and (odd number)
Script

class odd_even
{
public static void main(String[] args)
{
int x=12;
if( x % 2 == 0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
}
}

Output

even

HR ZONE Computer Classes TM 5


6. Print 1 to 100 (For loop)
Script

class numbers
{
public static void main(String[] args)
{
for (int i= 1; i<= 100; i++)
{
System.out.println(i);
}
}
}

Output

1 2 3 4 5 6 7 8 9 . . . . . 100

HR ZONE Computer Classes TM 6


-:Laboratory exercise:-

1. During a sale at a store, a 10% discount is applied to purchase over Rs. 5000. Write a
program that assigns any value to variable ‘purchase’ and then calculates the discounted price.
Display purchase amount and discount offered.
Script
class discount
{
public static void main(String args[])
{
int purchase=14000;
int discount;
int amount;

if(purchase>5000) //condition for purhase


{
discount=purchase*10/100;
amount=purchase-discount;
System.out.println("Discount is="+discount);
System.out.println("Amount after applying discount 10%="+amount);
}
else
{
System.out.println("NO Discount applied purchase amount is less than
5000="+purchase+"rs");
}
}
}

Output

Discount is=1400
Amount after applying discount 10%=12600

HR ZONE Computer Classes TM 7


2. Write a program that determines the price of a movie ticket based on customer’s age and
the time of the show (normal of matinee). The normal show and matinee show ticket price for
adult is Rs. 100 and Rs. 60 respectuvely. Adults are those over 13 years. The children’s ticket
price is Rs. 60 and Rs. 40 for normal show and matinee show respectively. Declare variable
of suitable data types for age and show time, assign the values to these varibles and print age,
show time and the ticket price.
Script
class Ticket
{
public static void main(String args[])
{
int age=10;
int ticket=0;
float showtime=7;
if(age>=13)
{
if(showtime>=10)
{
ticket=100;
}
else
{
ticket=50;
}
}
else if(age<13)
{
if(showtime>=10)
{
ticket=60;
}

else
{
ticket=40;

}
}

HR ZONE Computer Classes TM 8


System.out.println("Customer Age:"+ age);
System.out.println("Show Time:" + showtime);
System.out.println("Ticket:"+ ticket);
}
}

Output

Customer Age:10
Show Time:7.0
Ticket:40

HR ZONE Computer Classes TM 9


3. Write a program to display the grade based on percentage of marks using switch statement
Script
public class Grade
{
public static void main(String[] args)
{
int choice=0;
int marks=350;
if(marks > 499)
choice=1;
else if(marks>400)
choice=2;
else if(marks>300)
choice=3;
else if(marks>200)
choice=4;
switch(choice)
{
case 1:
System.out.println("Your Grade is A+");
break;
case 2:
System.out.println("Your Grade is B+");
break;
case 3:
System.out.println("Your Grade is C+");
break;
case 4:
System.out.println("Your Grade is C");
break;
default
System.out.println("Your Grade is D");
}
}
}

Output

Your Grade is C+

HR ZONE Computer Classes TM 10


4. A bank gives loan to customers at a simple interest of 12% per annum.Interest for the whole
term is charged at the beginning.Compute the monthly installments considering the terms of
36 months for loan amount of Rs.10000,20000,30000,40000,50000,60000,70000,80000,
90000,100000.
Script
class interest
{
public static void main(String args[])
{
double p,q,r;
for(int i=10000;i<=100000;i=i+10000)
{
p=i*36*12/1200;
q=p+i; r=q/36;
System.out.println("loan amount="+i+"per month installment="+r);
}
}
}

Output

loan amount=10000per month


installment=377.77777777777777
loan amount=20000per month installment=755.5555555555555
loan amount=30000per month
installment=1133.3333333333333
loan amount=40000per month installment=1511.111111111111
loan amount=50000per month installment=1888.888888888889
loan amount=60000per month
installment=2266.6666666666665
loan amount=70000per month
installment=2644.4444444444443
loan amount=80000per month installment=3022.222222222222
loan amount=90000per month installment=3400.0
loan amount=100000per month
installment=3777.777777777778

HR ZONE Computer Classes TM 11


5. Write a program that prints square root of interger numbers starting form 5 till the square
root is at 50 or less.
Script

public class SquareRoot


{
public static void main(String[] args)
{
int j=6;
for(int i=5; i< j; i++)
{
if(Math.sqrt(i) <=50)
{
System.out.println("SquareRoot of" + i + "is :" + Math.sqrt(i));
}
else
{
break;
}
j++;
}
}
}

Output

SquareRoot of5is :2.23606797749979


SquareRoot of6is :2.449489742783178



SquareRoot of2498is :49.9799959983992
SquareRoot of2499is :49.98999899979995
SquareRoot of2500is :50.0

HR ZONE Computer Classes TM 12


Chapter 8: Classes and Objects in Java

-: Textual Illustrations :-
1. Write a Program in Java to create a class named “Room” with attributes length, width, height
and three methods. The first method will assign values to attributes, second one will calculate
area, and third will assign values to attributes.

Script

class room //method class


{
float length,width,height; //local
void set(float l,float w,float h)
{
length=l;
width=w;
height=h;
}
double area()
{
return(length*width);
}
void display()
{
System.out.println("length="+length);
System.out.println("width="+width);
System.out.println("height="+height);
}
}
class roomdemo
{
public static void main(String args[])
HR ZONE Computer Classes TM 13
{
room r1;
r1=new room();
room r2=new room();
r1.display();
r2.display();
r1.set(10,20,30);
r2.set(11,24,23);
r1.display();
r2.display();
System.out.println("area of room="+r1.area());
}
}
Output

length=0.0

width=0.0

height=0.0

length=0.0

width=0.0

height=0.0

length=10.0

width=20.0

height=30.0

length=11.0

width=24.0

height=23.0

area of room=200.0

HR ZONE Computer Classes TM 14


2. Write a Java Program to Use class variable totWindows.

Script

class Room
{
float length, width, height;
byte nWindows;
static int totwindows; //class variable

void setAttr(float l, float w,float h,byte n)


{
length = l; width = w; height = h;
setWindows(n);
}

void setWindows(byte n)
{
totwindows = totwindows - nWindows + n;
nWindows = n;
}

double area()
{
return (length*width);
}

void display()
{
System.out.println("\nLength:" + length+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}

class RoomDemoStatic
{
public static void main(String args[])
{
Room r1= new Room(); Room r2= new Room();

HR ZONE Computer Classes TM 15


r1.setAttr(18, 12.5f, 10,(byte)2);
r1.display();
r1.setAttr(18, 12.5f, 10,(byte)2);
r2.display();

System.out.println("\n Room2 Number of windows modified from 1 to 2");


r2.setWindows((byte)2);
System.out.println("\n Total number windows:" + Room.totwindows);
}
}

Output

Length:18.0

width:12.5

Height:10.0

Numbers of windows:2

Length:0.0

width0.0

Height:0.0

Numbers of windows:0

Room2 Number of windows modified from 1 to 2

Total number windows:4

HR ZONE Computer Classes TM 16


3. Write a Program in Java to use Polymorphism to print a line as per specified Parameters
(Method Overloading)

Script

class PrintLine
{
static void printline()
{
for (int i=0; i<40;i++)
System.out.print("=");
System.out.println();
}

static void printline(int n)


{
for(int i=0;i<n;i++)
System.out.print("#");
System.out.println();
}

static void printline(char ch, int n)


{
for(int i=0;i<n;i++)
System.out.print(ch);
System.out.println();
}
}

public class polyDemo


{
public static void main(String[] s)
{
PrintLine.printline();
PrintLine.printline(30);
PrintLine.printline('+',20);
}
}

HR ZONE Computer Classes TM 17


Output

========================================
##############################
++++++++++++++++++++

HR ZONE Computer Classes TM 18


4. Write a Java Program to show the use of constructors.
Script

class Room
{
float lenght, width, height;
byte nWindows;
static int totwindows;

Room (float l, float w,float h,byte n)


{
lenght = l; width = w; height = h;
nWindows = n; totwindows+=n;
}

Room (float l, float w)


{
lenght = l; width = w; height = 10;
nWindows=1; totwindows++;
}

double area()
{
return (lenght*width);
}

void display()
{
System.out.println("\nLength:" + lenght+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}

class RoomConstractorDemoA
{
public static void main(String args[])
{
Room r1= new Room(16,12.5f);
Room r2= new Room(20,14,12,(byte)2);
r1.display();
HR ZONE Computer Classes TM 19
System.out.println("\n Total number windows:" + Room.totwindows);
}
}

Output

Length:16.0
width12.5
Height:10.0
Numbers of windows:1
Total number windows:3

HR ZONE Computer Classes TM 20


5. Write a Java Program to show the Use of User-defined No-Argument Constructors.
Script

class Room
{
float lenght, width, height;
byte nWindows;
static int totwindows;

Room(){}
Room (float l, float w,float h,byte n)
{
lenght = l; width = w; height = h;
nWindows = n; totwindows+=n;
}

Room (float l, float w)


{
lenght = l; width = w; height = 10;
nWindows=1; totwindows++;
}

double area()
{
return (lenght*width);
}

void display()
{
System.out.println("\nLength:" + lenght+ "\nwidth" +width);
System.out.println("Height:" + height);
System.out.println("Numbers of windows:" + nWindows);
}
}

class RoomConstractorDemoB
{
public static void main(String args[])
{
Room r1= new Room();
HR ZONE Computer Classes TM 21
Room r2= new Room(20,14,12,(byte)2);
r1.display(); r2.display();
System.out.println("\n Total number windows:" + Room.totwindows);
}
}

Output

Length:0.0
width0.0
Height:0.0
Numbers of windows:0
Length:20.0
width14.0
Height:12.0
Numbers of windows:2
Total number windows:2

HR ZONE Computer Classes TM 22


6. Write a Java Program to show the use of Default visibility modifier, available everywhere
in a package.
Script

class Rectangle
{
double length, width;

void setAttributes(double x, double y)


{
length = x; width = y;
}

double area()
{
return length*width;
}

void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle();

rect1.setAttributes(10.5,20);
rect1.display();
System.out.println("Area of rectangle is: " + rect1.area());
rect2.setAttributes(10,15);
System.out.println("Area of rectangle with length: " + rect2.length+ ",
width="+ rect2.width+"is"+rect2.area());
}
}

HR ZONE Computer Classes TM 23


Output

Rectangle with length= 10.5width= 20.0


Area of rectangle is: 210.0
Area of rectangle with length: 10.0, width=15.0is150.0

HR ZONE Computer Classes TM 24


7. Write a Java Program to show the Error whole Accessing private instance variable from
another class.
Script

class Rectangle
{
private double length, width;

Rectangle(double x, double y)
{
length = x; width = y;
}

Rectangle(){};

double area()
{
return length*width;
}

void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
}

class visibilityPrivateB
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle(10,15);

rect1.display(); rect2.display();
System.out.println("Area of rectangle with length: " + rect2.length+ ",
width="+ rect2.width+"is"+rect2.area());
}
}
HR ZONE Computer Classes TM 25
Output

Error

visibilityPrivateB.java:36: error: length has private access in Rectangle

System.out.println("Area of rectangle with length: " + rect2.length+


", width="+ rect2.width+"is"+rect2.area());

visibilityPrivateB.java:36: error: width has private access in Rectangle

System.out.println("Area of rectangle with length: " + rect2.length+


", width="+ rect2.width+"is"+rect2.area());

2 errors

HR ZONE Computer Classes TM 26


8. Write a Java Program to Access private variables through public or package methods.
Script

class Rectangle
{
private double length, width;

Rectangle(double x, double y)
{
length = x; width = y;
}

Rectangle(){};

double area()
{
return length*width;
}

void display()
{
System.out.println("Rectangle with length= " + length + "width= " +
width);
}
double getLength(){return length;}
double getWidth(){return width;}
}
class visibilityPrivateB
{
public static void main(String args[])
{
Rectangle rect1;
rect1= new Rectangle();
Rectangle rect2=new Rectangle(10,15);

rect1.display(); rect2.display();
System.out.println("Area of rectangle with length: " + rect2.getLength()+
", width="+ rect2.getWidth()+"is"+rect2.area());
}
}
HR ZONE Computer Classes TM 27
Output

Rectangle with length= 0.0width= 0.0


Rectangle with length= 10.0width= 15.0
Area of rectangle with length: 10.0, width=15.0is150.0

HR ZONE Computer Classes TM 28


9.write a Java Program to Pass an object as a parameter.
Script

class Rectangle
{
private double length, width;

Rectangle(double x, double y)
{
length = x; width = y;
}
Rectangle(){};

double area(){return length*width;}


void display()
{
System.out.println("Rectangle with length= " + length +"Width= " +
width);
}
double getLength(){return length;}
double getwidth(){return width;}
boolean isLarge(Rectangle rect)
{
if (area() >rect.area()) return true;
else return false;
}
}

class ObjectParameter
{
public static void main(String[] s)
{
Rectangle rect1 = new Rectangle(8,20);
Rectangle rect2 = new Rectangle(10,15);

rect1.display();
System.out.println("Area of rectangle 1 is: " + rect1.area()+ "\n");
rect2.display();
System.out.println("Area of rectangle 2 is: " + rect2.area()+ "\n");
if(rect1.isLarge(rect2))

HR ZONE Computer Classes TM 29


System.out.println("Area of rectangle 1 is larger than" + "Area of
rectangle 2");
}
}

Output

Rectangle with length= 8.0Width= 20.0


Area of rectangle 1 is: 160.0

Rectangle with length= 10.0Width= 15.0


Area of rectangle 2 is: 150.0

Area of rectangle 1 is larger thanArea of rectangle 2

HR ZONE Computer Classes TM 30


10. Write a Java Program to show the concept of Inheritance.

Script

class room //parent

float length,width,height; //local variables

room(float l,float w,float h) //constructor

length=l;

width=w;

height=h;

double area()

return(length*width);

void display()

System.out.println("\nlength="+length);

System.out.println("width="+width);

System.out.println("height="+height);

class classroom extends room //child

int benches,seats;

classroom(float l,float w,float h,int b,int s) //constructor

HR ZONE Computer Classes TM 31


{

super(l,w,h);

benches=b;

seats=s;

int getseats()

return(benches*seats);

void show()

super.display();

System.out.println("benches="+benches);

System.out.println("seats="+seats);

void display()

System.out.println("Total seats="+getseats());

class inheritancedemo

public static void main(String args[])

room r1=new room(10,20,30);

classroom c1=new classroom(15,25,35,10,5);

HR ZONE Computer Classes TM 32


r1.display();

c1.show();

c1.display();

System.out.println("area of room="+r1.area());

System.out.println("area of classroom="+c1.area());

Output

length=10.0
width=20.0
height=30.0

length=15.0
width=25.0
height=35.0
benches=10
seats=5
Total seats=50
area of room=200.0
area of classroom=375.0

HR ZONE Computer Classes TM 33


11 Write a Java Program to use the concept of Composition and Aggregation

Script

class room
{
protected float length,width,height; //local
room(float l,float w,float h)
{
length=l;
width=w;
height=h;
}
double area()
{
return(length*width);
}
void display()
{
System.out.println("length="+length);
System.out.println("width="+width);
System.out.println("height="+height);
}
}
class library
{
int books,magazines,newspaper;
room readingroom;
library(int b,int m,int n,room r)
{
books=b;
magazines=m;
newspaper=n;
readingroom=r;
}
void display()
{
System.out.println("books="+books);
System.out.println("magazines="+magazines);
System.out.println("newspaper="+newspaper);
readingroom.display();
HR ZONE Computer Classes TM 34
}
}
class container
{
public static void main(String args[])
{
room r1=new room(10,20,30);
library l1=new library(300,200,100,r1);
r1.display();
l1.display();
}
}

Output

length=10.0
width=20.0
height=30.0
books=300
magazines=200
newspaper=100
length=10.0
width=20.0
height=30.0

HR ZONE Computer Classes TM 35


-:Laboratory exercise:-

1. Create a class named ‘Fixed Deposit’ that contains three attributes (principal amount,annual
interest rate and period(years) of deposit) and a method that returns maturity amount using
compound interest.Create another class named ‘FixedDepositDemo’ with main()
method,create two objects,assign the values to their attributes and display them with maturity
amount.
Script

class FixedDeposit
{
int principle,rate,year;
void setAttr(int p, int r, int n)
{
principle = p;rate = r;year = n;
}

int compint()
{
return (principle*(1+rate/100)^year);
}

void display()
{
System.out.println("\n Principle: " +principle);
System.out.println("\n rate: " +rate);
System.out.println("\n year: " +year);
}
}

class FixedDepositDemo
{
public static void main(String args[])
{
FixedDeposit f1;
f1= new FixedDeposit();

FixedDeposit f2= new FixedDeposit();

f1.setAttr(1500,10,2);
f1.setAttr(1000,9,3);
HR ZONE Computer Classes TM 36
System.out.println("\n Principle Ammount" + f1.principle + "Rate" +
f1.rate + "Year: " + f1.year +"Compound Amount is"+ f1.compint());
System.out.println("\n Principle Ammount" + f2.principle + "Rate" +
f2.rate + "Year: " + f2.year +"Compound Amount is"+ f2.compint());
}
}

Output

Principle Ammount1000Rate9Year: 3Compound Amount is1003

Principle Ammount0Rate0Year: 0Compound Amount is 0

HR ZONE Computer Classes TM 37


2. Fixed deposit B

Script

class FixedDeposit
{
int principle,rate,year;
void setAttr(int p, int r, int n)
{
principle = p;rate = r;year = n;
}

int compint()
{
return (principle*(1+rate/100)^year);
}

void display()
{
System.out.println("\n Principle: " +principle);
System.out.println("\n rate: " +rate);
System.out.println("\n year: " +year);
}
}

class FixedDepositDemo
{
public static void main(String args[])
{
FixedDeposit f1;
f1= new FixedDeposit();

FixedDeposit f2= new FixedDeposit();

f1.setAttr(1500,10,2);
f1.setAttr(1000,9,3);

System.out.println("\n Principle Ammount" + f1.principle + "Rate" +


f1.rate + "Year: " + f1.year +"Compound Amount is"+ f1.compint());
System.out.println("\n Principle Ammount" + f2.principle + "Rate" +
f2.rate + "Year: " + f2.year +"Compound Amount is"+ f2.compint());
HR ZONE Computer Classes TM 38
}
}

Output

Principle Ammount1000Rate9Year: 3Compound Amount is1003

Principle Ammount0Rate0Year: 0Compound Amount is 0

HR ZONE Computer Classes TM 39


3. Modify

Script

import java.io.*;
class FixedDepositPrivate
{
private double princi_amt,intr,dur,comp_intr;
public double calculateCompoundInterest()
{
comp_intr=(princi_amt)*(Math.pow(1+(intr/100),dur));
return(comp_intr);
}
public void get() throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter principle amount");
princi_amt=Double.parseDouble(dis.readLine());
System.out.println("Enter Interest rate");
intr=Double.parseDouble(dis.readLine());
System.out.println("Enter Duration");
dur=Double.parseDouble(dis.readLine());
}
public void display()
{
System.out.println("Principle Amount:" +princi_amt);
System.out.println("Interest rate is:" +intr);
System.out.println("Duration is:" +dur);
System.out.println("Compound interest is:" +comp_intr);
}
}

class FixedDepositC
{
public static void main(String[] args)throws Exception
{
FixedDepositPrivate depo1= new FixedDepositPrivate();
depo1.get();
depo1.calculateCompoundInterest();
depo1.display();
}
}

HR ZONE Computer Classes TM 40


Output

Enter principle amount


5000
Enter Interest rate
2
Enter Duration
2
Principle Amount:5000.0
Interest rate is:2.0
Duration is:2.0
Compound interest is:5202.0

HR ZONE Computer Classes TM 41


4. Add class variable ‘totDeposit’ in a class that contains total amount of deposited principal
amount.Modify the constructors and setter methods so as to get the total deposit amount.Write
a method to display the value of ‘totDeposit’ variable and show its use.

Script

import java.io.*;
class FixedDepositPrivate
{
private double princi_amt,intr,dur,comp_intr,totdeposit;
public double calculateCompoundInterest()
{
comp_intr=(princi_amt)*(Math.pow(1+(intr/100),dur));
return(comp_intr);
}
public void get() throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter principle amount");
princi_amt=Double.parseDouble(dis.readLine());
System.out.println("Enter Interest rate");
intr=Double.parseDouble(dis.readLine());
System.out.println("Enter Duration");
dur=Double.parseDouble(dis.readLine());
}
public void calculateTotalDeposit()
{
totdeposit=princi_amt+comp_intr;
}
public void displayTotalDeposit()
{
System.out.println("Total deposit is:"+ totdeposit);
}
public void display()
{
System.out.println("Principle Amount:" +princi_amt);
System.out.println("Interest rate is:" +intr);
System.out.println("Duration is:" +dur);
System.out.println("Compound interest is:" +comp_intr);
}
}
HR ZONE Computer Classes TM 42
class FixedDepositD
{
public static void main(String[] args)throws Exception
{
FixedDepositPrivate depo1= new FixedDepositPrivate();
depo1.get();
depo1.calculateCompoundInterest();
depo1.display();
}
}

Output

Enter principle amount


10000
Enter Interest rate
20
Enter Duration
3
Principl0Amount:10000.0
Interest rate is:20.0
Duration is:3.0
Compound interest is:17279.999999999996

HR ZONE Computer Classes TM 43


5. Using Rectangle class derive a subclass ‘Box’ having additional attribute ‘height’ and
method ‘volume’. (Volume=height x width x length = height x area)

Script

import java.io.*;
class Rectangle
{
int length,breadth;
}

class Box extends Rectangle


{
int height,vol;

public void getData() throws IOException


{
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter length of rectangle box");
length=Integer.parseInt(dis.readLine());
System.out.println("Enter breadth of rectangle box");
breadth=Integer.parseInt(dis.readLine());
System.out.println("Enter height of rectangle box");
height=Integer.parseInt(dis.readLine());
}
public void volume()
{
vol=length*breadth*height;
}
public void displayVolume()
{
System.out.println("volume of rectangle box is: "+vol);
}
}

public class RectangleBoxDemo


{
public static void main(String[] args)throws Exception
{
Box box1=new Box();
box1.getData();
HR ZONE Computer Classes TM 44
box1.volume();
box1.displayVolume();
}
}

Output

Enter length of rectangle box

20

Enter breadth of rectangle box

15

Enter height of rectangle box

10

volume of rectangle box is: 3000

HR ZONE Computer Classes TM 45


Chapter 9: Working with array and string
-:Illustrations:-

1. Array object with its elements initialized by default values


Script

class testarray
{
public static void main(String[] s)
{
int marks[];
marks=new int[7];

for (int i = 0; i < 7; i++)


{
System.out.println("marks[" + i + "]is " + marks[i]);
}
}
}

Output

HR ZONE Computer Classes TM 46


2. Different ways to create and initialized array object
Script

class testarray
{
public static void main(String[] s)
{
int marks[];
marks=new int[3];

int marks2[]=new int[3];


int marks3[]=new int[3];
int marks4[]={50,60,70};
int marks5[]={70,80,90};

System.out.print("Array marks 1:\t");


display(marks,3);
System.out.print("Array marks 2:\t");
display(marks2,3);
System.out.print("Array marks 3:\t");
display(marks3,3);
System.out.print("Array marks 4:\t");
display(marks4,3);
System.out.print("Array marks 5:\t");
display(marks5,3);
}

static void display(int arr[], int size)


{
for(int i=0; i<size; i++)
{
System.out.print(arr[i] + "\t");
}
System.out.println();
}
}

HR ZONE Computer Classes TM 47


Output

Array marks 1: 0 0 0
Array marks 2: 0 0 0
Array marks 3: 0 0 0
Array marks 4: 50 60 70
Array marks 5: 70 80 90

HR ZONE Computer Classes TM 48


3. Program to compute average of 10 numbers using 1-D array and loop.
Script

class ArrayAvg
{

public static void main(String[] s)


{
double[] numbers = {10.5,20.6,30.8,15.5,17.3,25.5,27.2,20,30,18.5};
byte ctr;
double sum = 0,avg;

System.out.println("list of number is");


for (ctr=0;ctr<10;ctr++)
{
System.out.println(numbers[ctr]);
sum = sum + numbers[ctr];
}

avg = sum/10;
System.out.println("The average of above number is"+avg);
}
}

Output

list of number is
10.5
20.6
30.8
15.5
17.3
25.5
27.2
20.0
30.0
18.5
The average of above number is21.59

HR ZONE Computer Classes TM 49


4. write a java program to use sort() and fill() methods of array class.
Script

class ArrayClassSortFill
{
public static void main(String[] s)
{
double list[]= {6.4,8,7.8,9.8,9.5,6,7,8,8.5,5.9};

int index;

System.out.println("Initial Elements: ");


display(list);
java.util.Arrays.sort(list,3,9);
System.out.println("\n sort partial array: list[3] to list[8]: ");
display(list);
java.util.Arrays.sort(list);
System.out.println("\n sort whole array ");
display(list);

java.util.Arrays.fill(list,7);
System.out.println("\n Fill whole array");
display(list);
java.util.Arrays.fill(list,2,6,5);
System.out.println("\n fill partial array: list[2] to list[5]:");
display(list);
}

static void display(double ary[])


{
for(int i=0; i<ary.length;i++)
{
System.out.print(ary[i]+ "\t");
}
System.out.println();
}
}

HR ZONE Computer Classes TM 50


Output

Initial Elements:
6.4 8.0 7.8 9.8 9.5 6.0 7.0 8.0 8.5 5.9

sort partial array: list[3] to list[8]:


6.4 8.0 7.8 6.0 7.0 8.0 8.5 9.5 9.8 5.9

sort whole array


5.9 6.0 6.4 7.0 7.8 8.0 8.0 8.5 9.5 9.8

Fill whole array


7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0 7.0

fill partial array: list[2] to list[5]:

7.0 7.0 5.0 5.0 5.0 5.0 7.0 7.0 7.0 7.0

HR ZONE Computer Classes TM 51


5. write a Java Program to Search an element in an array.
Script

class LinearSrch
{
public static void main(String[] s)
{
double list[]={6,5,7,9,9.5,6.5,7.5,8};
int index;

System.out.println("Given array elements are:");


display(list);

index=search(list,8);
if(index<0)
System.out.println("\nElement 8 is not found in array");
else
System.out.println("\nElement 8 is found at position" +index);
index=search(list,5.5);
if(index<0)
System.out.println("\nElement 5.5 is not found in array");
else
System.out.println("\nElement 5.5 is found at position" +index);
}

static void display(double ary[])


{
for (int i=0; i<ary.length;i++)
{
System.out.print(ary[i]);
}
System.out.println();
}

static int search(double ary[],double x)


{
Fo
r (int i=0; i<ary.length;i++)
{
if (ary[i]==x)return i;
HR ZONE Computer Classes TM 52
}
return -1;
}
}

Output

Given array elements are:


6.05.07.09.09.56.57.58.0

Element 8 is found at position7

Element 5.5 is not found in array

HR ZONE Computer Classes TM 53


6. write a Java Pro2-D array
Script

class Array2D
{
public static void main(String[] s)
{
int marks1[][];
marks1=new int[5][3];
int marks2[][]=new int[5][3];
int marks3[][]=new int[5][3];
int
marks4[][]={{50,60,70},{35,30,50},{70,75,80},{80,85,90},{50,50,55}};
int
marks5[][]={{50,60,70},{35,30,50},{70,75,80},{80,85,90},{50,50,55}};

System.out.print("2-D Array marks 1:\t");


display(marks1,5,3);
System.out.print("2-D Array marks 2:\t");
display(marks2,5,3);
System.out.print("2-D Array marks 3:\t");
display(marks3,5,3);
System.out.print("2-D Array marks 4:\t");
display(marks4,5,3);
System.out.print("2-D Array marks 5:\t");
display(marks5,5,3);
}

static void display(int arr[][ ], int rows, int cols)


{
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
HR ZONE Computer Classes TM 54
Output

2-D Array marks 1: 0 0 0


0 0 0
0 0 0
0 0 0
0 0 0
2-D Array marks 2: 0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
2-D Array marks 3: 0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
2-D Array marks 4: 50 60 70
35 30 50
70 75 80
80 85 90
50 50 55
2-D Array marks 5: 50 60 70
35 30 50
70 75 80
80 85 90
50 50 55

HR ZONE Computer Classes TM 55


7. Program using 2-D array with variable number of columns
Script

class Array2Dchar
{
public static void main(String[] s)
{
char
names[][]={{'j','a','v','a'},{'C'},{'C','+','+'},{'B','a','s','i','c'},{'P','a','s','c','a','T'}};
System.out.println("Number o elements in 2-D
array:"+names.length+"\n");

System.out.println("Number of elements in 2-D array of characters: \n");


display(names,5);
}

static void display(char arr[][], int rows)


{
for(int i=0;i<rows;i++)
{
System.out.print("Row" +i+ "have" +arr[i].length +"character elements:
");
for(int j=0;j<arr[i].length;j++)
{
System.out.print(arr[i][j]);
}
System.out.println();
}
}
}

HR ZONE Computer Classes TM 56


Output

Number o elements in 2-D array:5

Number of elements in 2-D array of characters:

Row0have4character elements: java


Row1have1character elements: C
Row2have3character elements: C++
Row3have5character elements: Basic
Row4have6character elements: PascaT

HR ZONE Computer Classes TM 57


8. 2-D array: characters stored in bytes using corresponding integer values
Script

class Array2Dbyte
{
public static void main(String[] s)
{
byte names[]
[]={{'j','a','v','a'},{67},{'C','+','+'},{'B','a','s','i','c'},{'P','a','s','c','a','T'}};
System.out.print("Five names stored in 2-d Array of bytes:\n");
display(names,5);
}
static void display(byte arr[][],int rows)
{
for(int i=0;i<rows;i++)
{
for(int j=0;j<arr[i].length;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}

Output

Five names stored in 2-d Array of bytes:


106 97 118 97
67
67 43 43
66 97 115 105 99
80 97 115 99 97 84

HR ZONE Computer Classes TM 58


9. Comparing strings using methods of class String.
Script

class StringComparison
{
public static void main(String[] s)
{
String str1="India is great";
String str2="INDIA IS GREAT";

System.out.println("str1: "+ str1);


System.out.println("str2: "+ str2);
System.out.println("str1.equals(str2):" + (str1.equals(str2)));
System.out.println("str1.equalsIgnoreCase(str2):"+
(str1.equalsIgnoreCase(str2)));
System.out.println("str1.CompareTo(str2):" + (str1.compareTo(str2)));
System.out.println("str1.CompareToIgnoreCase(str2):"+
(str1.compareToIgnoreCase(str2)));
}
}

Output

str1: India is great


str2: INDIA IS GREAT
str1.equals(str2):false
str1.equalsIgnoreCase(str2):true
str1.CompareTo(str2):32
str1.CompareToIgnoreCase(str2):0

HR ZONE Computer Classes TM 59


-: Laboratory Exercise :-

1. Maximum and minimum temperature of the day.


Script

public class Temperature


{
public static void main(String[] args)
{
int tem[]={20,36,18,38,37,38,39,24,41,42,44,22,41};

int max=tem[0];
for(int j=1; j<=12;j++)
{
if(max<tem[j])
max=tem[j];
}
System.out.println("Maximum temperature is: "+max);

int min=tem[0];
for(int i=1; i<=12;i++)
{
if(min>tem[i])
min=tem[i];
}
System.out.println("Lowest temperature is: "+min);
}
}

Output

Maximum temeprature is: 44

Lowest temperature is: 18

HR ZONE Computer Classes TM 60


3. String is palindrome or not.
Script

class PalindromeTest
{
public static void main (String[] args)
{
StringBuffer s1= new StringBuffer("madam");
StringBuffer s2= new StringBuffer(s1);
s1.reverse();
System.out.println("Given String is:"+s2);
System.out.println("Given String is:"+s1);

if(String.valueOf(s1).compareTo(String.valueOf(s2))==0)
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}

Output

Given String is:madam

Given String is:madam

Palindrome

HR ZONE Computer Classes TM 61


4. “DD-MMM-YYYY”

Script

import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample
{
public static void main(String[] args)
{
Date today=new Date();

System.out.println("Today is:"+ today);

SimpleDateFormat DATE_FORMAT=new SimpleDateFormat("dd-


mmm-yyyy");
String date= DATE_FORMAT.format(today);
System.out.println("Today in dd-mmm-yyyy format:"+ date);

Calendar c=Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat("EEEEE");
String dayOfWeek=dateFormat.format(c.getTime());
System.out.println("Today's day is:"+ dayOfWeek);
}
}

Output

Today is:Mon Jan 09 13:10:53 IST 2023

Today in dd-mmm-yyyy format:09-010-2023

Today's day is:Monday

HR ZONE Computer Classes TM 62


5. Print the weekday on your birthday

Script

import java.util.*;

import java.text.SimpleDateFormat;

import java.text.DateFormat;

public class GetDayName

public static void main (String[] args)

Date date1=(new GregorianCalendar(1987,Calendar.APRIL,15)).getTime();

System.out.println("1990-05-19 was a" + sayDayName(date1));

public static String sayDayName(Date d)

DateFormat f=new SimpleDateFormat("EEEEE");

return f.format(d);

Output

1990-05-19 was aWednesday

HR ZONE Computer Classes TM 63


Chapter 10: Exception handling in Java
-: Illustrations :-

1. A program Illustration run-time error

Script

class RuntimeErrorDemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};

System.out.println("Statement to be executed before displaying the fifth


element");

System.out.println(citylist[5]);

System.out.println("Statement to be executed after displaying the fifth


element");
}
}

Output

Statement to be executed before displaying the fifth element


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 4
at RuntimeErrorDemo.main(RuntimeErrorDemo.java:9)

HR ZONE Computer Classes TM 64


2. A program illustrating arithmetic exception

Script

class RuntimeErrorDemo2
{
public static void main(String args[])
{
int numerator = 15;
int denominator = 0;
int answer;

System.out.println("Statement to be executed before performing division


operation");

answer = numerator/denominator;

System.out.println("Statement to be executed after performing division


operation");

}
}

Output

Statement to be executed before performing division operation

Exception in thread "main" java.lang.ArithmeticException: / by zero

at RuntimeErrorDemo2.main(RuntimeErrorDemo2.java:11

HR ZONE Computer Classes TM 65


3. A program that illustrating try block

Script

class TryBlockdemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};

System.out.println("Statement to be executed before try");

try
{
System.out.println("Statement to be executed before displaying the
fifth element");

System.out.println(citylist[5]);

System.out.println("Statement to be executed after displaying the


fifth element");
}
System.out.println("Statement to be executed before try");
}
}

Output

Statement to be executed before try

Statement to be executed before displaying the fifth element

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of


bounds for length 4

at TryBlockdemo.main(TryBlockdemo.java:13)

HR ZONE Computer Classes TM 66


4. A program that illustrates the use of try… catch

Script

class TryCatchdemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};

System.out.println("Statement to be executed before try");

try
{
System.out.println("Statement to be executed before displaying the
fifth element");

System.out.println(citylist[5]);

System.out.println("Statement to be executed after displaying the


fifth element");
}
catch(ArrayIndexOutOfBoundsException eobj)
{
System.out.println("Within Catch Block");
System.out.println("Caught Exception object of type: "+eobj);
}
System.out.println("Statement to be executed before try");
}
}

Output

Statement to be executed before try

Statement to be executed before displaying the fifth element

Within Catch Block

Caught Exception object of type: java.lang.ArrayIndexOutOfBoundsException: Index 5


out of bounds for length 4

Statement to be executed before try


HR ZONE Computer Classes TM 67
5. A program that which illustrates finally block without catch block

Script

class FinallyDemo
{
public static void main(String args[])
{
String citylist[]={"Ahemedabad","Baroda","Rajkot","Surat"};
int numerator = 15, denominator = 0, answer;
System.out.println("Statement to be executed before try block");

try
{
System.out.println("Begininig of try block...");

System.out.println(citylist[5]);

answer = numerator/denominator;
System.out.println("End of try block");
}
finally
{
System.out.println("this part of code will always get executed");
}
System.out.println("End of program...");
}
}

Output

Statement to be executed before try block

Begininig of try block...

this part of code will always get executed

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of


bounds for length 4

at FinallyDemo.main(FinallyDemo.java:13)

HR ZONE Computer Classes TM 68


6. Program which illustrates the use of throw keyword

Script

class ThrowDemo
{
public static void main(String args[])
{
try
{
System.out.println("Before throwing an exception object....");

Exception myobject = new Exception("Demonstration of


throw...");

throw myobject;

}
catch(Exception eobj)
{
System.out.println("Exception caught: "+eobj);
}
}
}

Output

Before throwing an exception object....

Exception caught: java.lang.Exception: Demonstration of throw...

HR ZONE Computer Classes TM 69


7. Program which illustrates the use of throws keyword

Script

class ThrowDemoB

public static void main(String args[])

try

performDivision();

catch(ArithmeticException eobj)

System.out.println("Exception caught: "+eobj);

public static void performDivision() throws ArithmeticException

int ans;

ans = 15/0;

Output

Exception caught: java.lang.ArithmeticException: / by zero

HR ZONE Computer Classes TM 70


8. User defined exception class.(error)

Script

import java.util.Scanner;
class InvalidMarksException extends java.lang.Exception
{
public InvalidMarksException(String message)
{
super(message);
}
}

class CustomExceptionDemo2
{
public static void main(String args[])
{
Scanner kbinput=new Scanner(System.in);
int marks;
boolean continueLoop = true;
do
{
System.out.println("Enter the marks: ");
marks = kbinput.nextInt();
System.out.println("You entered"+ marks);

try
{
if(marks<0||marks>100)
{
throw new InvalidMarksException ("Wrong
marks...");
}
else{
System.out.println("Marks are valid");
}
continueLoop = false;
}
catch(InvalidMarksException eobj)
{
System.out.println("Exception Caught: "+ eobj);
HR ZONE Computer Classes TM 71
}
}
while(continueLoop);
}
}

Output

Error: Main method not found in class InvalidMarksException, please define the main
method as:

public static void main(String[] args)

or a JavaFX application class must extend javafx.application.Application

HR ZONE Computer Classes TM 72


Laboratory exercise

1. Add elements in array.

Script

import java.io.*;
class ArrayDemo1
{
static int arr[]=new int[10];
public static void add()throws IOException
{
int p,n;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Array element");
n=Integer.parseInt(dis.readLine());
System.out.println("At which index you want to insert this element");
p=Integer.parseInt(dis.readLine());

try
{
arr[p]=n;
System.out.println("Element inserted");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception occurs");
System.out.println("provied index is out of array bounds");
}
}

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


{
System.out.println("Calling add method to insert element into the array");
add();
}
}

HR ZONE Computer Classes TM 73


Output

Calling add method to insert element into the array


Enter Array element
55
At which index you want to insert this element
2
Element inserted

HR ZONE Computer Classes TM 74


2. Remove try…catch block from the method

Script

import java.io.*;
class ArrayDemo2
{
static int arr[]=new int[10];
public static void add()throws IOException,ArrayIndexOutOfBoundsException
{
int p,n;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Array element");
n=Integer.parseInt(dis.readLine());
System.out.println("At which index you want to insert this element");
p=Integer.parseInt(dis.readLine());
arr[p]=n;
System.out.println("Element inserted");
}

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


{
System.out.println("Calling add method to insert element into the array");
add();
}
}

Output

Calling add method to insert element into the array


Enter Array element
1
At which index you want to insert this element
2
Element inserted

HR ZONE Computer Classes TM 75


3. Java program that throws and catches an Arithmetic exception

Script

import java.io.*;
class SqrtException
{
public static void main(String ar[])throws IOException
{
double n,r;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter Value to obtain aquare root");
n=Double.parseDouble(dis.readLine());
try
{
if(n<0)
{
throw new ArithmeticException();
}
r=Math.sqrt(n);
System.out.println("Square root is :"+ r);

}
catch(ArithmeticException e)
{
System.out.println("Exception occurs");
System.out.println("Cannot find the square of negative value ");
}

}
}
Output

Enter Value to obtain aquare root

625

Square root is :25.0

HR ZONE Computer Classes TM 76


4. Validate the birth date.

Script

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.*;
class InvalidBirthDateException extends Exception
{
public InvalidBirthDateException(String m)
{
System.out.println(m);
System.out.println("You entered an invalid date");
}
}

class BirthDateDemo
{
public static void main(String[] args) throws IOException,ParseException
{
String s1,s2;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter your birth date in DD.MM.YYYY format");
s1=dis.readLine();
SimpleDateFormat sdf1=new SimpleDateFormat("dd.MM.yyyy");
Date date1=sdf1.parse(s1);
SimpleDateFormat df=new SimpleDateFormat("dd.MM.yyyy");
Date date=new Date();
s2=df.format(date);
Date date2=df.parse(s2);

try
{
if(date1.after(date2) || date1.equals(date2))
{
throw new InvalidBirthDateException("Exception occurs");
}
else
{
System.out.println("This is a valid date,no exception");
HR ZONE Computer Classes TM 77
}
}
catch(InvalidBirthDateException e)
{}
}
}

Output

Enter your birth date in DD.MM.YYYY format

10-09-2004

Exception in thread "main" java.text.ParseException: Unparseable date: "10-09-2004"

at java.base/java.text.DateFormat.parse(DateFormat.java:399)

at BirthDateDemo.main(InvalidBirthDateException.java:23)

HR ZONE Computer Classes TM 78


6. Invalid transaction

Script

import java.io.*;
class InvalidTransaction extends Exception
{
public InvalidTransaction(String m)
{

System.out.println("Transaction exception occurs");


System.out.println(m);
}
}

class BankTransaction
{
public static void main(String ar[]) throws IOException
{
int withdrawAmount,balanceAmount;
DataInputStream dis= new DataInputStream(System.in);
System.out.println("Enter balance amount");
balanceAmount=Integer.parseInt(dis.readLine());
System.out.println("Enter withdrawal amount");
withdrawAmount=Integer.parseInt(dis.readLine());

try
{
if(withdrawAmount>balanceAmount)
{
throw new InvalidTransaction("No enough balance
amount");
}
else
{
System.out.println("Withdrawal is possible");
}
}
catch (InvalidTransaction e)
{
System.out.println(e);
HR ZONE Computer Classes TM 79
}
}
}

Output

Enter balance amount

50000

Enter withdrawal amount

20000

Withdrawal is possible

HR ZONE Computer Classes TM 80


Chapter 11: File handling
-: Illustrations :-
2. Program to illustrate file write operation.

Script
import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
FileReader frobject=null;

try
{
frobject=new FileReader("Charfile.txt");
int i;
char ch;
while ((i=frobject.read())!=-1)
{
ch=(char) i;
System.out.print(ch);
}
}

catch(Exception eobj)
{
System.out.println(eobj);
}

finally
{
try
{
frobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}

HR ZONE Computer Classes TM 81


}
}
}

Output

java.io.FileNotFoundException: Charfile1.txt (The system cannot find the file specified)

java.lang.NullPointerException: Cannot invoke "java.io.FileReader.close()" because


"<local1>" is null

HR ZONE Computer Classes TM 82


3. Program to illustrate file read operation

Script

import java.io.*;
class FileWriterDemo
{
public static void main(String args[])
{
FileReader frobject=null;

try
{
frobject=new FileReader("Charfile1.txt");
int i;
char ch;
while ((i=frobject.read())!=-1)
{
ch=(char) i;
System.out.print(ch);
}
}

catch(Exception eobj)
{
System.out.println(eobj);
}

finally
{
try
{
frobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}
}

Output

HR ZONE Computer Classes TM 83


4. Program to read and write bytes to binary file

Script

import java.io.*;
class BinaryFileDemo
{
public static void main (String args[])
{
FileOutputStream outobject= null;
FileInputStream inobject= null;

String cities="Rajkot \n Ahmedabad \n Vadodra \n Vapi \n";

byte citiesarray[] = cities.getBytes();

try
{
outobject= new FileOutputStream("Binaryfile.dat");

outobject.write(citiesarray);
outobject.close();

inobject = new FileInputStream("Binary.dat");

int i;

while((i=inobject.read())!=-1)
{
System.out.print((char)i);
}
inobject.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}

HR ZONE Computer Classes TM 84


Output
java.io.FileNotFoundException: Binary.dat (The system cannot find the file specified)

HR ZONE Computer Classes TM 85


5. Program to add two numbers.

Script

import java.io.*;
import java.util.*;
class ScannerInputDemo
{
public static void main(String args[])
{
Scanner kbinput=null;
int number1;
int number2;
int sum=0;

try{
kbinput = new Scanner(System.in);
System.out.println("Enter The first number: ");
number1=kbinput.nextInt();
System.out.println("Enter The Second number: ");
number2=kbinput.nextInt();
sum= number1+number2;
System.out.println("Sum is:"+sum);
}
catch(Exception eobj)
{
System.out.println(eobj);
}
finally {
try
{
kbinput.close();
}
catch(Exception eobj)
{
System.out.println(eobj);
}
}
}
}
HR ZONE Computer Classes TM 86
Output
Enter The first number:

21

Enter The Second number:

16

Sum is:37

HR ZONE Computer Classes TM 87


6. Program to calculate the total marks of each student

Script

import java.io.*;
import java.util.*;

class ScannerFileDemo
{
public static void main (String args[])
{
Scanner fileinput=null;
int rollno, mark1,mark2,mark3,total;
String name=null;
File fobject;

try
{
fobject=new File("Studets.dat");

fileinput=new Scanner(fobject);

System.out.println("Defualt Delimeter is:"+ fileinput.delimiter()+


"\n");

while(fileinput.hasNext())
{
rollno=fileinput.nextInt();
name=fileinput.next();
mark1=fileinput.nextInt();
mark2=fileinput.nextInt();
mark3=fileinput.nextInt();
total=mark1+mark2+mark3;
System.out.println("Total marks of rollno "+ rollno
+","+name+ "are :"+ total);
}
fileinput.close();
}
catch(Exception eobj)
{
HR ZONE Computer Classes TM 88
System.out.println(eobj);
}
}
}

Output
java.io.FileNotFoundException: Studets.dat (The system cannot find the file specified)

HR ZONE Computer Classes TM 89


7. Program to read username and password

Script

import java.io.Console;
import java.util.Arrays;
public class ConsoleDemo {
public static void main(String[] args)
{
Console console=System.console();
String username=console.readLine("Username: ");
char[] password= console.readPassword("Password");

if(username.equals("admin")&&
String.valueOf(password).equals("secret"))
{
console.printf("Welcome to java application \n");
}
else {
console.printf("Invalid username or password. \n");
}
}
}

Output

Exception in thread "main" java.lang.NullPointerException: Cannot invoke


"java.io.Console.readLine(String, Object[])" because "<local1>" is null

at ConsoleDemo.main(ConsoleDemo.java:7)

HR ZONE Computer Classes TM 90

You might also like