0% found this document useful (0 votes)
8 views

R23-Java Lab Exercise

This document is a lab manual for Object Oriented Programming through Java, intended for II Year B.Tech. students. It outlines the vision and mission of the institution and the CAI department, along with program educational objectives, outcomes, and specific outcomes related to AI and data science. The manual includes course objectives, a list of lab exercises, installation instructions for Java software, and guidelines for lab conduct.

Uploaded by

narayanababu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

R23-Java Lab Exercise

This document is a lab manual for Object Oriented Programming through Java, intended for II Year B.Tech. students. It outlines the vision and mission of the institution and the CAI department, along with program educational objectives, outcomes, and specific outcomes related to AI and data science. The manual includes course objectives, a list of lab exercises, installation instructions for Java software, and guidelines for lab conduct.

Uploaded by

narayanababu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

NB

Object Oriented Programming through Java


Lab Manual

Subject Code : 23A05303P


Regulations : R23

Class : II Year B.Tech., - I Semester


(Common to CAI & CSM)

Compiled by:
Dr. B. Narayana Babu
Professor, Department of CAI

Department of CAI
SIDDARTHA EDUCATIONAL ACADEMY GROUP OF INSTITUTIONS
Approved by AICTE, New Delhi & Affiliated to JNTUA, Ananthapuramu, AP.
Near C. Gollapalli, Tirupati – 517 505, Andhra Pradesh

SEGAI - Tirupati Page 1


NB

VISION AND MISSION OF THE INSTITUTION


Vision
To create an advanced centre of professional learning of international standing where pursuit of knowledge
and excellence shall reign supreme, unfettered by the barriers of nationality, language, cultural plurality
and religion.

Mission
Imparting quality value based education of international standard and imbibing skill for solving real life
problems. Creating leadership qualities with perspective futuristic vision. Instilling habit of continual
learning.

VISION AND MISSION OF CAI DEPARTMENT


Vision
To Achieve excellent standards of quality-education by using the latest tools, nurturing collaborative
culture and disseminating customer oriented innovations to relevant areas of academia and industry
towards serving the greater cause of society.

Mission
 To develop professionals who are skilled in the area of Artificial Intelligence and Data Science.
 To impart quality and value based education and contribute towards the innovation of computing,
expert system, Data Science to raise satisfaction level of all stakeholders.
 Our effort is to apply new advancements in high performance computing hardware and software.

SEGAI - Tirupati Page 2


NB

Program Educational Objectives (PEOs):

A graduate of the Computer Science and Engineering(AI) Program should:

Program Educational Objective 1: (PEO1)


To Formulate, analyze and solve Engineering problems with strong foundation in Mathematical,
Scientific, Engineering fundamentals and modern computing practices through advanced
curriculum.

Program Educational Objective 2: (PEO2)


Analyze the requirements, realize the technical specification and design the Engineering
solutions by applying artificial intelligence theory and principles.

Program Educational Objective 3: (PEO3)


Demonstrate technical skills, competency in AI and promote collaborative learning and team work
spirit through multi -disciplinary projects and diverse professional activities

Program Educational Objective 4: (PEO4)


Equip the graduates with strong knowledge, competence and soft skills that allows them to
contribute ethically to the needs of society and accomplish sustainable progress in the emerging
computing technologies through life-long learning

SEGAI - Tirupati Page 3


NB

Program Outcomes (POs):

PO1 Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
PO4 Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual
knowledge to assess Societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able
to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
PO11 Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these
to one's own work, as a member and leader in a team, to manage projects and
in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context
of technological change.

SEGAI - Tirupati Page 4


NB

Program Specific Outcomes (PSOs):

PSO1 Ability to analyze and apply the knowledge of human cognition, Artificial Intelligence,
Machine Learning and data engineering in terms of real world problems to meet the
challenges of the future.
PSO2 Ability to develop computational knowledge and project development skills using
innovative tools and techniques to solve problems in the areas related to Deep Learning,
Machine learning, Artificial Intelligence.
PSO3 Ability to lead a product development company/team and use the acquired knowledge to
identify real-world research problems.

Course Objectives:

• Practice object-oriented programming in the Java programming language


