0% found this document useful (0 votes)
21 views32 pages

Final - Basics of Java Lab Manual (BPLCK205C)

The document is a laboratory manual for the Basics of Java course at H.K.E. Society’s S.L.N. College of Engineering, detailing the vision, mission, and program outcomes of the Computer Science & Engineering department. It includes a list of programming experiments for students to complete, along with specific Java programming tasks and examples. The manual also outlines the continuous internal evaluation (CIE) process for assessing student performance in laboratory work.

Uploaded by

bbharthi476
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views32 pages

Final - Basics of Java Lab Manual (BPLCK205C)

The document is a laboratory manual for the Basics of Java course at H.K.E. Society’s S.L.N. College of Engineering, detailing the vision, mission, and program outcomes of the Computer Science & Engineering department. It includes a list of programming experiments for students to complete, along with specific Java programming tasks and examples. The manual also outlines the continuous internal evaluation (CIE) process for assessing student performance in laboratory work.

Uploaded by

bbharthi476
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

2022-23

H
Department of Computer Science & Engineering
.
H.K.E. Society’s S.L.N. College of Engineering
(Affiliated to VTU - Belagavi, Approved by AICTE – New Delhi, Accredited by NAAC)
Yeramarus Camp, Raichur – 584135

(Integrated Component)
Basics of Java Laboratory Manual
(BPLCK205C)
(CBCS Scheme)

Prepared by: Prof. Suresh Patel


Department of Computer Science & Engineering
H.K.E. Society’s S.L.N. College of Engineering
(Affiliated to VTU - Belagavi, Approved by AICTE – New Delhi, Accredited by NAAC)
Yeramarus camp, Raichur – 584135

VISION

The Department of Computer Science & Engineering


Nurtures young engineers with technical knowledge
and to be responsible in societal life with leadership
and ethical qualities for life-long learning.

MISSION
 To provide young computing aspirants with
best practices in teaching-learning with
highly experienced faculty
 To team up with industries and provide
experience on latest tools to excel in
promising technologies.
 To prepare students with required
fundamentals practical exposure, social and
professional morals
Programme Outcomes (POs)
PO1: Apply knowledge of computing fundamentals, computing
specialization, mathematics and domain knowledge to provide IT
solutions.
PO2: Identify, analyze and solve IT problems using fundamental
principles of mathematics and computing sciences.
PO3: Design, Develop and evaluate software solutions to meet societal
and environmental concerns.
PO4: Conduct investigations of complex problems using research based
knowledge and methods to provide valid conclusions.
PO5: Select and apply appropriate techniques and modern tools for
complex computing activities.
PO6: Understand professional ethics, cyber regulations and
responsibilities.
PO7: Involve in life-long learning for continual development as an IT
professional.
PO8: Apply and demonstrate computing and management principles to
manage projects in multidisciplinary environments by involving in
different roles
PO9: Comprehend& write effective reports and make quality
presentations.
PO10: Understand and assess the impact of IT solutions on socio- environmental
Issues.
PO11: Work collaboratively as a member or leader in multidisciplinary
teams.
PO12: Identify potential business opportunities and innovate to create
value to the society and seize that opportunity.
CONTENTS
List of problems for which student should develop program and execute in the Laboratory.
Exp. No Title Of the Experiment
Write a JAVA program that prints all real solutions to the quadratic equation
1
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.

2 Write a JAVA program for multiplication of two arrays.

Demonstrate the following operations and sign extension with Java programs
3
(i) << (ii) >> (iii) >>>

Write a JAVA program to sort list of elements in ascending and descending


4
order
Create a JAVA class called Student with the following details as variables within
it.
USN
NAME
5 BRANCH
PHONE
PERCENTAGE
Write a JAVA program to create n Student objects and print the USN, Name,
Branch, Phone, and percentage of these objects with suitable headings.
Write a JAVA program demonstrating Method overloading and Constructor
6
overloading.
Design a super class called Staff with details as StaffId, Name, Phone, Salary.
Extend this class by writing three subclasses namely Teaching (domain,
7
publications), Technical (skills), and Contract (period). Write a JAVA program
to read and display at least 3 staff objects of all three categories.

