Sei sulla pagina 1di 43

Java Programming [CE241] Enrolment No.

:18DCS074

11. Design a class named Circle containing following attributes and behavior.
 One double data field named radius. The default value is 1.
 A no-argument constructor that creates a default circle.
 A Single argument constructor creates Circle with the specified
radius.
 A method named getArea() that returns area of the Circle.
 A method named getPerimeter() that returns perimeter of it.
PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
class Circle
{ double radius;
Circle()
{ radius=1; }
Circle(double r)
{ radius=r; }
double getArea()
{ return 3.14*radius*radius; }
double getPerimeter()
{ return 2*3.14*radius; } }
class Main extends Circle
{ public static void main(String args[])
{ Circle c=new Circle();
double rs,area,perimeter;
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Scanner s=new Scanner(System.in);
area=c.getArea();
perimeter=c.getPerimeter();
System.out.println("area of circle is :" + area);
System.out.println("perimeter of circle is :" + perimeter);
System.out.print("\nenter the value of radius: ");
rs=s.nextDouble();
Circle c1=new Circle(rs);
area=c1.getArea();
perimeter=c1.getPerimeter();
System.out.println("area of circle is :" + area);
System.out.println("perimeter of circle is :" + perimeter); }}

DEPSTAR 16 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

OUTPUT:

CONCLUSION:
In this program we have learn the use of default constructor, parameterized
constructor in java.

DEPSTAR 17 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