• implement Classes, Objects, Methods, Inheritance, Exception, Runtime
Polymorphism, User defined Exception handling mechanism
• Illustrate inheritance, Exception handling mechanism, JDBC connectivity.
• Construct Threads, Event Handling, implement packages, Java FX GUI.

Course Outcomes (CO):

CO1 Demonstrate a solid understanding of Java syntax, including data types,


control structures, methods, classes, objects, inheritance, polymorphism, and
exception handling. (L2)
CO2 Apply fundamental OOP principles such as encapsulation, inheritance,
polymorphism, and abstraction to solve programming problems effectively.
(L3)
CO3 Familiar with commonly used Java libraries and APIs, including the
Collections Framework, Java I/O, JDBC, and other utility classes. (L2)
CO4 Develop problem-solving skills and algorithmic thinking, applying OOP
concepts to design efficient solutions to various programming challenges. (L3)
CO5 Develop new programs for solving typical computer science problems (L6)

Do’s
1. Come with completed observation and record
2. Wear ID card before entering into the lab.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
5. Report any broken plugs or exposed electrical wires to your lecturer/laboratory
technician immediately.

SEGAI - Tirupati Page 5


NB

6. Write in time, out time and system details in the login register.

Don’ts
1. Do not eat or drink in the laboratory.
2. Do not operate mobile phones in the lab. Keep mobile phones either in silent or
switched off mode.
3. Do not change system settings.
4. Do not disturb your neighbouring students. They may be busy in completing tasks.
5. Do not remove anything from the computer laboratory without permission.
6. Do not use pen drives.
7. Do not misbehave.

INDEX
Exercise List of Experiments
a) Write a JAVA program to display default value of all primitive
data type of JAVA
1 b) Write a java program that display the roots of a quadratic
equation ax2+bx=0. Calculate the discriminate D and basing on
value of D, describe the nature of root.
a) Write a JAVA program to search for an element in a given list
of elements using binary search mechanism.
b) Write a JAVA program to sort for an element in a given list of
2
elements using bubble sort
c) Write a JAVA program using StringBuffer to delete, remove
character.
a) Write a JAVA program to implement class mechanism. Create
a class, methods and invoke them inside main method.
3 b) Write a JAVA program implement method overloading.
c) Write a JAVA program to implement constructor.
d) Write a JAVA program to implement constructor overloading.
a) Write a JAVA program to implement Single Inheritance
b) Write a JAVA program to implement multi level Inheritance
4
c) Write a JAVA program for abstract class to find areas of
different shapes
a) Write a JAVA program give example for “super” keyword.
b) Write a JAVA program to implement Interface. What kind of
5 Inheritance can be achieved?
c) Write a JAVA program that implements Runtime
polymorphism
a) Write a JAVA program that describes exception handling
mechanism
6 b) Write a JAVA program Illustrating Multiple catch clauses
c) Write a JAVA program for creation of Java Built-in Exceptions
d) Write a JAVA program for creation of User Defined Exception
a) Write a JAVA program that creates threads by extending
Thread class. First thread display “Good Morning “every 1 sec,
7
the second thread displays “Hello “every 2 seconds and the third
display “Welcome” every 3 seconds, (Repeat the same by

SEGAI - Tirupati Page 6


NB

implementing Runnable)
b) Write a program illustrating is Alive and join ()
c) Write a Program illustrating Daemon Threads.
d) Write a JAVA program Producer Consumer Problem
a) Write a JAVA program that import and use the user
defined packages
b) Without writing any code, build a GUI that display text in
8 label and image in an ImageView (use JavaFX)
c) Build a Tip Calculator app using several JavaFX
components and learn how to respond to user
interactions with the GUI
Text and References:-
Text Books:
1. JAVA one step ahead, Anitha Seth, B.L.Juneja, Oxford.
2. Joy with JAVA, Fundamentals of Object Oriented Programming,
DebasisSamanta, MonalisaSarma, Cambridge, 2023.
3. JAVA 9 for Programmers, Paul Deitel, Harvey Deitel, 4th Edition, Pearson.
Reference Books
4. The complete Reference Java, 11th edition, Herbert Schildt,TMH
5. Introduction to Java programming, 7th Edition, Y Daniel Liang, Pearson
Online Learning Resources/Virtual Labs:
1.https://nptel.ac.in/courses/106/105/106105191/
2.https://infyspringboard.onwingspan.com/web/en/app/toc/lex_auth_012880464547
618816 347_shared/overview
\