8 Demonstrate dynamic dispatch using abstract class in JAVA.

Create two packages P1 and P2. In package P1, create class A, class B inherited
from A, class C . In package P2, create class D inherited from class A in package
9
P1 and class E. Demonstrate working of access modifiers (private, public,
protected, default) in all these classes using JAVA.
Write a JAVA program to read two integers a and b. Compute a/b and print,
10 when b is not zero. Raise an exception when b is equal to zero. Also
demonstrate working of ArrayIndexOutOfBoundException.

CIE for the practical component of the IC:


1. On completion of every experiment/program in the laboratory, the students
shall be evaluated and marks shall be awarded on the same day. The 15 marks
are for conducting the experiment and preparation of the laboratory record,
the other 05 marks shall be for the test conducted at the end of the semester.
2. The CIE marks awarded in the case of the Practical component shall be based
on the continuous evaluation of the laboratory report. Each experiment report
can be evaluated for 10 marks. Marks of all experiments’ write-ups are added
and scaled down to 15 marks.
3. The laboratory test (duration 03 hours) at the end of the 15th week of the
semester / after completion of all the experiments (whichever is early) shall be
conducted for 50 marks and scaled down to 05 marks.
4. Scaled-down marks of write-up evaluations and tests added will be CIE marks
for the laboratory component of IC for 20 marks.
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-1:

Aim: Introduce the java fundamentals, data types, operators in java.

Program: Write a java program that prints all real solutions to the quadratic
equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula.

import java.io.*;
import java.util.*;
class Imaginary
{
public static void main(String ar[])
{
int a,b,c,d;
Scanner s=new Scanner(System.in);
System.out.print("The Quadratic Equation is of the form ax2+bx+c=0. \n”);
System.out.print("a = "+"\n");
a=s.nextInt();
System.out.print("b = "+"\n");
b=s.nextInt();
System.out.print("c= "+"\n");
c=s.nextInt();
System.out.println("The quadratic equation you entered is
"+a+"+x2+"+b+"+x+"+c+"=0");
System.out.print("real and imaginary roots are");
d=(b*b)-4*(a*c);
if(d>0)
{
System.out.println("Real and distinct");
double rt1=(-b+Math.sqrt(d))/(2*a);
double rt2=(-b-Math.sqrt(d))/(2*a);
System.out.print("Roots are "+rt1 +" "+rt2);
}
else if(d==0)
{
System.out.println("Real and equal");
double rt1=(-b)/(2*a);
double rt2=(-b)/(2*a);
System.out.print("Roots are "+rt1 +" "+rt2);
}
else if(d<0)
{
System.out.println("Imaginary");
}
}
}

Suresh Patel Page 1


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Output :

The Quadratic Equation is of the form ax2+bx+c=0.


Please enter values
a=1
b=2
c=1
The quadratic equation you entered is 1×2+2x+1=0
Its roots are Real and Equal
Roots are -1.0 -1.0

Suresh Patel Page 2


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-2:

Aim: Introduce the java fundamentals, operators, looping and arrays in java.

Method-1: Write a JAVA program for multiplication of two arrays.

import java.io.*;
import java.util.Scanner;
public class matrixmul1{
public static void main(String args[]){

Scanner in=new Scanner(System.in);


System.out.println("Enter the order of the matrix-A (M*N)");
System.out.println("Enter the value of M");
int m=in.nextInt();
System.out.println("Enter the value of N");
int n=in.nextInt();
int a[][]=new int[m][n];
System.out.println("Enter the elements of the Matrix-A:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.println("The elements of the Matrix-A are:");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("Enter the order of the matrix-B (P*Q)");
System.out.println("Enter the value of P");
int p=in.nextInt();
System.out.println("Enter the value of Q");
int q=in.nextInt();
int b[][]=new int[p][q];
System.out.println("Enter the elements of the Matrix-B:");
for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
b[i][j]=in.nextInt();
}
}
System.out.println("The elements of the Matrix-B are:");
Suresh Patel Page 3
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

for(int i=0;i<p;i++)
{
for(int j=0;j<q;j++)
{
System.out.print(b[i][j]+" ");
}
System.out.println(" ");
}

int c[][]=new int[n][p];


if(n!=p)
{
System.out.println("Matrix Multiplication not possible");
}
else
{

for(int i=0;i<m;i++){
for(int j=0;j<q;j++){
c[i][j]=0;
for(int k=0;k<p;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
}//end of j loop
System.out.println();//new line
}
System.out.println("The Resultant Matrix-C is:");
for(int i=0;i<m;i++)
{
for(int j=0;j<q;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println(" ");
}
}
}
}

Output:
Enter the order of the matrix-A (M*N)
Enter the value of M
2
Enter the value of N
3

Suresh Patel Page 4


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Enter the elements of the Matrix-A:


123
456
The elements of the Matrix-A are:
123
456
Enter the order of the matrix-B (P*Q)
Enter the value of P
3
Enter the value of Q
2
Enter the elements of the Matrix-B:
12
34
56
The elements of the Matrix-B are:
12
34
56
The Resultant Matrix-C is:
22 28
49 64

Suresh Patel Page 5


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Method-2: Write a JAVA program for multiplication of two arrays.

public class MatrixMultiplicationExample{


public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3]; //3 rows and 3 columns
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing
}//end of j loop
System.out.println();//new line
}
}
}