12. Design a class named Account that contains:

 A private int data field named id for the account (default 0).
 A private double data field named balance for the account (default

stores the current interest rate (default 7%). Assume all accounts have
the same interest rate.
 A private Date data field named dateCreated that stores the date when
the account was created.
 A no-arg constructor that creates a default account.
 A constructor that creates an account with the specified id and initial
balance.
 The accessor and mutator methods for id, balance, and
for dateCreated.
 A method getMonthlyInterestRate() that returns the monthly interest
rate.
 A method named getMonthlyInterest() that returns the monthly
interest.
 method withdraw that withdraws a specified amount from the
account.
 A method named deposit that deposits a specified amount to the
account.
PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
import java.util.Date;
class Account
{
int id;
Scanner s=new Scanner(System.in);
double balance,annualInterestRate;
String date;
Account()
{

private id=0;
private balance=500;
private annualInterestRate=7;
date="12/02/2001";

DEPSTAR 18 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

}
Account(int i1,double balan)
{
id=i1;
balance=balan;
}
int getId()
{
return id; }
double getBalance()
{ return balance; }
double getAnnualInterestRate()
{ return annualInterestRate; }
String getDate()
{ return date; }}
class Acc
{ public static double getMonthlyInterest(Account obj)
{ return (obj.getBalance() * obj.getAnnualInterestRate() * 0.01 / 12);}
public static double getMonthlyInterestRate(Account obj)
{ return ((obj.getAnnualInterestRate()/1200) * (getMonthlyInterest(obj)));}
public static void withdraw(Account obj)
{ double with;
Scanner s1=new Scanner(System.in);
System.out.println("enter the money you want to withdraw:");
with=s1.nextDouble();
obj.balance=obj.balance-with;
System.out.println("your current balance is: " + obj.balance); }
public static void deposite(Account obj)
{ double dep;
Scanner s2=new Scanner(System.in);
System.out.println("enter the money you want to deposite:");
dep=s2.nextDouble();
obj.balance=obj.balance+dep;
System.out.println("your current balance is: " + obj.balance);}
public static void main(String args[])
{ Account a=new Account();
double mi,mir;
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
mi=getMonthlyInterest(a);
DEPSTAR 19 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

mir=getMonthlyInterestRate(a);
withdraw(a);
deposite(a);
System.out.println("your monthly interest is:"+ mi + " \n"+"your
monthly interest rate is:"+ mir );
}
}

OUTPUT:

CONCLUSION:
In this program we have learn how we can access private data members of
any class using other member functions.

DEPSTAR 20 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

13. Use the Account class created as above to simulate an ATM machine.
Create 10 accounts with id AC001…..AC010 with initial balance 300₹. The
system prompts the users to enter an id. If the id is entered incorrectly, ask
the user to enter a correct id. Once an id is accepted, display menu with
multiple choices. 1. Balance inquiry 2. Withdraw money [Maintain
minimum balance 300₹] 3. Deposit money 4. Money Transfer 5. Create
Account 6. Deactivate Account 7. Exit Hint: Use ArrayList, which is can
shrink and expand with compared to Array.
PROGRAM CODE:
import java.util.Scanner;
import java.util.ArrayList;
import java.lang.NullPointerException;
class Test
{ public static void main(String[] args)throws NullPointerException
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
int i;
ArrayList<Account> arrL=new ArrayList<Account>();
for(i=0;i<10;i++)
{ Account ac=null;
if(i<9)
ac=new Account("AC00"+(i+1));
else
ac=new Account("AC0"+(i+1));
arrL.add(ac);
}
Account ac=null;
Scanner sc=new Scanner(System.in);
int temp;
do
{ Account.menu();
System.out.print("\nEnter the choice : ");
temp=sc.nextInt();
if(temp==7)
System.exit(0);
if(temp==5)
{ System.out.print("\nEnter the Account id : ");
String id=sc.next();
ac=new Account(id);
arrL.add(ac);
DEPSTAR 21 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

System.out.println("Your account has been successfully created.");


continue;
}
if(temp==6)
{ System.out.print("\nEnter the Account id : ");
String id=sc.next();
for(i=0;i<arrL.size();i++)
{ ac=arrL.get(i);
if(id.equals(ac.getId()))
{ arrL.remove(i);
break;
}
}
System.out.println("Your account has been successfully deleted.");
continue;
}
do
{ System.out.print("\nEnter the Account id : ");
String id=sc.next();
for(i=0;i<arrL.size();i++)
{ ac=arrL.get(i);
if(id.equals(ac.getId()))
break;
}
if(i==arrL.size())
System.out.println("Enter valid id ");
else
break;
}while(true);
switch(temp)
{
case 1:
ac.balanceInquiry();
break;
case 2:
ac.withdrawMoney();
break;
case 3:
ac.depositMoney();
break;
DEPSTAR 22 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

case 4:
int j;
System.out.print("Enyer the Transfered Account id : ");
String id1=sc.next();
System.out.print("Enter the Transfered amount : ");
double db=sc.nextDouble();
Account ac1=null;
for(j=0;j<10;j++)
{
ac1=arrL.get(j);
if((ac1.getId()).equals(id1))
break;
}
ac.moneyTransfer(ac1,db);
break;
default:
System.out.println("Please Enter the valid choice.");
}
}while(true); }}
class Account
{ private Scanner sc=new Scanner(System.in);
private String id="";
private double balance=300;
public Account(String id)
{
this.id=id;
}
public Account(String id,double balance)
{ this.id=id;
this.balance=balance;
}
public Account()
{ System.out.print("\nEnter the Account id : ");
id=sc.next();
System.out.print("\nEnter the initial amount : ");
balance=sc.nextDouble(); }
public void balanceInquiry()
{ System.out.println("Your Bank balance is : "+balance); }

public void withdrawMoney()


DEPSTAR 23 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

{ int flag=0;
do
{ System.out.print("\nEnter the withdral amount : ");
double temp=sc.nextDouble();
if(temp<0)
System.out.println("Please enter the valid withdraw amount.");
else if(balance-temp>=300)
{ balance-=temp;
break; }
else
System.out.println("you are not able to withdraw money.");
}while(true);
System.out.println("Your available balance is : "+balance);
}

public void depositMoney()


{ do
{System.out.print("\nEnter the deposit amount : ");
double temp=sc.nextDouble();
if(temp<0)
System.out.println("Please enter the valid deposit amount.");
else
{ balance+=temp;
break;
}
}while(true);
System.out.println("Your available balance is : "+balance);
}
public void moneyTransfer(Account ac1,double bal)
{
if(this.balance-bal>=300)
{ this.balance-=bal;
ac1.setBalance(ac1.getBalance()+bal);
System.out.println("Money Transfer is successfully completed.");
}
else
System.out.println("Money Transfer is not successfully completed.");
}
public void createAccount(Account ac)
{ ac=new Account();
DEPSTAR 24 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

System.out.println("Your Account has been successfully created.");}


public static void menu()
{System.out.println("\n 1. Balance inquiry \n 2. Withdraw money \n
3. Deposit money\n 4. Money Transfer\n 5. Create Account\n 6. Deactivate
Account\n 7. Exit");}
public void setBalance(double balance)
{this.balance=balance;}
public double getBalance()
{return balance; }
public String getId()
{return id;}}
OUTPUT:

CONCLUSION:
In this program we have learn the use of Array List ,switch statements and
do while loops using which we have create functions for ATM.

DEPSTAR 25 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

14. Write a java program that implements educational hierarchy using


inheritance.

PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
class Office
{ int empid;
String empName;
double salary;
void getValue(){};}
class Teaching extends Office
{ String designation;
void setValue()
{ Scanner s=new Scanner(System.in);
System.out.println("Enter designation of Employee:");
designation=s.nextLine();
System.out.println("Enter Employee name:");
empName=s.nextLine();
System.out.println("Enter Employee Id:");
empid=s.nextInt();
System.out.println("Enter salary:");
salary=s.nextDouble(); }
void getValue()
{ System.out.println("DESIGNATION: " + designation);
System.out.println("EMPLOYEE ID: " + empid);
System.out.println("EMPLOYEE NAME: " + empName);
System.out.println("SALARY:" + salary); } }
class NonTeaching extends Office
{ String designation;
void setValue()
{ Scanner s=new Scanner(System.in);
DEPSTAR 26 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

System.out.println("Enter designation of Employee:");


designation=s.nextLine();
System.out.println("Enter Employee name:");
empName=s.nextLine();
System.out.println("Enter Employee Id:");
empid=s.nextInt();
System.out.println("Enter salary:");
salary=s.nextDouble(); }
void getValue()
{ System.out.println("DESIGNATION: " + designation);
System.out.println("EMPLOYEE ID: " + empid);
System.out.println("EMPLOYEE NAME: " + empName);
System.out.println("SALARY:" + salary); } }
class Main
{ public static void main(String args[])
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Teaching t1=new Teaching();
NonTeaching t2=new NonTeaching();
t1.setValue();
t1.getValue();
t2.setValue();
t2.getValue();
}}
OUTPUT:

CONCLUSION:
In this program we have learn the use of hierarchical inheritance in java.

DEPSTAR 27 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

15. Develop a Program that illustrate method overloading concept.


PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
class Ex15
{ public static void main(String args[])
{
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Calc cal=new Calc();
System.out.println("5+3 = "+cal.sum(5,3));
System.out.println("5+3+2 = "+cal.sum(5,3,2));
System.out.println("5+3+2+1 = "+cal.sum(5,3,2,1)); }}
class Calc
{
public int sum(int a,int b)
{
return a+b;
}
public int sum(int a,int b,int c,int d)
{
return a+b+c+d;
}
public int sum(int a,int b,int c)
{
return a+b+c;
}
}
OUTPUT:

CONCLUSION:
In this program we have learn the concepts of method overloading in java.

WAP that illustrate the use of interface reference. Interface Luminious


Object has two method lightOn() and lightOff(). There is one class Solid

DEPSTAR 28 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

16. extended by 2 classes Cube and Cone. There is one class LuminiousCone
extends Cone and implements Luminoius Interface. LumminuiousCube
extends Cube and implements Luminious Interface. Create a object of
LuminiousCone and LuminousCube and use the concept of interface
reference to invoke the methods of interface.
PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
interface Luminious //declaring an interface Luminious
{
void lightOn();
void lightOff();
}
class Solid
{ //declaring and empty class Solid
}
class Cube extends Solid //declaring a empty Cube class extends
Solid
{
}
class Cone extends Solid //declaring a empty Cone class extends Solid
{
}
class LuminuiousCube extends Cube implements Luminious
{ //implementing Luminious and extending
Cube
public void lightOn()
{
System.out.println("Luminuious Cube light on.");
}
public void lightOff()
{
System.out.println("Luminuious Cube light off.");
}
}
class LuminiousCone extends Cone implements Luminious
{ //implementing Luminious and extending Cone
public void lightOn()
{
System.out.println("Luminuious Cone light on."); }
DEPSTAR 29 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

public void lightOff()


{
System.out.println("Luminuious Cone light off.");
}
}
class Ex16M
{
public static void main(String[] args)
{
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
System.out.println("for Luminuious Cube");
Luminious Lu=new LuminuiousCube();
Lu.lightOn();
Lu.lightOff();
System.out.println("\nfor Luminuious Cone");
Lu=new LuminiousCone();
Lu.lightOn();
Lu.lightOff();
}
}
OUTPUT:

CONCLUSION:
In this program we have learn the basic concepts of how to implement
interface in java.

DEPSTAR 30 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

17. WAP that illustrate the interface inheritance. Interface P is extended by P1


and P2 interfaces. Interface P12 extends both P1 and P2. Each interface
declares one method and one constant. Create one class that implemetns
P12. By using the object of the class invokes each of its method and
displays constant.

PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
interface p //declaring interface p
{
final int a=100;
public void showP();
}
interface p1 extends p //extending interface p with p1
{
final int a=200;
public void showP1();
}
interface p2 extends p //extending interface p with p2
{
final int a=300;
public void showP2();
}
interface p12 extends p1,p2 //extending p with p1 and p2 both
{ final int a=400;
public void showP12();
}
class Test1 implements p12
{
public void showP12()
{
System.out.println("P12.A = "+p12.a);
}
public void showP2()
{
System.out.println("P2.A = "+p2.a);
}
public void showP1()
{
DEPSTAR 31 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

System.out.println("P1.A = "+p1.a);
}
public void showP()
{
System.out.println("P.A = "+p.a);
}
public void show()
{
showP();
showP1();
showP2();
showP12();
}
}
class Ex17M
{
public static void main(String[] args)
{
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Test1 t1=new Test1();
t1.show();
}
}
OUTPUT:

CONCLUSION:
In this program we have learn inheritance using interface , also we have
learn the use of implements and extends keyword.

DEPSTAR 32 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

18. Create an abstract class Robot that has the concretre subclasses , RobotA,
RobotB, RobotC. Class RobotA1 extends RobotA, RobotB1 extends
RobotB and RobotC1 extends RobotC. There is interface Motion that
declares 3 methods forward(), reverse() and stop(), implemented by RobotB
and RobotC. Sound interface declare method beep() implemented by
RobotA1, RobotB1 and RobotC1. Create an instance method of each class
and invoke beep() and stop() method by all objects.
PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
interface sound //declaring interface Sound
{
void beep();
}
interface Motion //declaring interface Motion
{
public void forward();
public void reverse();
public void stop();
}
abstract class Robot //an abstarct class Robot
{
abstract public void bulid();
}
class RobotA extends Robot
{
public void bulid()
{
System.out.println("robot A is build");
}
}
class RobotA1 extends RobotA
{
public void beep()
{
System.out.println("beep beep"); //functions to check working of
robot
}}
class RobotB extends Robot implements Motion
{
DEPSTAR 33 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

public void bulid()


{
System.out.println("robot B is build");
}
public void forward()
{
System.out.println("robotB moves forward");
}
public void reverse()
{
System.out.println("robotB moves reverse");
}
public void stop()
{
System.out.println("robotB get stop");
}
}
class RobotB1 extends RobotB implements sound
{
public void beep()
{
System.out.println("beep beep");
}}
class RobotC extends Robot implements Motion
{
public void bulid()
{
System.out.println("robot C is build");
}
public void forward()
{
System.out.println("robotC moves forward");
}
public void reverse()
{
System.out.println("robotC moves reverse");
}
public void stop()
{ System.out.println("robotC get stop"); }}
class RobotC1 extends RobotC implements sound
DEPSTAR 34 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

{ public void beep()


{ System.out.println("beep beep");
}}
class ex18
{
public static void main(String args[])
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
RobotA1 a=new RobotA1();
a.beep();
RobotB1 b=new RobotB1();
b.beep();
b.stop();
RobotC1 c=new RobotC1();
c.beep();
c.stop();
}}
OUTPUT:

CONCLUSION:
In this program we have learn inheritance with abstract class and interface in
java.

DEPSTAR 35 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

19. Write a java program to create an abstract class named Shape that contains
two integers and an empty method named printArea(). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes
extends the class Shape. Each one of the classes contain only the method
printArea( ) that prints the area of the given shape.
PROGRAM CODE:
import java.util.*;
import java.util.Scanner;
abstract class shape //abstract class
{
abstract void PrintArea();
abstract void getValue();
int length;
int width;
}
class Rectangle extends shape
{
void getValue()
{
Scanner s=new Scanner(System.in);
length=s.nextInt();
width=s.nextInt();
}
void PrintArea() //area of rectangle
{
System.out.println("Area Of Rectangle: "+(length*width));
}
}
class Triangle extends shape
{
void getValue()
{
Scanner s=new Scanner(System.in);
length=s.nextInt();
width=s.nextInt();
}
void PrintArea() //area of trinagle
{ System.out.println("Area Of Triangle: "+(0.5*length*width)); }}
class Circle extends shape
{ void getValue()
DEPSTAR 36 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

{ Scanner s=new Scanner(System.in);


length=s.nextInt();
width=s.nextInt();}
void PrintArea()
{ System.out.println("Area Of Circle: "+(Math.PI*length*length)); }}
class ex19
{ public static void main(String args[])
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Rectangle r=new Rectangle();
Triangle t=new Triangle();
Circle c=new Circle();
r.getValue();
r.PrintArea();
t.getValue();
t.PrintArea();
c.getValue();
c.PrintArea();}}