Lab Exercise
Lab – 1 (2 Hrs actual Time)
1. Write a program to display any message
2. Write a Java program to display default value of all primitive data types of java
3. Write a program check two strings are equal or not.

Lab – 2 (2 Hrs actual Time)


1. Write a program to give the examples of operators.
a) Increment and decrement operators.
b) Bitwise Complement Operator.
c) Arithmetic operator.
d) Relational Operator
e) Bitwise operator.
f) Conditional Operator

2. Write a program to give the example of control statements.


a) If statements.
b) Switch Statements.
c) For loop.
d) While Statements.

SEGAI - Tirupati Page 7


NB

e) Do statements
3. Write a program to calculate the following
a) Find the length of array.
b) Demonstrate a one-dimensional array.
c) Demonstrate a two-dimensional array.
d) Demonstrate a multi-dimensional array.
4. Write a program to the find the following
a) Sum of digit
b) Prime number checking
5. Write a program to arrange the numbers in ascending order.
6. Write a program for calculating Matrix Operations.
a) Addition.
b) Multiplication.
Lab Manual
Installation of Java software:

Steps:
1. Download JDK7.0 from www.java.sun.com/downloads

2. Install JDK by double clicking on setup file

3. Follow the installation wizard.


4. Upon successful installation the default location where java is installed is

C:\Program Files\Java directory.

5. To compile a java class we have to use javac (javacompiler)

6. To execute java program we have to use jvm (java virtual machine).


7. To use javac and jvm we have to configure environment variables.

Environment Variables
PATH:
1. This environment variable is to locate the compiler.
2. Right click MYCOMPUTER and find a properties tab, Click on Properties Tab and find
Advanced Tab, Click on it to see environment variables.
3. In this create a new environment variable called PATH and copy the location of java
compiler as value to it.

Default location:
$PATH= C:\Program Files\Java\Jdk1.6.0\bin;

SEGAI - Tirupati Page 8


NB

CLASSPATH:
This environment variable will help the jvm to find the runtime environment of java i.e. all
predefined classes and interfaces can be located using this variable. The location for runtime
environment is JRE folder.

$CLASSPATH= C:\Program Files\Java\Jre\bin;

Installation of Java software, study of any Integrated development environment, Use Eclipse or
Netbeans platform and acquaint with the various menus. Create a test project, add a test class
and run it.

See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods and classes. Try debug step by step with java program to find prime
numbers between 1 to n.

1. Aim: To create and test java projects in Eclipse and Netbean platform

How to Download and Install Eclipse to Run Java

Step 1) Installing Eclipse


Open your browser and type https://www.eclipse.org/

Step 2) Click on “Download” button.

SEGAI - Tirupati Page 9


NB

Step 3) Click on “Download 64 bit” button

Step 4)
Click on
“Download” button

Step 5) Install Eclipse.


Click on “downloads” in Windows file explorer.
Click on “eclipse-inst-win64.exe” file.

Step 6) Click on Eclipse IDE for java Developers

SEGAI - Tirupati Page 10


NB

Step 7) Click on Install button

SEGAI - Tirupati Page 11


NB

Step 8) Click on “LAUNCH” button.

Step 9) Click on “Launch” button.

SEGAI - Tirupati Page 12


NB

Step 10) Click on “Create a new Java project” link.

Step 11) Create a new Java Project


Write project name.
Click on “Finish button”.

SEGAI - Tirupati Page 13


NB

Step 12) Click create in new module-info.java file

Step 13) Create Java Package.


Goto “src”.
Click on “New”.
Click on “Package”.

SEGAI - Tirupati Page 14


NB

Step 14) Writing package name.


Write name of the package
Click on Finish button.

Step 15) Creating Java Class


Click on package you have created.
Click on “New”.
Click on “Class”.

SEGAI - Tirupati Page 15


NB

Step 16) Defining Java Class.


Write class name
Click on “public static void main (String*+ args)” checkbox.
Click on “Finish” button.

SEGAI - Tirupati Page 16


NB

Step 17) Click on “Run” button.

SEGAI - Tirupati Page 17


NB

