You are on page 1of 28

Achyut Krishna Sai

Achyut Krishna Sai


20CE120
Achyut Krishna Sai

Charotar University of Science and Technology [CHARUSAT]


Chandubhai S. Patel Institute of Technology [CSPIT]
U & P U. Patel Department of Computer Engineering
Practical List
Subject code : CE251 Semester : 3 Academic Year : 2021-22
Subject name : Java Programming

PART-I
Data Types, Variables, Arrays, Operators, Control Statements, String

1. Introduction to Object Oriented Concepts, comparison of Java with other object-oriented


programming languages. Introduction to JDK, JRE, JVM, java doc,
command line argument

Ans Introduction to Object Oriented Concepts: Object-oriented programming is a model that provides
different types of concepts, such as inheritance, abstraction, polymorphism, etc. These concepts aim
to implement real-world entities in programs. They create working methods and variables to reuse
them without compromising the security.

Comparison: The main difference between Java and any other programming language is the unique
method in which Java code is executed. Unlike compiled languages such as C++, Java is compiled
into bytecode which can run on any device with the Java Virtual Machine (JVM).

JDK: The Java Development Kit is an implementation of either one of the Java Platform, Standard
Edition, Java Platform, Enterprise Edition, or Java Platform, Micro Edition platforms released by
Oracle Corporation in the form of a binary product aimed at Java developers on Solaris, Linux,
macOS or Windows.

JRE: The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer's
operating system software and provides the class libraries and other resources that a specific Java
program needs to run The Java Virtual Machine, or JVM, executes live Java applications.

JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed. JVMs are available for many hardware and
software platforms.

JAVADOC: Javadoc is a documentation generator created by Sun Microsystems for the Java
language for generating API documentation in HTML format from Java source code. The HTML
format is used for adding the convenience of being able to hyperlink related documents together.

COMMAND LINE ARGUMENT: A command-line argument is an information that directly


follows the program's name on the command line when it is executed. To access the command-line
arguments inside a Java program is quite easy.

U & P U. Patel Department of Computer Engineering, CSPIT, CHARUSAT Page | 1


Achyut Krishna Sai

Achyut Krishna Sai

2. A typical mobile number in India is “+91-AA-BBB-CCCCC”. Where the first two digits (AA)
indicate a mobile system operator, the next three (BBB) denote the mobile switching code (MSC)
while the remaining five digits (CCCCC) are unique to the subscriber. Write an application that
takes a mobile number as an input from a user in above mentioned format and display code for
mobile system operator, mobile switching code and last 5 digits which are unique to subscriber.
Ex. For an input +91-94-999-65789, output should be:
Mobile system operator code is 94
MSC is 999
Unique code is 65789

Code import java.util.Scanner;

