20CE120 - CE251 Java Practical Part I, II - III, IV
20CE120 - CE251 Java Practical Part I, II - III, IV
20CE120 - CE251 Java Practical Part I, II - III, IV
PART-I
Data Types, Variables, Arrays, Operators, Control Statements, String
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.
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
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
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
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
String key[]={"A","C","D","A","A","B","B","C"};
int count;
void check()
{
for(int i=0;i<10;i++)
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
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
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.
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);
}
}
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
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();
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;
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();
}
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();
}
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
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.
{
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
}
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 {
Output
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.
}
class Circle extends GeometricObject
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
{
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 ");
}
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
}
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
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
{
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
package pack1;
import java.util.Scanner;
IN PACKAGE PACK2
package pack2;
import pack1.*;
public class cls2 {
}
Output
PART-IV
Exception Handling
1 WAP to show the try - catch block to catch the different types of exception.
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.
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.
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