Output:

6 6 6
12 12 12
18 18 18

Suresh Patel Page 6


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-3:

Aim: Demonstrate the use of bitwise operators in java.

Program: Demonstrate the following operations and sign extension with Java
programs (i) << (ii) >> (iii) >>>

import java.util.Scanner;

class bitwiseop
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the number:");
int num = in.nextInt();
while(true)
{
System.out.println("\nEnter 1: << operator 2: >> operator 3: >>> operator
\n");
int sy = in.nextInt();
int output;
switch(sy)
{
case 1:
output = num << 2;
System.out.println("\nOutput after bitwise left shift operation for

"+num+"="+output);
break;

case 2:
output = num >> 2;
System.out.println("\nOutput after bitwise right shift operation for

"+num+"="+output);
break;

case 3:
output = num >>> 2;
System.out.println("\nOutput after bitwise Unsigned Right Shift for

"+num+"="+output);
break;

default:
System.out.println("\nYou have entered wrong operator");
return;
}
}
Suresh Patel Page 7
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

}
}

Output:

Enter the number:4


Enter 1: << operator 2: >> operator 3: >>> operator

Output after bitwise left shift operation for 4=16


Enter 1: << operator 2: >> operator 3: >>> operator

Output after bitwise right shift operation for 4=1


Enter 1: << operator 2: >> operator 3: >>> operator

Output after bitwise Unsigned Right Shift for 4=1


Enter 1: << operator 2: >> operator 3: >>> operator

You have entered wrong operator

Suresh Patel Page 8


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-4:

Aim: Demonstrate of looping constructs & arrays in java.

Program: Write a JAVA program to sort list of elements in ascending and


descending
order

import java.util.Scanner;

class sorting
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] a = new int[5];
int i, j, temp;
System.out.println("Please Enter 5 elements in the Array");
for (i = 0; i < 5; i++)
{
a[i] = in.nextInt();
}

for (i = 0; i < 5; i++)


{
for (j = i + 1; j < 5; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}

System.out.println("Sorted Array in Increasing Order:-");


for (j = 0; j < 5; j++)
{
System.out.println(a[j]);
}
for (i = 0; i < 5; i++)
{
for (j = i + 1; j < 5; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
Suresh Patel Page 9
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

}
}
}

System.out.println("Sorted Array in Decreasing Order:-");


for (j = 0; j < 5; j++)
{
System.out.println(a[j]);
}
}
}

Output:

Please Enter 5 elements in the Array


2
10
1
-22
56

Sorted Array in Increasing Order:-


-22
1
2
10
56

Sorted Array in Decreasing Order:-


56
10
2
1
-22

Suresh Patel Page 10


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-5: (Week-3)

Aim: Demonstrating creation of java classes, objects, constructors, declaration


and initialization of variables.

Program: Create a Java class called Student with the following details as variables
within it: USN, Name, Branch, Phone. Write a Java program to create n Student
objects and print the USN, Name, Branch, and Phone of these objects with suitable
headings.