Exercise – 1 (2 Hrs actual Time)


a) Write a JAVA program to display default value of all primitive data type of JAVA
b) Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

a) Displayingdefaultvalueofallprimitivedatatypes
AIM: To write a JAVA program to display default value of all primitive data type of
JAVA

SOURCE-CODE:
class defaultdemo
{
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
System.out.println("The default values of primitive data types are:");
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}}

Sample Input/output:
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false

SEGAI - Tirupati Page 18


NB

NOTE:
To Compile:

javac defaultdemo.java

To Run:

java defaultdemo

b) Roots of a quadratic equation


AIM: To write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.

SOURCE-CODE:
import java.util.*;
class quadraticdemo
{
public static void main(String[] args)
{
int a, b, c;
double r1, r2, D;
Scanner s = new Scanner(System.in);
System.out.println("Given quadratic equation:ax^2 + bx + c");
System.out.print("Enter a:");
a = s.nextInt();
System.out.print("Enter b:");
b = s.nextInt();
System.out.print("Enter c:");
c = s.nextInt();
D = b * b - 4 * a * c;
if(D > 0)
{
System.out.println("Roots are real and unequal");
r1 = ( - b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
System.out.println("First root is:"+r1);
System.out.println("Second root is:"+r2);
}
else
if(D == 0)
{
System.out.println("Roots are real and equal");
r1 = (-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
}
else
SEGAI - Tirupati Page 19
NB

{
System.out.println("Roots are imaginary");
}}}

Sample OUTPUT:
Given quadratic equation:ax^2 + bx + c
Enter a:2
Enter b:3
Enter c:1
Roots are real and unequal
First root is:-0.5
Second root is:-1.0

NOTE:
To Compile:

javac quadraticdemo.java

To Run:

java quadraticdemo

Exercise – 2 (2 Hrs actual Time)


a) Write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
b) Write a JAVA program to sort for an element in a given list of elements using
bubble sort
c) Write a JAVA program using StringBuffer to delete, remove character.

a) Implementation of Binary search mechanism


AIM: To write a JAVA program to search for an element in a given list of elements using
binary search mechanism
SOURCE-CODE:
import java.util.Scanner;
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;

SEGAI - Tirupati Page 20


NB

int a[ ]=new int[20];


Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements in sorted order:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
System.out.println("Enter the search value:");
num = s.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
System.out.println("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println( " Number is not found");
}}

Sample Output:-
Enter total number of elements: 5
SEGAI - Tirupati Page 21
NB

Enter elements: 2 4 6 8 9
Enter the search value: 8
number found

b) Bubble sort
AIM: To write a JAVA program to sort for an element in a given list of elements using
bubble sort
SOURCE-CODE:
import java.util.Scanner;
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}}}
System.out.println("The sorted elements are:");
for(i=0;i<n;i++)
SEGAI - Tirupati Page 22
NB

System.out.print("\t"+a[i]);
}}
Sample Output
Enter total number of elements:
10
Enter elements: 3 2 5 7 6 8 9 1 4 0
The sorted elements are: 0 1 2 3 4 5 6 7 8 9

C) Implementing StringBuffer
AIM: To write a JAVA program using StringBuffer to delete, remove character
SOURCE CODE:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0); System.out.println(sb3);
}}
Sample Output
World
Some Content
Hello World

SEGAI - Tirupati Page 23


NB

Exercise – 3 (2 Hrs actual Time)


a) Write a JAVA program to implement class mechanism. Create a class, methods
and invoke them inside main method.
b) Write a JAVA program implement method overloading.
c) Write a JAVA program to implement constructor.
d) Write a JAVA program to implement constructor overloading.

a) Implementing Class & Objects

AIM: To write a JAVA program to implement class mechanism. – Create a class,


methods and invoke them inside main method

SOURCE-CODE:
1. no return type and without parameter-list:
class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}}
OUTPUT: 10 20
2. no return type and with parameter-list:
class A
{
void display(int l,int b)
{
System.out.println(l);
System.out.println(b);
}}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}}

OUTPUT: 10 20

SEGAI - Tirupati Page 24


NB

3. return type and without parameter-list


class A
{
int l=10,b=20;
int area()
{
return l*b;
}}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}}
OUTPUT: The area is:200