OUTPUT:

CONCLUSION:

In this practical we have learn Hierarchical inheritance using abstract class.


Using which we have print different area of different shapes.

DEPSTAR 37 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

20. Write a java program to find the details of the students eligible to enroll for
the examination ( Students, Department combinedly give the eligibility
criteria for the enrollement class) using interfaces

PROGRAM CODE:
import java.lang.*;
import java.util.*;
class Student
{
int studentId;
Scanner s=new Scanner(System.in);
String studentName,Class;
int getStudentId()
{
return studentId;
}
String getStudentName()
{
return studentName;
}
String getStudentClass()
{
return Class;
}
}
interface Department
{
int studentId1=0;
int attendance1=0;
double getAttendence();
DEPSTAR 38 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

class Exam extends Student implements Department


{
double attendLecture,totalLecture;
int studentId= studentId1;
double attendance = attendance1;

public double getAttendence()


{
return this.attendance;
}
boolean eligible() //function to check student eligibility
{
if(this.attendance>75)
{
return true;
}
else
return false;}
void calculateAttendence()
{this.attendance=(this.attendLecture/this.totalLecture)*100;}
void setValue() //function to set info of students
{
System.out.println("Enter Student Id :");
super.studentId=s.nextInt();
s.nextLine();
System.out.println("Enter Student Name :");
super.studentName=s.nextLine();
System.out.println("Enter Student Class :");
super.Class=s.nextLine();
System.out.println("Enter attendLecture");
this.attendLecture=s.nextInt();
System.out.println("Enter totalLecture");
this.totalLecture=s.nextInt();
}
}
class ex21
{
public static void main(String []args)
DEPSTAR 39 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

{
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Exam E=new Exam();
E.setValue();
E.calculateAttendence();
System.out.println("Student Id : "+E.getStudentId());
System.out.println("Student Name : "+E.getStudentName());
System.out.println("Student Class : "+E.getStudentClass());
System.out.println("Student attendance : "+E.getAttendence());
System.out.println("You are eligible or not for Exam :
"+E.eligible());
}
}

OUTPUT:

CONCLUSION:
We have created a program for students eligible to enroll for the
examination using interface.

DEPSTAR 40 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

21. Write a java program which shows importing of classes from other user
define packages.
PROGRAM CODE:
Code1:
package mypack; //makling package mypack
class Sup1
{
public void hello()
{
System.out.println("Hello World");
}
}

Code 2:
import java.util.*;
import mypack.Sup1; //importing Sup1 class from mypack
class Sub1
{
public static void main(String args[])
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
{ Sup1 a=new Sup1();
a.hello();
}}

OUTPUT:

CONCLUSION:
In this program we have learn the basics concepts of packages in java.

DEPSTAR 41 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

22. Write a program that demonstrates use of packages & import statements.

PROGRAM CODE:
//this is the class define in one package
package myPackage; //making a Demo class in myPackage
public class Demo{
public Demo(){
System.out.println("In class Demo");}
public void printSomething(){
System.out.println("Print Something...");
}}
//this the class containing main which import myPackage
import myPackage.*; //importing myPackage
class Prac22{
public static void main(String []args){
Demo d = new Demo();
d.printSomething();
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074"); }}
OUTPUT:

CONCLUSION:
In this practical we have learn how to import a class define in another
package using import keyword.

DEPSTAR 42 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

23. Write a program that illustrates the significance of interface default method.

PROGRAM CODE:

interface one{
String s1 = "interface 1";
void display();
default void useDefault(){ //default method of
interface
System.out.println("default method define in interface 1");}}
class Implements implements one
{ public void display(){
System.out.println("you are in " + s1); }}
class Prac23{
public static void main(String []args){
Implements i = new Implements();
i.display();
i.useDefault(); //calling default method of
interface
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074"); }}

OUTPUT:

CONCLUSION:
In this practical we have learn the significance of interface default method.
Which is used to define any method in interface.

DEPSTAR 43 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

24. WAP to show the try - catch block to catch the different types of exception.
PROGRAM CODE:
import java.util.*;
class ex24
{ public static void main(String ...arg)
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
try //try block 1
{ System.out.println("1st Try block");
System.out.println(10/0); }
catch(ArithmeticException e) //catch block 1
{ System.out.println(e); }
try //try block 2
{ System.out.println("2nd try block");
int [] arr= new int[4];
int i= arr[4]; }
catch(ArrayIndexOutOfBoundsException e) //catch block 2
{ System.out.println(e); }
try { //try block 3
System.out.println("3rd try block");
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e) //catch block 3
{ System.out.println("NullPointerException.."); } }}
OUTPUT:

CONCLUSION:
In this practical we have learn the use of try and catch block to handle the
different types of exception.

DEPSTAR 44 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

25. WAP to generate user defined exception using “throw” and “throws”
keyword.

PROGRAM CODE:
import java.io.IOException;
class Exm25{
void m()throws IOException{
throw new IOException("device error"); //throw an exception
void n()throws IOException{
m(); //call the m() method
}
void p(){
try{
n(); //call the n() method
}catch(Exception e){System.out.println(e);} //catch the Exception
}
public static void main(String args[]){
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
Exm25 obj=new Exm25();
obj.p();
System.out.println("Then Normal flow ");
}
}
OUTPUT:

CONCLUSION:
In this practical we have learn the use of throws and throw keyword to
handle the Exception.

DEPSTAR 45 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

26. Write a program that raises two exceptions. Specify two „catch‟ clauses for
the two exceptions. Each „catch‟ block handles a different type of exception.
For example the exception could be „ArithmeticException‟ and
„ArrayIndexOutOfBoundsException‟. Display a message in the „finally‟
block.

PROGRAM CODE:
import java.util.*;
class ex26
{
public static void main(String ...arg)
{
try
{ System.out.println("Try block");
int [] arr= new int[4];
int i= arr[4]; } //Exception
catch(ArithmeticException e) //catch block 2
{ System.out.println(e); }
catch(ArrayIndexOutOfBoundsException e) //catch block 2
{ System.out.println(e); }
Finally //finally block
{
System.out.println("This is finally block");
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}}}
OUTPUT:

CONCLUSION:
In this practical we have learn the use of finally block and also how we can
use different catch blocks for same try block to catch different types of
exception.

DEPSTAR 46 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

27. WAP to show how to create a file with different mode and methods of File
class to find path, directory etc.
PROGRAM CODE:
import java.util.*;
import java.io.*;
import java.io.File;
class File2
{
public static void main(String[] args) {
File f = new File("input.txt");
System.out.println("File name :"+f.getName());
System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Exists :"+f.exists());
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
}
OUTPUT:

CONCLUSION:
In this program we have learn the use of different methods to get the path
and directory of a file.

DEPSTAR 47 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

28. Write a program to show a tree view of files and directories under a
specified drive/volume.
PROGRAM CODE:
import java.util.*;
import java.io.*;
import java.io.File;
public class FILE3
{
public static void main(String args[]) throws IOException
{
String maindir="D:\\java";
File f=new File(maindir);
File arr[] = f.listFiles();
if(f.exists() && f.isDirectory())
{
System.out.println("Files from main directory : " + maindir);
}
RecursivePrint(arr,0,0);
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
static void RecursivePrint(File[] arr,int index,int level)
{
if(index == arr.length)
return;
for (int i = 0; i < level; i++)
System.out.print("\t");
if(arr[index].isFile())
System.out.println(arr[index].getName());
else if(arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}
RecursivePrint(arr,++index, level);
}
}

DEPSTAR 48 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

OUTPUT:

CONCLUSION:
In this program we have learn how to show a tree view of files and
directories under a specified drive/volume.

DEPSTAR 49 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

29. Write a Java program that reads on file name from the user, then displays
information about whether the file exists, whether the file is readable,
whether the file is writable, the type of file and the length of the file in
bytes?

PROGRAM CODE:
import java.util.*;
import java.io.*;
class File4
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
String nameOfFile;
nameOfFile=s.nextLine();
File f=new File(nameOfFile);
nameOfFile=f.getName();
if(f.exists())
{
System.out.println(nameOfFile + " exists");
}
else
{
System.out.println(nameOfFile + " does not exists");

}
if(f.canRead())
{
System.out.println(nameOfFile + " is Readable");
}
else
{
System.out.println(nameOfFile + " cannot Read");
}
if(f.canWrite())
{
System.out.println(nameOfFile + " is Writable");
}
else
{
DEPSTAR 50 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

System.out.println(nameOfFile + " can't write");


}
System.out.println("Extension of file :" + getFileexten(f));
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
private static String getFileexten(File f){
String fileType="undetermined";
try
{
if(f != null && f.exists()){
String nameOfFile=f.getName();

fileType= nameOfFile.substring(nameOfFile.lastIndexOf("."));
}
}
catch(Exception e)
{
fileType="";
}
return fileType;
}
}
OUTPUT:

CONCLUSION:
In this program we have learn how to displays information about whether
the file exists, whether the file is readable, whether the file is writable, the
type of file and the length of the file in bytes

DEPSTAR 51 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

30. Write a program to transfer data from one file to another file so that if the
destination file does not exist, it is created.
PROGRAM CODE:
import java.util.*;
import java.io.*;
public class FILE
{
public static void main(String args[]) throws IOException
{
FileInputStream in= null;
FileOutputStream ot=null;
try
{
in= new FileInputStream("input.txt");
ot= new FileOutputStream("ouput.txt");
int c;
while((c=in.read())!=-1)
{
ot.write(c);
}
}
finally
{
if (in != null) {
in.close();
}
if (ot != null) {
ot.close();
}
}
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
}

DEPSTAR 52 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

OUTPUT:

CONCLUSION:
In this program we have learn how we can transfer data from one file to
another file.

DEPSTAR 53 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

31. WAP to show use of character and byte stream.


PROGRAM CODE:
import java.util.*;
import java.io.*;
class File5
{
public static void main(String args[]) throws IOException
{
FileReader sourceI = null;
FileInputStream s1 = null;
FileOutputStream s2 = null;
try
{
sourceI =new FileReader("ouput.txt");
int temp;
while((temp=sourceI.read())!=-1)
{
System.out.print((char)temp);
}
}
finally
{
if(sourceI!=null)
sourceI.close();
}
try
{
s1 =new FileInputStream("ouput.txt");
s2=new FileOutputStream("output.txt");
int temp;
while((temp=s1.read())!=-1)
{
s2.write((byte)temp);
}
}
finally
{
if(s1!=null)
s1.close();
if(s2!=null)
DEPSTAR 54 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

s2.close();
}
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
}
OUTPUT:

CONCLUSION:
In this program we have learn the use of character and byte stream.

DEPSTAR 55 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

32. WAP to read console input and write them into a file. (BufferedReader
/BufferedWriter).

PROGRAM CODE:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.*;
class File6 {
public static void main(String[] args) throws IOException
{BufferedReader R= new BufferedReader InputStreamReader(System.in));
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
System.out.println("Console Input(type \"stop\"to exit):");
String inp = "";
do{ inp=R.readLine();
buffer.write(inp);
}while(!inp.equals("stop"));
buffer.close();
System.out.println("Success");
System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
}
}
OUTPUT:

CONCLUSION:
In this program we have learn how to read console input and write them into
a file using BufferedReader and BufferedWriter.

DEPSTAR 56 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

33. WAP implementing Wrapper class.

PROGRAM CODE:

class ValueOf {
void method(String[] args)
{
Integer I = Integer.valueOf("10");
System.out.println(I);
Double D = Double.valueOf("10.0");
System.out.println(D);
Boolean B = Boolean.valueOf("true");
System.out.println(B);
}
}
class XXXValue {
void method(String[] args)
{
Integer I = new Integer(130);
System.out.println(I.byteValue());
System.out.println(I.shortValue());
System.out.println(I.intValue());
System.out.println(I.longValue());
System.out.println(I.floatValue());
System.out.println(I.doubleValue());
}
}

class ToString {
void method(String[] args)
{
Integer I = new Integer(10);
String s = I.toString();
System.out.println(s);
}
}

class prac7 {
public static void main (String[] args) {
ValueOf vo=new ValueOf();
DEPSTAR 57 | P a g e
Java Programming [CE241] Enrolment No.:18DCS074

XXXValue xv=new XXXValue();


ToString ts=new ToString();

vo.method();
xv.method();
ts.method();
}
}

CONCLUSION:
We used Wrapper classes to add more functionalities to the primitive
datatype and also make them an object so they can be further used in
multithreading or in collection frameworks.

DEPSTAR 58 | P a g e