import java.util.Scanner;
public class student {
String USN;
String Name;
String branch;
String phone;

void insertRecord(String reg, String name, String br, String ph)


{
USN=reg;
Name=name;
branch=br;
phone=ph;
}

void displayRecord()
{
System.out.println(USN+" "+Name+" "+branch+" "+phone);
}

public static void main(String args[]){


student s[]=new student [100];
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of students");
int n=sc.nextInt();
for(int i=0; i<n; i++)
s[i]=new student();
for(int k=0; k<n; k++)
{
System.out.println("enter the usn, name, programme, phone");
String USN=sc.next();
String Name=sc.next();
String branch=sc.next();
String phone=sc.next();
s[k].insertRecord(USN, Name, branch, phone);
}
for(int k=0; k<n;k++)
{
System.out.println("usn, name, programme, phone");
s[k].displayRecord();
Suresh Patel Page 11
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

}
}
}

Output:

enter the number of students


2
enter the usn, name, programme, phone
3SL20CS001 ABC CSE 123456

enter the usn, name, programme, phone


3SL20EC001 XYZ ECE 987654

usn, name, programme, phone


3SL20CS001 ABC CSE 123456

usn, name, programme, phone


3SL20EC001 XYZ ECE 987654

Practice Programs:

Aim: Discuss the various Decision-making statements, loop constructs in java

Program:
A. Write a program to check prime number
B.Write a program for Arithmetic calculator using switch case menu

A) Write a program to check prime number

import java.util.Scanner;

public class prime


{
public static void main(String[] args)
{
int n, i, count=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number: \n");
n = s.nextInt();
for(i=2; i<n; i++)
{
if(n%i == 0)
{
count++;
break;
}
Suresh Patel Page 12
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

if(count==0)
System.out.println(n + " is a Prime Number.");
else
System.out.println(n + " is not a Prime Number.");
}
}

Output:

Enter a Number:
11
11 is a Prime Number.

Enter a Number:
10
10 is not a Prime Number.

B)Write a program for Arithmetic calculator using switch case menu

import java.util.Scanner;

class calc {

public static void main(String[] args) {

double num1, num2;


Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
scanner.close();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;

case '-':
output = num1 - num2;
break;

Suresh Patel Page 13


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

case '*':
output = num1 * num2;
break;

case '/':
output = num1 / num2;
break;

default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+output);
}
}

Output:
Enter first number:5
Enter second number:2
Enter an operator (+, -, *, /): +
5.0 + 2.0: 7.0

Suresh Patel Page 14


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-6:

Aim: Introduce concepts of method overloading, constructor overloading,


overriding

Program: Write a java program demonstrating Method overloading and


Constructor overloading.

// Java program to illustrate Constructor Overloading


Import java.util.Scanner;
class Box
{
double width, height, depth;

Box(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}

Box()
{
width = height = depth = 0;
}

Box(double len)
{
width = height = depth = len;
}

double volume()
{
return width * height * depth;
}
}

class Sum {

int sum(int x, int y)


{
return (x + y);
}

int sum(int x, int y, int z)


{
return (x + y + z);
}

Suresh Patel Page 15


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

double sum(double x, double y)


{
return (x + y);
}
}

public class Test


{
public static void main(String args[])
{
while(true)
{
System.out.println(" Enter 1: Constructor Overloading Program \n
2: Method Overloading Program”);
Scanner sc=new Scanner(System.in);
System.out.println("Enter your choice:\n");
int ch=sc.nextInt();
switch(ch)
{
case 1:
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
break;
case 2:
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
break;
case 3: System.out.println(" Invalid Input!!! input again\n");
}
}
}
}

Suresh Patel Page 16


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Output:

Enter 1: Constructor Overloading Program


2: Method Overloading Program

Enter your choice:


3

Invalid Input!!! input again

Enter 1: Constructor Overloading Program


2: Method Overloading Program

Enter your choice:


1

Volume of mybox1 is 3000.0


Volume of mybox2 is 0.0
Volume of mycube is 343.0

Enter 1: Constructor Overloading Program