4. return type and with parameter-list:


class A
{
int area(int l,int b)
{
return l*b;
}}
class methoddemo {
public static void main(String args[])
{
A a1=new A();
int r=a1.area(10,20);
System.out.println(“The area is:”+r);
}}
OUTPUT: The area is:200

c) Method Overloading
AIM: To write a JAVA program implement method overloading
SOURCE-CODE:
class A
{
int l=10,b=20;
int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}}
SEGAI - Tirupati Page 25
NB

class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
int r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}}
OUT-PUT:
The area is: 200
The area is: 100

d) Implementing Constructor
AIM: To write a JAVAto implement constructor
SOURCE-CODEs:

i)A constructor with no parameters:


class A
{
int l,b;
A()
{
l=10; b=20;
}
int area()
{
return l*b;
}}
class constructordemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}}

Sample OUTPUT:
The area is:200

ii) A constructor with parameters


class A
{
int l,b;
A(int u,int v)
{
SEGAI - Tirupati Page 26
NB

l=u; b=v;
}
int area()
{
return l*b;
}}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area();
System.out.println("The area is: "+r);
}}
OUT-PUT:
The area is:200

e) Constructor Overloading
AIM: To write a JAVA program to implement constructor overloading
SOURCE-CODE:
class A
{
int l,b;
A()
{
l=10;b=20;
}
A(int u,int v)
{
l=u;b=v;
}
int area()
{
return l*b;
}}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
A a2=new A(30,40);
int r2=a2.area();
System.out.println("The area is: "+r2);
}}
OUT-PUT:
The area is: 200
The area is: 1200
SEGAI - Tirupati Page 27
NB

Exercise – 4 (2 Hrs actual Time)


a) Write a JAVA program to implement Single Inheritance
b)Write a JAVA program to implement multi level Inheritance
c) Write a JAVA program for abstract class to find areas of different shapes

a) Implementing Single Inheritance

AIM: To write a JAVA program to implement Single Inheritance

SOURCE-CODE:

class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}}

OUTPUT:
Inside A's Constructor
Inside B's Constructor

b) Multi level Inheritance


AIM: To write a JAVA program to implement multi level Inheritance
SOURCE-CODE:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}}
class B extends A
{
SEGAI - Tirupati Page 28
NB

B()
{
System.out.println("Inside B's Constructor");
}}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}}
class multidemo
{
public static void main(String args[])
{
C c1=new C();
}}
OUTPUT:
Inside A's Constructor
Inside B's Constructor
Inside C's Constructor

c) Abstract Class
AIM: To write a java program for abstract class to find areas of different shapes
SOURCE-CODE:
abstract class shape
{
abstract double area();
}
class rectangle extends shape
{
double l=12.5,b=2.5;
double area()
{
return l*b;
}}
class triangle extends shape
{
double b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}}
class square extends shape
{
double s=6.5;
double area()
{
return 4*s;
SEGAI - Tirupati Page 29
NB

}}
class shapedemo
{
public static void main(String[] args)
{
rectangle r1=new rectangle();
triangle t1=new triangle();
square s1=new square();
System.out.println("The area of rectangle is: "+r1.area());
System.out.println("The area of triangle is: "+t1.area());
System.out.println("The area of square is: "+s1.area());
}}
OUTPUT:
The area of rectangle is: 31.25
The area of triangle is: 13.65
The area of square is: 26.0

SEGAI - Tirupati Page 30


NB

Exercise – 5 (2 Hrs actual Time)


a) Write a JAVA program give example for “super” keyword.
b) Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?

c) Write a JAVA program that implements Runtime polymorphism

a) super keyword implementation

AIM: Write a JAVA program give example for “super” keyword


SOURCE-CODEs:
(i) Using super to call super class constructor (Without parameters)

class A
{
int l,b;
A()
{
l=10; b=20;
}}
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}}
OUTPUT: The vol. is:6000

(ii) Using super to call super class constructor (With parameters)


class A
{
int l,b;

SEGAI - Tirupati Page 31


NB

A(int u,int v)
{
l=u; b=v;
}}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}}
OUTPUT: The vol. is:18000