class Phn
{
Scanner scan=new Scanner(System.in);
String no,arrOfStr[];
void get()
{
System.out.println("Enter mobile no. in \"+91-AA-BBB-CCCCC\" format: ");
no=scan.next();
arrOfStr=no.split("-",4);
}
void show()
{
System.out.println("\nThe entered mobile number is +"+no);
System.out.println("Mobile system operator code : "+arrOfStr[1]+"\nMobile
switching code : "+arrOfStr[2] +"\nSubscriber's unique last 5 digits : "+arrOfStr[3]);
}
}
public class MobileNo
{
public static void main(String []args)
{
Phn obj=new PhoneNo();
obj.get();
obj.show();
}
}
Output
Achyut Krishna Sai

Achyut Krishna Sai

3. Given two non-negative int values, return true if they have the same first digit, such as with 72 and
75.
firstDigit(7, 71) → true
firstDigit(6, 17) → false
firstDigit(31, 311) → true

Code import java.util.Scanner;


class First1
{
int fd1,fd2;
Boolean firstDigit(int no1,int no2)
{
while(no1>=10)
{
no1=no1/10;
}
fd1=no1;
while(no2>=10)
{
no2/=10;
}
fd2=no2;
if(fd1==fd2)
{
return true;
}
else
{
return false;
}
}
}
class First0
{
public static void main(String[] args)
{
int no1,no2;
Scanner sc=new Scanner(System.in);
for(int i=1; i<=5; i++)
{
System.out.println("Enter 2 nos :");
no1=sc.nextInt();
no2=sc.nextInt();

First1 o1=new First1();


if(o1.firstDigit(no1,no2))
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
}
}
Achyut Krishna Sai

Achyut Krishna Sai

Output

4. The problem is to write a program that will grade multiple-choice tests. Assume there are eight
students and ten questions, and the answers are stored in a two-dimensional array. Each row records a
student’s answers to the questions, as shown in the following array. Students’ answers to the
Questions:
0123456789
Student 0 A B A C C D E E A D
Student 1 D B A B C A E E A D
Student 2 E D D A C B E E A D
Student 3 C B A E D C E E A D
Student 4 A B D C C D E E A D
Student 5 B B E C C D E E A D
Student 6 B B A C C D E E A D
Student 7 E B E C C D E E A D

The key is stored in a one-dimensional array:


Key to the Questions:
0123456789
Key D B D C C D A E A D
Your program grades the test and displays the result. It compares each student’s answers with the
key, counts the number of correct answers, and displays it.

Code class Student


{
String marks[][]= {{"A","B","C","E","D","A","E","A"},
{"A","C","D","D","A","A","B","E"},
{"E","C","D","A","E","A","E","B"},
{"A","C","D","A","A","A","B","A"},
{"A","C","D","A","A","B","B","C"},
{"E","C","D","A","E","A","E","B"},
{"E","C","D","A","E","A","E","E"},
{"E","C","D","A","A","A","E","B"},
{"A","C","D","A","A","A","E","B"},
{"E","C","D","A","A","B","E","C"}};

String key[]={"A","C","D","A","A","B","B","C"};
int count;
void check()
{
for(int i=0;i<10;i++)
Achyut Krishna Sai

Achyut Krishna Sai

{
count=0;
for(int j=0;j<8;j++)
{
if(marks[i][j]==key[j])
{
count++;
}
}
System.out.println("Score of student-"+(i+1)+" is "+count);
}
}
}
public class StudentQ {
public static void main(String[] args) {
Student d=new Student();
d.check();
}
}
Output

5. We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the
next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number
of blocks in such a triangle with the given number of rows.
triangle(0) →0
triangle(1) →1
triangle(2) →3

Code import java.util.Scanner;


import java.lang.String;

class recur{
int triangle(int num)
{
if(num==0) {
return 0;
}
else
return num + triangle(num-1);
}
}
public class Part1prog5
{
public static void main(String args[])
{
recur t = new recur();
Scanner sc = new Scanner(System.in);
Achyut Krishna Sai

Achyut Krishna Sai

System.out.println("enter the number");


int num = sc.nextInt();
System.out.println("total blocks = "+t.triangle(num));
}
}
Output

PART-II
Object Oriented Programming: Classes, Methods, Inheritance
1. Design a class named Cylinder containing following attributes and behavior.
One double data field named radius. The default value is 1.
One double data field named height. The default value is 1.
A no-argument constructor that creates a default Cylinder.
A Single argument constructor that creates a Cylinder with the specified radius.
Two argument constructor that creates a Cylinder with the specified radius and height.
A method named getArea() that returns area of the Cylinder.
Create a class TestCylinder and test and display result.

Code class Cylinder


{
double radius=1;
double height=1;
Cylinder()
{
}
Cylinder(double r)
{
radius=r;
}
Cylinder(double rad,double h)
{
radius=rad;
height=h;
}
double getArea()
{
double ar;
ar=(2*3.14*radius*height)+(2*3.14*radius*radius);
return ar;
}
}
public class TestCylinder {

public static void main(String[] args) {


Cylinder c=new Cylinder();
System.out.print("Area of cylinder with default values of radius and
height: "+c.getArea());
System.out.println();
Achyut Krishna Sai

Achyut Krishna Sai

Cylinder c2=new Cylinder(2);


System.out.print("Area of cylinder with default value of radius:
"+c2.getArea());
System.out.println();
Cylinder c3=new Cylinder(2.5,3);
System.out.print("Area of cylinder with specified values of radius and
height: "+c3.getArea());
System.out.println();
System.out.println();
System.out.print("Made by- Pranay Patel, id- 20C098");
}
}
Output

2. Design a class named Account that contains:


A private int data field named id for the account (default0).
A private double data field named balance for the account (default500₹).
A private double data field named annualInterestRate that 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, andannualInterestRate.
The accessor method for dateCreated.
A method named getMonthlyInterestRate() that returns the monthly interest rate.
A method named getMonthlyInterest() that returns the monthly interest.
A method named withdraw that withdraws a specified amount from the account.
A method named deposit that deposits a specified amount to the account.
Code class Account
{
private int id=0;
double balance=500,annualInterestRate=7,amount;
String dateCreated;
Account()
{
id=0;
balance=500;
annualInterestRate=7;
}
Account(int i,double bal)
{
id=i;
balance=bal;
}
void setdata(int i,double bal,double aInt,String dt)
{
Achyut Krishna Sai

Achyut Krishna Sai

id=i;
balance=bal;
annualInterestRate=aInt;
dateCreated=dt;
}
int getId()
{
return id;
}
double getBal()
{
return balance;
}
double getAnn()
{
return annualInterestRate;
}
double getMonthlyInterestRate()
{
return (annualInterestRate/100)/12;
}
double getMonthlyInterest()
{
return balance*((annualInterestRate/100)/12);
}
String getDt()
{
return dateCreated;
}
void withdraw(double amount)
{
balance-=amount;
if(balance>0)
System.out.println("Remaining balance after withdrawal of
Rs."+amount+" is Rs."+balance);
else
System.out.println("Withdrawal of Rs."+amount+" is not
possible!!");
}
void deposit(double amount)
{
balance+=amount;
System.out.println("Total balance after deposit of Rs."+amount+" is
Rs."+balance);
}
}

public class MyAccount


{
public static void main(String[] args) {
Account a1=new Account();
Account a2=new Account(123456,100000);

a2.setdata(1289031,1000000, 4.2, "12-5-2020");


System.out.println("Account Details:\n");
System.out.println("Balance :"+a2.getBal());
System.out.println("Annual Interest :"+a2.getAnn());
System.out.println("Monthly Interest Rate
:"+a2.getMonthlyInterestRate());
Achyut Krishna Sai

Achyut Krishna Sai

System.out.println("Monthly Interest :"+a2.getMonthlyInterest());


System.out.println("Account was created on "+a2.getDt());
a2.withdraw(12000);
a2.deposit(100000);
}
}
Output

3. 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 balance300₹]
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.
Code import java.lang.*;
import java.util.*;
class Account1
{
int balance;
String id;
Scanner sc;
Account1(String
i)
{
id=i;
balance=300;
sc=new Scanner(System.in);
}
void balance_inq()
{
System.out.println("Account id: "+id);
System.out.println("Account Balance: "+balance);
}
void withdraw()
{
int sub;
System.out.println("Enter the amount to withdraw: ");
Achyut Krishna Sai

Achyut Krishna Sai

sub=sc.nextInt();
if(balance-sub > 300) {
balance-=sub;
System.out.println("Current balance="+balance);}
else {
System.out.println("Cannot withdraw because minimum balance
Rs.300 is required!!");}
}
void deposit()
{
int add;
System.out.println("Enter the amount to be deposited: ");
add=sc.nextInt();
balance+=add;
System.out.println("Current balance="+balance);
}
void create(ArrayList arr)
{
String str;
System.out.print("Enter ID :- ");
str = sc.next();

Account1 ac = new Account1(str);


arr.add(ac);
System.out.println("Account was successfully created!!");
}
void delete(ArrayList arr)
{
String str;
Account1 ac = null;
System.out.print("Enter ID :- ");
str = sc.next();

Iterator itr = arr.iterator();


while(itr.hasNext())
{
Account1 a = (Account1) itr.next();
if(str.equals(a.id))
ac = a;
}

if(ac == null)
System.out.println("Account not found");
else
{
arr.remove(ac);
System.out.println("Account removed successfully");
}
}
void moneyTransfer(ArrayList arr)
{
int temp;
String id;
Scanner sc = new Scanner(System.in);
Account1 ac = null;

System.out.print("Enter ID to transfer :- ");


id = sc.next();
Achyut Krishna Sai

Achyut Krishna Sai

Iterator itr = arr.iterator();


while(itr.hasNext())
{
Account1 a = (Account1) itr.next();

if(id.equals(a.id))
ac = a;

if(ac == null)
System.out.println("Account not found");
else
{
System.out.print("Enter amount to transfer :- ");
temp = sc.nextInt();

if(temp > balance)


System.out.println("Not enough balane to transfer");
else
{
ac.balance = ac.balance + temp;
balance = balance - temp;
}
}
}

}
public class Prog_3
{
public static void main(String[] args)
{
int c=1,ch;
String i;
ArrayList<Account1>arr = new ArrayList<Account1>();
//Account1 a=new Account1(i);
Account1 ac ;
Account1 a = new Account1(null);

arr.add(new Account1("AC001"));
arr.add(new Account1("AC002"));
arr.add(new Account1("AC003"));
arr.add(new Account1("AC004"));
arr.add(new Account1("AC005"));
arr.add(new Account1("AC006"));
arr.add(new Account1("AC007"));
arr.add(new Account1("AC008"));
arr.add(new Account1("AC009"));
arr.add(new Account1("AC010"));
Scanner sc=new Scanner(System.in);
System.out.println("Enter any id fron AC001 to AC010: ");
i=sc.next();

Iterator itr = arr.iterator();


while(itr.hasNext())
{
a = (Account1) itr.next();
if(i.equals(a.id))
ac = a;
Achyut Krishna Sai

Achyut Krishna Sai

}
ac=a;
if(ac == null)
{
System.out.println("Invalid ID");
System.exit(0);
}
else
{

while(c!=0)
{
System.out.println("\nHow can I help you?: \n1.Balance
inquiry\n2.Withdraw Money[Maintain minimum balance Rs.3oo]\n3.Deposit Money\n4.Money
Transfer\n5.Create Account\n6.Deativate Account\n7.Exit.");
System.out.println("Enter your choice from above:");
ch=sc.nextInt();
switch(ch)
{
case 1:
a.balance_inq();
break;
case 2:
a.withdraw();
break;
case 3:
a.deposit();
break;
case 4:
a.moneyTransfer(arr);
break;
case 5:
a.c reate(arr);
break;
case 6:
a.d elete(arr);
break;
case 7:
System.out.println("Thanks for coming!!");
c=0;
break;
default:
System.out.println("Please enter the valid choice!");
}
}

}
}
}
Output
Achyut Krishna Sai

Achyut Krishna Sai

4. (Subclasses of Account) In Programming Exercise 2, the Account class was defined to model
a bank account. An account has the properties account number, balance, annual interest rate,
and date created, and methods to deposit and withdraw funds. Create two subclasses for
checking and saving accounts. A checking account has an overdraft limit, but a savings
account cannot be overdrawn. Write a test program that creates objects of Account,
SavingsAccount, and CheckingAccount and invokes their toString() methods.

Code class Account


{
private int id=0;
double balance=500,annualInterest=7,amount;
String dateCreated;
Account()
{
id=0;
balance=50000;
annualInterest=7;
}
Account(int i,double bal)
Achyut Krishna Sai

Achyut Krishna Sai

{
id=i;
balance=bal;
}
void setdata(int i,double bal,double aInt,String dt)
{
id=i;
balance=bal;
annualInterest=aInt;
dateCreated=dt;
}
int getId()
{
return id;
}
double getBal()
{
return balance;
}
double getAnn()
{
return annualInterest;
}
double getMonthlyInterestRate()
{
return (annualInterest/100)/12;
}
double getMonthlyInterest()
{
return balance*((annualInterest/100)/12);
}
String getDt()
{
return dateCreated;
}
void withdraw(double amount)
{
balance-=amount;
if(balance>0)
System.out.println("The balance left after withdrawal of Rs."+amount+"
is Rs."+balance);
else
System.out.println("Withdrawal of Rs."+amount+" is not
possible!!");
}
void deposit(double amount)
{
balance+=amount;
System.out.println("The balance left after deposit of Rs."+amount+" is
Rs."+balance);
}
}
class SavingAccount extends Account
{
SavingAccount(double a)
{
amount=a;
balance-=amount;
}
Achyut Krishna Sai

Achyut Krishna Sai

public String toString()


{
if(balance>=3000)
{
return "The balance left after withdrawal of Rs."+amount+" is Rs.
"+balance;
}
else
{
return "Beyond1 Over Draft Limit Not Possible!!\nMinimum balance
of Rs. 3000 is required.";
}
}
}
class CheckingAccount extends Account
{
CheckingAccount(double am)
{
amount = am;
balance-=amount;

}
public String toString()
{
System.out.println("Withdrawal Successful!!");
return "Now the balance left is Rs."+balance+" after the withdrawal of
Rs."+amount;
}
}
public class MyAccount1 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Account a1=new Account();
Account a2=new Account(123456,100000);

a2.setdata(1289031,1000000, 4.2, "12-5-2020");


System.out.println("Account Details:\n");
System.out.println("Balance :"+a2.getBal());
System.out.println("Annual Interest :"+a2.getAnn());
System.out.println("Monthly Interest Rate
:"+a2.getMonthlyInterestRate());
System.out.println("Monthly Interest :"+a2.getMonthlyInterest());
System.out.println("Account was created on "+a2.getDt());
a2.withdraw(12000);
a2.deposit(100000);
System.out.print("\n \n");
SavingAccount a=new SavingAccount(90);
CheckingAccount b=new CheckingAccount(100);

System.out.println("For Saving Account:\n");


System.out.println(a);
System.out.print("\n \n");
System.out.println("For Checking Account:\n");
System.out.println(b);
}
}
Achyut Krishna Sai

Achyut Krishna Sai

Output

5. Develop a Program that illustrate method overloading concept.


Code class Class1
{
int calc(int m,int n)
{
System.out.println(m+" + "+n+" =");
return (m+n);
}
float calc(int m,float n)
{
System.out.println(m+" - "+n+" =");
return (m-n);
}
float calc(float m,float n)
{
System.out.println(m+" * "+n+" =");
return m*n;
}
int calc(int a,int b,int c)
{
System.out.println(a+" + "+b+" + "+c+" =");
return a+b+c;
}
}
public class Prog_5 {
public static void main(String[] args)
{
Class1 c=new Class1();
System.out.println(c.calc(10,12));
System.out.println(c.calc(10,12.99f));
System.out.println(c.calc(10f,12.01f));
System.out.println(c.calc(10,12,20));
}
}
Achyut Krishna Sai

Achyut Krishna Sai

Output

PART-III
Package & Interface
1. Create an abstract class GeometricObject as the superclass for Circle and Rectangle.
GeometricObject models common features of geometric objects. Both Circle and Rectangle
contain the getArea() and getPerimeter() methods for computing the area and perimeter
of a circle and a rectangle. Since you can compute areas and perimeters for all geometric
objects, so define the getArea() and getPerimeter() methods in the GeometricObject class.
Give implementation in the specific type of geometric object. Create TestGeometricObject
class to display area and perimeter of Rectangle and Triangle, compare area of both and
display results. Design of all classes are given in the following UML diagram.

Code abstract class GeometricObject


{
abstract void draw();
abstract double getArea();
abstract double getPerimeter();
void display()
{
System.out.println("In abstract class..");
}
}
class Rectangle extends GeometricObject
{
void draw()
{
System.out.println("In rectangle");
}
double getArea()
{
int l=10;
int b=20;
return (l*b);
}
double getPerimeter()
{
int l=10;
int b=20;
return (2*(l+b));
}

}
class Circle extends GeometricObject
Achyut Krishna Sai

Achyut Krishna Sai

{
void draw()
{
System.out.println("In circle");
}
double getArea()
{
int r=7;
return (3.14*r*r);
}
double getPerimeter()
{
int r=7;
return (2*3.14*r);
}
}
class TestGeometricObject
{
public static void main(String args[])
{
GeometricObject s=new Circle();
//In real scenario, Object is provided through factory method
s.draw();
System.out.println("Area of circle "+s.getArea());
System.out.println("Perimeter of circle "+s.getPerimeter());
GeometricObject s2=new Rectangle();
s2.draw();
System.out.println("Area of rectanglee "+s2.getArea());
System.out.println("Perimeter of rectangle "+s2.getPerimeter());
}
}
Output

2. Write a program to create a default method in an interface IPrinter. Create an


interface IPrinter and IScanner. You can assume variables and methods for both interfaces.
Create a concrete class to implement both the interfaces. Create 5 objects of the class, store it in
Vector and display the result of the vector.

Code public interface Ip


{
void print();
void connect();
void on();
}
interface IScanner
{
void scan();
void scconnect();
}
class implementation implements Ip,IScanner
{
public void print()
Achyut Krishna Sai

Achyut Krishna Sai

{
System.out.println("In IPrinter ");
}
public void connect()
{
System.out.println("Connecting with pc ");
}
public void scan()
{
System.out.println("In IScanner ");
}
public void scconnect()
{
System.out.println("Displaying on screen ");
}

public class IPrinter


{
public static void main(String[] args)
{
implementation a= new implementation();

a.connect();
a.print();

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

a.scconnect();
a.scan();

System.out.println("");

Output

3. 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 implements P12. By using the object of the class invokes each of its method
and displays constant.

Code interface P
{
final int no1=1;
void dispP();
Achyut Krishna Sai

Achyut Krishna Sai

}
interface P1 extends P
{
final int no2=2;
void dispP1();
}
interface P2 extends P
{
final int no3=3;
void dispP2();
}
interface P12 extends P1,P2
{
final int no4=4;
void dispP12();
}
class imp implements P12
{
public void dispP()
{
System.out.println("Displaying P : "+no1);
}
public void dispP1()
{
System.out.println("Displaying P1 : "+no2);
}
public void dispP2()
{
System.out.println("Displaying P2 : "+no3);
}
public void dispP12()
{
System.out.println("Displaying P12 : "+no4);
}

}
class WAP
{
public static void main(String arg[])
{
imp i=new imp();
i.dispP();
i.dispP1();
i.dispP2();
i.dispP12();
}
}
Achyut Krishna Sai

Output

4. Develop a Program that illustrate method overriding concept.


Code class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Car extends Vehicle
{
void run() {System.out.println("It is a Car.");}
}
class Part3prac4 {
public static void main(String args[]){
Car obj = new Car();
obj.run();
}
}

Output

5. Write a java program which shows importing of classes from other user define packages.
Code Packages->Source Packages-> pack1 -> pack1.java
Packages->Source Packages-> packages->demo.java
Packages->Source Packages-> packages->pack2.java

PUBLIC STATIC VOID MAIN IS IN demo.java


Program pack1.java:
package pack1;
public class pack1 {
void defaultmethod()
{
System.out.println("Hello from pack1 default method");
}
public void method()
{
System.out.println("Hello from pack1 public method");
}
private void privatemethod()
{
System.out.println("Hello from pack1 private method");
}
protected void protectedmethod()
Achyut Krishna Sai

{
System.out.println("Hello from pack1 protected method");
}

}
Program demo.java:
package pakages;
import pack1.pack1;
import pakages.pack2;
public class demo {
void defaultmethod()
{
System.out.println("Hello from packages default method");
}
public void method()
{
System.out.println("Hello from packages public method");
}
private void privatemethod()
{
System.out.println("Hello from packages private method");
}
protected void protectedmethod()
{
System.out.println("Hello from packages protected method");
}
public static void main(String[] args) {
pack1 p = new pack1();
pack2 pa = new pack2();
demo pac = new demo();
p.method();
pa.defaultmethod();
pa.method();
pa.protectedmethod();
pac.defaultmethod();
pac.privatemethod();
pac.protectedmethod();
pac.method();
}

}
Program pack2.java:
package pakages;
public class pack2 {
void defaultmethod()
{
System.out.println("Hello from packages.pack2 default method");
}
public void method()
{
System.out.println("Hello from packages.pack2 public method");
}
private void privatemethod()
{
System.out.println("Hello from packages.pack2 private method");
}
protected void protectedmethod()
Achyut Krishna Sai

{
System.out.println("Hello from packages.pack2 protected method");
}
}
Output

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


Code IN PACKAGE PACK1

package pack1;

import java.util.Scanner;

public class cls1 {


Scanner sc=new Scanner(System.in);
int r;
public int fun() {
System.out.println("Enter value : ");
r=sc.nextInt();
return r;
}
}

IN PACKAGE PACK2

package pack2;
import pack1.*;
public class cls2 {

public static void main(String[] args) {


cls1 c = new cls1();
System.out.println("Entered value is "+c.fun());
}

}
Output

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


Achyut Krishna Sai

Code public interface inter


{
void fun() {}
}
class main implements inter
{
public void fun() {
System.out.print("How are you ? \n");
}
}
public class Part3prac7
{
public static void main(String args[]) {
main i = new main();
i.fun();
System.out.print("Hope you are doing fine...");
}
}
Output

PART-IV
Exception Handling
1 WAP to show the try - catch block to catch the different types of exception.

Program: package 20CE120;


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
class Division
{
float divide(int a, int b) throws ArithmeticException
{
return(a/b);
}
}
public class ExceptionDemo1
{
static int demoproc(String s) {
try {
if (s == null) {
throw new NullPointerException("String is null.");
} else {
return s.length();
}
} catch (NullPointerException e) {
System.out.println("NullPointerException Caught inside demoproc method...");
throw e; // rethrow the exception
}
}
public static void main(String[] args)
{
try
{
int a = 5/0;
Achyut Krishna Sai

System.out.println("Value of a = "+a);
}
catch(ArithmeticException e)
{
System.out.println("Exception = "+e);
}
finally
{
//finally block is executed compulsorily irrespective of the occurrence of an error
System.out.println("finally block executes ");
}
System.out.println("Rest of the code...");
try
{
int[] a = new int[5];
a[2] = a[10]/0+2; // In this line a[10] is evaluated first, so handle ArrayIndexOutOfBounds first and
then ArithmeticException... see below example
System.out.println("After exception occurs...");
}
catch(ArrayIndexOutOfBoundsException aioob)
{
System.out.println("Array index Out of Bounds..");
}
try {
int[] a = new int[5];

try {
a[2] = a[10] / 0 + 2;
} catch(ArrayIndexOutOfBoundsException aioe)
{
System.out.println("Access of invalid index in array - index out of range...");
}
catch(ArithmeticException ae)
{
System.out.println("Enter valid denominator..");
}finally {
System.out.println("Within Inner finally block.....");
}
} catch(Exception e)
{
System.out.println("Unexpected exception occured... :::"+e);
} finally {
System.out.println("Finally block executed.....");
}
System.out.println("After fially block .......");
try
{
Class c = Class.forName("p1.ExceptionDemo3");
System.out.println("2nd line");
}
catch(ClassNotFoundException e)
{
System.out.println("Class not found..");
}
try
{
FileInputStream fis = new FileInputStream("C:\\Arithmetic.java");
DataInputStream ds = new DataInputStream(fis);
}
catch(FileNotFoundException f)
{
System.out.println("File not found..");
Achyut Krishna Sai

}
char c;
String s = null;
try
{
int n = s.length();
}
catch(NullPointerException e)
{
System.out.println(e);
}int n1,n2;
float ans;
Scanner ss = new Scanner(System.in);
System.out.println("\nEnter number 1 :");
n1 = ss.nextInt();
System.out.println("\nEnter number 2 :");
n2 = ss.nextInt();
Division d = new Division();
try
{ ans = d.divide(n1, n2);
System.out.println("Ans = "+ans);
}
catch(ArithmeticException ae)
{ System.out.println("Denominator cant be zero."); // Write User-friendly message here}
try {
String sss = null;
int len = demoproc(sss);
System.out.println("Lenght of the String is = " + len);
} catch (NullPointerException e) {
System.out.println("NullPointerException is caught in caller method if callee method not able to handle it.. "
+ e);
} } }
OUTPUT

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

Program: class ThrowDemo {


static int demoproc(String s) throws NullPointerException{
try {
if (s == null) {
throw new NullPointerException("String is null.");
} else {
return s.length();
}
} catch (NullPointerException e) {
System.out.println("NullPointerException Caught inside demoproc method...");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
String s = null;
int len = demoproc(s);
Achyut Krishna Sai

System.out.println("Lenght of the String is = " + len);


} catch (NullPointerException e) {
System.out.println("NullPointerException is caught in caller method if callee method not able to handle it.. " +
e);
}
}
}
OUTPUT

3 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 ‘Arithmetic Exception’ and ‘Array Index
Out of Bounds Exception’. Display a message in the ‘finally’ block.

Program: package 20CE120;


public class JavaApplication34 {
public static void main(String[] args) {
try
{ int a = 5/0;
System.out.println("Value of a = "+a); }
catch(ArithmeticException e)
{ System.out.println("Exception = "+e); }
try
{ int[] a = new int[5];
a[2] = a[10]/0+2; // In this line a[10] is evaluated first, so handle ArrayIndexOutOfBounds first and
then ArithmeticException... see below example
System.out.println("After exception occurs..."); }
catch(ArrayIndexOutOfBoundsException a)
{ System.out.println("Array index Out of Bounds.."); }

finally
{
//finally block is executed compulsorily irrespective of the occurrence of an error
System.out.println("finally block executes after arithmetic exception occured and array out of bound
occured");
}
}
}
Achyut Krishna Sai

OUTPUT

You might also like