2: Method Overloading Program

Enter your choice:


2

30
60
31.0

Enter 1: Constructor Overloading Program


2: Method Overloading Program

Enter your choice:

Suresh Patel Page 17


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-7:

Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism

Program: Design a super class called Staff with details as StaffId, Name, Phone,
Salary. Extend this class by writing three subclasses namely Teaching (domain,
publications), Technical (skills), and Contract (period). Write a Java program to
read and display at least 3 staff objects of all three categories.

import java.util.Scanner;

class Astaff {
String StaffID, Name, Phone, Salary;
void read(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter StaffID");
StaffID = sc.nextLine();
System.out.println("Enter Name");
Name = sc.nextLine();
System.out.println("Enter Phone");
Phone = sc.nextLine();
System.out.println("Enter Salary");
Salary = sc.nextLine();
}

void disp(){
System.out.println("Details are");
System.out.println("StaffID:"+StaffID);
System.out.println("Name:"+Name);
System.out.println("Phone:"+Phone);
System.out.println("Salary:"+Salary);
}
}

class ATeaching extends Astaff {


String Domain, Publications;
void read1(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter Domain");
Domain = sc.nextLine();
System.out.println("Enter Publications");
Publications = sc.nextLine();
}

void disp1(){
System.out.println("Domain:"+Domain);
System.out.println("Publications:"+Publications);
}
}

Suresh Patel Page 18


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

class ATechnical extends Astaff {


String skills;
void read2(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter skills");
skills = sc.nextLine();
}

void disp2(){
System.out.println("skills:"+skills);
}
}

class A Contract extends Astaff {


String period;
void read3(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter period");
period = sc.nextLine();
}

void disp3(){
System.out.println("period:"+period);
}
}

class pgm2 {
public static void main(String []args){
Scanner sc=new Scanner (System.in);
System.out.println("Enter the number of staff\n");
int n=sc.nextInt();
ATeaching ob[]= new ATeaching [10];
System.out.println("Enter Teaching staff details\n");
for(int i=0; i<n; i++)
ob[i]=new ATeaching();
for(int i=0; i<n;i++)
{
ob[i].read();
ob[i].read1();
System.out.println("Teaching Staff details are:\n");
ob[i].disp();
ob[i].disp1();
}

ATechnical ob1[]= new ATechnical [10];


System.out.println("Enter Technical staff details\n");
for(int i=0; i<n; i++)
ob1[i]=new ATechnical();
for(int i=0;i<n;i++)
{
Suresh Patel Page 19
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

ob1[i].read();
ob1[i].read2();
System.out.println("Technical Staff details are:\n");
ob1[i].disp();
ob1[i].disp2();
}

AContract ob2[]= new AContract[10];


System.out.println("Enter Contract staff details\n");

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


ob2[i]=new AContract();
for(int i=0;i<n;i++)
{
ob2[i].read();
ob2[i].read3();
System.out.println("Contract Staff details are:\n");
ob2[i].disp();
ob2[i].disp3();
}
}
}

Output:

Run-1:

Enter the number of staff

1
Enter Teaching staff details

Enter StaffID
1
Enter Name
ABC
Enter Phone
123456
Enter Salary
25000
Enter Domain
CSE
Enter Publications
Pristine

Teaching staff details are:

Details are
StaffID:1
Suresh Patel Page 20
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Name:ABC
Phone:123456
Salary:25000
Domain:CSE
Publications:Pritine

Enter Technical staff details


Enter StaffID
2
Enter Name
XYZ
Enter Phone
874444
Enter Salary
12000
Enter skills
java

Techinical staff details are:


Details are
StaffID:2
Name:XYZ
Phone:874444
Salary:12000
skills:java

Enter Contract staff details


Enter StaffID
3
Enter Name
ttt
Enter Phone
4664646
Enter Salary
10000
Enter period
1

Contract staff details are:


Details are
StaffID:3
Name:ttt
Phone:4664646
Salary:10000
period:1

Suresh Patel Page 21


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-8:

Aim: Demonstrate the concept of abstract classes & polymorphism

Program: Demonstrate dynamic dispatch using abstract class in JAVA.