b) Implementing interface
AIM: To write a JAVA program to implement Interface.
SOURCE-CODEs:
(i) First form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}}
class C extends B
{
public void callme()
{
System.out.println("C's method");
SEGAI - Tirupati Page 32
NB

}}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}}
OUTPUT:
B's method
C's method

ii) Second form of interface implementation


interface D
{
void display();
}
interface E extends D
{
void show();
}
class A {
void callme()
{
System.out.println("This is in callme method");
}}
class B extends A implements E
{
public void display()
{
System.out.println("This is in display method");
}
public void show()
{
System.out.println("This is in show method");
}}
class C extends B
{
void call()
{
System.out.println("This is in call method");
}}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
SEGAI - Tirupati Page 33
NB

c1.show();
c1.callme();
c1.call();
}}
OUT-PUT:
This is in display method
This is in show method
This is in callme method
This is in call method

iii) Third form of interface implementation


interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("This is in B's method");
} }
class C implements A
{
public void display()
{
System.out.println("This is C's method");
}}
class interfacedemo
{
public static void main(String args[])
{
B b1=new B();
C c1=new C();
b1.display();
c1.display(); } }

OUTPUT: This is in B's method


This is C's method

iv) Fourth form of interface implementation


interface A
{
void display();
}
interface B
{
void callme();
}
interface C extends A,B
SEGAI - Tirupati Page 34
NB

{
void call();
}
class D implements C
{
public void display()
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}}
class interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call(); } }
OUTPUT: interface A
interface B
interface C

d) implements Runtime polymorphism RuntimePolymorphism

AIM: To write a JAVA program that implements Runtime polymorphism

SOURCE-CODE:

class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{

SEGAI - Tirupati Page 35


NB

void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
ref.display();
ref=b1;
ref.display();
ref=a1;
ref.display();
}
}
OUT-PUT:

Inside C class

Inside B class

Inside A class

SEGAI - Tirupati Page 36


NB

Exercise – 6 (2 Hrs actual Time)


a) Write a JAVA program that describes exception handling mechanism
b) Write a JAVA program Illustrating Multiple catch clauses
c) Write a JAVA program for creation of Java Built-in Exceptions
d) Write a JAVA program for creation of User Defined Exception

a) Write a JAVA program that describes exception handling mechanism