(Dynamic Method Dispatch in Java is the process by which a call to an overridden


method is resolved at runtime (during the code execution). The concept of
method overriding is the way to attain runtime polymorphism in Java. During the
code execution, JVM decides which implementation of the same method should be
called).

import java.util.Scanner;
/* Program is used for simple method overriding example with dynamic method
dispatch.*/

class stude
{
public void show()
{
System.out.println("Student details.");
}
}

public class colstudent extends Student


{
public void show()
{
System.out.println("College Student details.");
}

//main method
public static void main(String args[]){
//Super class can contain subclass object.
stude obj = new colstudent();

//method call resolved at runtime


obj.show();
}
}

Ouput:

College Student details.


School Student details.

Suresh Patel Page 22


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-9:

Aim: Demonstrate the concept of packages & Access Specifiers.

Program: Create two packages P1 and P2. In package P1, create class A, class B
inherited from A, class C . In package P2, create class D inherited from class A in
package P1 and class E. Demonstrate working of access modifiers (private, public,
protected, default) in all these classes using JAVA.

//Method-1: default access specifiers for display method


A.java:

package demopackage;

// Class A
public class A
{
void display()
{
System.out.println("Hello");
}
}

B.java:

package demopackage;
import demopackage.*; // importing all classes in package p1

// Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

Output:

Hello

Suresh Patel Page 23


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

//Method2: Private access specifiers for display method


A.java:

package demopackage;

// Class A
public class A
{
private void display()
{
System.out.println("Hello");
}
}

B.java:

package demopackage;
import demopackage.*; // importing all classes in package p1

// Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

Output:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -


Erroneous sym type: demopackage.B.display at demopackage.B.main(B.java:12)

//Method3: Private access specifiers for display method


A.java:

package demopackage;

// Class A
public class A
{
protected void display()
{
System.out.println("Hello");
}
}
Suresh Patel Page 24
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

B.java:

package demopackage;
import demopackage.*; // importing all classes in package p1

// Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}

Output:

Hello

Suresh Patel Page 25


Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

Program-10:

Aim: Demonstrate the concept of Exceptions along with handling mechanism.

Program: Write a JAVA program to read two integers a and b. Compute a/b and
print, when b is not zero. Raise an exception when b is equal to zero. Also
demonstrate working of ArrayIndexOutOfBoundException.

import java.util.Scanner;
class pgm10
{
public static void main(String[ ] args)
{
int a, b, result;
Scanner in =new Scanner(System.in);
while(true)
{
System.out.println("\nEnter 1: Divide by Zero 2: Array index out of bound 3:
Exit \n");
int sy = in.nextInt();
switch(sy)
{
case 1:
System.out.println("Divide by Zero");
System.out.println("Input two integers");
System.out.println("Enter the Value of A");
a=in.nextInt();
System.out.println("Enter the Value of B");
b=in.nextInt();
try
{
result=a/b;
System.out.println("Result="+result);
}

catch(ArithmeticException e)
{
System.out.println("exception caught: Divide by zero error"+e);
}
break;
case 2:
int arr[]=new int[5];
try
{
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
Suresh Patel Page 26
Basics of Java Programming Integrated Laboratory Manual [BPLCK205C]

System.out.println("The Elements of the array are");


for(int i=0;i<=arr.length; i++)
{
System.out.println(arr[i]);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("exception caught: Array Index Out of Bound error"+e);
}

break;
default:
System.out.println("\nYou have entered wrong operator");
return;
}
}
}
}

Output:

Enter 1: Divide by Zero 2: Array index out of bound 3: Exit


1
Divide by Zero
Input two integers
Enter the Value of A
5
Enter the Value of B
0
exception caught: Divide by zero errorjava.lang.ArithmeticException: / by zero

Enter 1: Divide by Zero 2: Array index out of bound 3: Exit


2
The Elements of the array are
10
20
30
40
50
exception caught: Array Index Out of Bound
errorjava.lang.ArrayIndexOutOfBoundsException: 5

Enter 1: Divide by Zero 2: Array index out of bound 3: Exit


3
You have entered wrong operator

Suresh Patel Page 27

You might also like