AIM: To write a JAVA program that describes exception handling mechanism
SOURCE-CODE:
Usage of Exception Handling:
class trydemo
{
public static void main(String args[])
{
try
{
int a=10,b=0;int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
OUT-PUT:
java.lang.ArithmeticException: / by zeroAfter the catch
statement
b) Illustrating multiple catch clauses
AIM: To write a JAVA program Illustrating Multiple catch clauses
SOURCE-CODE:
class multitrydemo
{
SEGAI - Tirupati Page 37
NB

public static void main(String args[])


{
try
{
int a=10,b=5;int c=a/b;
int d[]={0,1}; System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
OUT-PUT:
java.lang.ArrayIndexOutOfBoundsException: 10 After the catch statement

c) Creation of Java Built-in-Exceptions


AIM: To write a JAVA program for creation of Java Built-in Exceptions
SOURCE-CODEs:
(i) Arithmetic exception
class arithmeticdemo
{
public static void main(String args[])
{
try
{
int a = 10, b = 0;int c =
SEGAI - Tirupati Page 38
NB

a/b;
System.out.println (c);
}
catch(ArithmeticException e)
{
System.out.println (e);
}
}
}
OUT-PUT:
java.lang.ArithmeticException: / by zero

(ii)NullPointer Exception
class nullpointerdemo
{
public static void main(String args[])
{
try
{
String a = null; System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NullPointerException

(iii)StringIndexOutOfBound Exception
class stringbounddemo
{
SEGAI - Tirupati Page 39
NB

public static void main(String args[])


{
try
{
String a = "This is like chipping ";char c
= a.charAt(24); System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.StringIndexOutOfBoundsException: String
index out of range: 24

(iv)FileNotFound Exception
import java.io.*;
class filenotfounddemo
{
public static void main(String args[])
{
try
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
SEGAI - Tirupati Page 40
NB

}
OUT-PUT:
java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified)

(v)NumberFormat Exception
class numberformatdemo
{
public static void main(String args[])
{
try
{
int num = Integer.parseInt ("babu") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}
OUT-PUT:
java.lang.NumberFormatException: For input string: "babu"
(vi)ArrayIndexOutOfBounds Exception
class arraybounddemo
{
public static void main(String args[])
{
try
{
int a[] = new int[5];a[6] =
9;
}
catch(ArrayIndexOutOfBoundsException e)
SEGAI - Tirupati Page 41
NB

{
System.out.println (e);
}
}
}
OUT-PUT:
java.lang.ArrayIndexOutOfBoundsException: 6

d) Creation of User Defined Exception


AIM: To write a JAVA program for creation of User Defined Exception
SOURCE-CODE:
class A extends Exception
{
A(String s1)
{
super(s1);
}
}
class owndemo
{
public static void main(String args[])
{
try
{
throw new A("demo ");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUT-PUT:
A: demo

SEGAI - Tirupati Page 42


NB

Exercise – 7 (2 Hrs actual Time)


a) Write a JAVA program that creates threads by extending Thread class. First
thread display “Good Morning “every 1 sec, the second thread displays “Hello “every
2 seconds and the third display “Welcome” every 3 seconds, (Repeat the same by
implementing Runnable)
b) Write a program illustrating is Alive and join ()
c) Write a Program illustrating Daemon Threads.
d) Write a JAVA program Producer Consumer Problem

a) Write a JAVA program that creates threads by extending Thread class. First thread display
“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third
display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable)

SOURCE-CODEs:
(i)Creating multiple threads using Thread class

class A extends Thread


{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000); System.out.println("good
morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000); System.out.println("hello");
}
}
catch(Exception e)
{
SEGAI - Tirupati Page 43
NB

System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class threaddemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
Cc1=newC();
a1.start();
b1.start();
c1.start();
}
}
OUT-PUT:
good morninghello
good morninggood
morningwelcome
hello
good morning
good morning
hello
good morning
welcome good
morninghello
good morninggood
morningwelcome
hello
good morninghello
SEGAI - Tirupati Page 44
NB

welcome hello
welcome
hello
hello
welcomehello
welcome
welcome
welcome
welcome

(ii) Creating multiple threads using Runnable interface

class A implements Runnable


{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B implements Runnable
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C implements Runnable
SEGAI - Tirupati Page 45
NB

{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
A a1=new A(); B
b1=new B(); C
c1=new C();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
t2.start();
t3.start();
}
}
OUT-PUT:
good morning
good morning
hello
good morning
welcome good
morninghello
good morninggood
morningwelcome
hello
goodmorning
goodmorning
hello
good morning
welcome
good morning
hello
SEGAI - Tirupati Page 46
NB

welcomehello
hello
welcomehello
welcomehello
hello
welcome
welcome
welcome
welcome

b) Write a program illustrating is Alive and join ()

AIM: To write a program illustrating is Alive and join ()


SOURCE-CODE:
class A extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000); System.out.println("good
morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000); System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SEGAI - Tirupati Page 47
NB

class C extends Thread


{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class isalivedemo
{
public static void main(String args[])
{
A a1=new A(); B
b1=new B(); C
c1=new C();
a1.start();
b1.start();
c1.start();
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());try
{
a1.join();
b1.join();
c1.join();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
}
}
OUT-PUT:
true good morning
true hello
true welcome
SEGAI - Tirupati Page 48
NB

good morning hello


good morning hello
hello welcome
good morning hello
welcome welcome
good morning hello
hello hello
good morning welcome
good morning welcome
welcome welcome
hello welcome
good morning false
good morning false
hello false
good morning
welcome

c) Write a Program illustrating Daemon Threads

AIM: To write a program illustrating Daemon Threads


SOURCE-CODE:
class A extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
System.out.println("daemon thread work");else
System.out.println("user thread work");
}
}
class daemondemo
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A();
A a3=new A();
a1.setDaemon(true);
a1.start();
a2.start();
a3.start();
}
}
OUT-PUT:
daemon thread work
user thread work
user thread work

SEGAI - Tirupati Page 49


NB

d) Write a JAVA program Producer Consumer Problem

AIM: Write a JAVA program Producer Consumer Problem


SOURCE-CODE:
class A
{
int n;
boolean b=false;
synchronized int get()
{
if(!b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n);
b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n;
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
A a1;
SEGAI - Tirupati Page 50
NB

Thread t1;
producer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class consumer implements Runnable
{
A a1;
Thread t1;
consumer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class interdemo
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}

OUT-PUT:
Put:1
Got:1
Put:2
Got:2
Put:3
SEGAI - Tirupati Page 51
NB

Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10

SEGAI - Tirupati Page 52


NB

Exercise – 8 (2 Hrs actual Time)


a) Write a JAVA program that import and use the user defined packages
b) Paint like Paint Brush in Apple
c) Display Analog Clock using Applet

Program to implement user defined packages in terms of creating a new package and
importing the same.
//Creating Package
package Pattern;
public class Pattern
{
public void pattern1()
{
int rows = 5;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print("* ");
}
System.out.println();
}
}
public void pattern2()
{
int rows = 5;
for(int i = 1; i <= rows; ++i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println();
}
}
public void pattern3()
{
int rows = 5;
for(int i = rows; i >= 1; --i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print("* ");
}
System.out.println();
}
}
public void pattern4()
SEGAI - Tirupati Page 53
NB

{
int rows = 5;
for(int i = rows; i >= 1; --i)
{
for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println();
}
}
public void pattern5()
{
int alphabet = 65;
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= i; j++)
{
System.out.print((char) alphabet + " ");
}
alphabet++;
System.out.println();
}
}
}

//Using Package
import Pattern.*;
class usePattern
{
public static void main(String args[])
{
Pattern p1=new Pattern();
p1.pattern1();
p1.pattern5();
}
}

Output:

E:>javac Pattern.java

E:>cd..

E:>javac usePattern.java

SEGAI - Tirupati Page 54


NB

E:>java usePattern

**

***

****

*****

BB

C CC

D DDD

E EEEE

F FFFFF

b) Paint like Paint Brush in Applet

AIM: To write a JAVA program to paint like paint brush in applet.

SOURCE-CODE:

import java.applet.*; import


java.awt.*; import
java.awt.event.*;
//<applet code="paintdemo" width="800" height="500"></applet>
public class paintdemo extends Applet implements MouseMotionListener
{
int w, h; Image i;
Graphics g1;
public void init()
{
w = getSize().width; h = getSize().height;i =
createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white ); g1.fillRect( 0, 0, w, h ); g1.setColor( Color.red );i =
createImage( w, h );
g1 = i.getGraphics();
g1.setColor( Color.white ); g1.fillRect( 0, 0, w, h ); g1.setColor( Color.blue );
addMouseMotionListener( this );
}
public void mouseMoved( MouseEvent e ) { }public void
mouseDragged( MouseEvent me )
{
int x = me.getX(); int y = me.getY();
g1.fillOval(x-10,y-10,20,20); repaint();

SEGAI - Tirupati Page 55


NB

me.consume();
}
public void update( Graphics g )
{
g.drawImage( i, 0, 0, this );
}
public void paint( Graphics g )
{
update(g);
}
}
OUT-PUT:

C) Display Analog Clock using Applet


AIM: To write a JAVA program to create different shapes and fill colors using Applet
SOURCE-CODE:
import java.awt.*; import
java.applet.*;
//<applet code="graphicsdemo" width="400" height="400"></applet>public
class graphicsdemo extends Applet
{
public void paint(Graphics g)
{
int x[]={10,220,220};
int y[]={400,400,520};
int n=3; g.drawLine(10,30,200,30);
g.setColor(Color.blue); g.drawRect(10,40,200,30); g.setColor(Color.red);
g.fillRect(10,80,200,30); g.setColor(Color.orange);
g.drawRoundRect(10,120,200,30,20,20); g.setColor(Color.green);
g.fillRoundRect(10,160,200,30,20,20); g.setColor(Color.blue);
g.drawOval(10,200,200,30); g.setColor(Color.black);
g.fillOval(10,240,40,40); g.setColor(Color.yellow);
g.drawArc(10,290,200,30,0,180); g.setColor(Color.yellow);
g.fillArc(10,330,200,30,0,180); g.setColor(Color.pink); g.fillPolygon(x,y,n);
}
}
OUT-PUT:

SEGAI - Tirupati Page 56


NB

*************** End *****************

SEGAI - Tirupati Page 57

You might also like