KEMBAR78
r22 - Oop Lab Manual CSD | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
20 views81 pages

r22 - Oop Lab Manual CSD

The document is a laboratory manual for the Object Oriented Programming course at the Department of Computer Science & Engineering, focusing on Java. It outlines program outcomes, specific course objectives, and expected outcomes for students, including practical exercises and assessments. The manual includes a detailed list of experiments, tools, and techniques to develop skills in OOP concepts, GUI applications, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views81 pages

r22 - Oop Lab Manual CSD

The document is a laboratory manual for the Object Oriented Programming course at the Department of Computer Science & Engineering, focusing on Java. It outlines program outcomes, specific course objectives, and expected outcomes for students, including practical exercises and assessments. The manual includes a detailed list of experiments, tools, and techniques to develop skills in OOP concepts, GUI applications, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

(AUTONOMOUS)

Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

Laboratory Manual

OBJECT ORIENTED PROGRAMMING


LABORATORY

(II B. Tech- I SEMESTER)

(VCE-R22)

Course Code-A8602
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
PROGRAM OUTCOMES (POS)
PO1: Engineering Knowledge: Apply knowledge of mathematics, science, engineering fundamentals
and an engineering specialization to the solution complex engineering problems.
PO2: Problem Analysis: Identify, formulate, 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 specified needs with appropriate consideration for
public health and safety, 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
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 contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to professional
engineering practice.
PO7: Environment and Sustainability: Understand the impact of professional engineering solutions
in societal and environmental contexts and demonstrate knowledge of and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of engineering practice.
PO9: Individual and Team Work: Function effectively as an individual, and as a member or leader in
diverse teams and in multi-disciplinary 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 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.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: To collect requirements, analyze, design, implement and test software Systems.
PSO2: To analyze the errors and debug them within minimal time.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
OBJECT ORIENTED PROGRAMMING
Course Title Course Type Non-Integrated
LABORATORY
II Year I
Course Code A8602 Credits 4 Class
Semester
Contact Work Total Number of
TLP Credits Assessment in
Hours Load Classes
Weight age
Theory 3 3 3 Per Semester
Course
Structure Practice 1 2 2
Theory Practical CIE SEE
Tutorial - - -

Total 4 5 5 42 28 40% 60%

Course Lead: Mr M.Yugandhar


Theory Practice
Course
Instructors Dr Shaik Imam Saheb
Dr Shaik Imam Saheb
Mr. Bijaya Kumar Sethi
Mr. Bijaya Kumar Sethi

COURSE OVERVIEW:
This integrated course provides a comprehensive coverage of theory and practice of OOP concepts
using Java. The course focuses on different aspect of core Java Environment suitable to write efficient,
maintainable, and portable code for real world application. It provides strong foundation on OOP
Principles, Packages, and Interfaces and also illustrates Exception Handling and Multithreaded
mechanisms. The course provides In depth knowledge to implement Collection framework. Emphasis
on AWT and Swing concepts used for GUI applications is given with event handling. The course plays a
vital role in developing front-end interface for Mini and Major Projects.
COURSE OBJECTIVE
The course enables the learner to apply Object-oriented Programming concepts to develop Console and
GUI components as per needs and specifications.
COURSE OUTCOMES (COs)
After the completion of the course, the student will be able to:
CO# Course Outcomes
A8602.1 Make use of various constructs to write a console application.
A8602.2 Use principles of OOP to develop real time applications.
A8602.3 Examine the applications for Exception Handling and Multithreading.
A8602.4 Implement Collection Framework to organize data efficiently .
A8602.5 Build GUI applications using AWT and Swings.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

Bloom’s Level of the Course Outcomes:

Bloom’s Level
CO# Remember Understand Apply Analyze Evaluate Create
(L1) (L2) (L3) (L4) (L5) (L6)
A8602.1 ✔
A8602.2 ✔
A8602.3 ✔
A8602.4 ✔
A8602.5 ✔

Course Articulation Matrix:

PO10

PO11

PO12

PSO1

PSO2
CO#/
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9

POs
A8602.1 2 2 2 2
A8602.2 3 2 2 2
A8602.3 2 2 2 2
A8602.4 3 2 2 2
A8602.5 3 3 3 3
Note: 1-Low, 2-Medium, 3-High
List of Programs For Practice:
Tools and Expected
S.No Title of the Experiment
Techniques Skills/Ability
Implement Control statements
a. Read the marks of a student in 4 subjects and find
1 grade.
b. Program to check a number is Amstrong or not. Open source
Program to display prime numbers from m to n. Java Tool kit:
Implement OOP First principle - Encapsulation JDK 8 and Apply OOP
a. Define a class Rectangle with data member’s length above versions, principles to solve
and width. Write methods to find perimeter and problems
area of a rectangle. (class and object) Open Source
2
b. Create a class Account with data members name, IDE: Eclipse /
acno and balance. Use appropriate methods to NetBeans
perform various operations like deposit, withdraw,
balnce Check. OS: Windows /
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Tools and Expected
S.No Title of the Experiment
Techniques Skills/Ability
c. Create a class Student with appropriate data and Linux
methods using constructor.
Implement OOP Second principle – Polymorphism Web browser:
and Arrays Internet
a. Create overloaded methods to find volume of Explorer/
3 Sphere, Cylinder & Cone. Google/ Firefox
b. To sort given list of elements in ascending order.
c. Read two matrices of size m*n , p*q , perform the
multiplication of matrices.
Implement Java String Class.
a. Check a string is palindrome or not.
b. Given a string and an int n, return a string made of
n repetitions of the last ncharacters of the string.
You may assume that n is between 0 and the length
of the string, inclusive. Write a Java program.
repeatEnd("Hello",3)→"llollollo
repeatEnd("Hello",2)→"lolo"
repeatEnd("Hello", 1) → "o"
4
c. We'll say that a "triple" in a string is a char
appearing three times in a row. Return the number
of triples in the given string. The triples may
overlap. Write a Java program.
countTriple("abcXXXabc")→1,
countTriple("xxxabyyyycd")→3
countTriple("a") → 0
d. Read array of City names and Sort in dictionary
order.(Ascending order). Develop user
defined packages
Implement OOP Third principle – Inheritance.
and Interfaces
a. Declare a class called Employee having employee
_id and employee_name as members. Extend class
Employee to have a subclass called Salary having
designation and monthly_salary as members.
Define following:
 Required constructor
 A method to find and display all details of
employees drawing salary more than
5
Rs.20000/-
 main () method to create an array.
b. Write a Java program that create an abstract base
class Shape with two members base and height, a
member function for initialization and a function to
compute shapeArea(). Derive two specific classes
Triangle and Rectangle which override the function
shapeArea(). Write a driver classes (main) to
display the area of the triangle and the rectangle.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Tools and Expected
S.No Title of the Experiment
Techniques Skills/Ability
(Use super keyword).

Implement Packages and Interfaces.


a. Create a Package Measure; in which store a class
named Convertor that contains methods to convert
mm to cm, cm to m and m to km. Define a class
Need_Convertor that imports the Convertor class,
now store Need_Convertor outside the package
6 Measure. Perform path settings accordingly.
b. Write a Java program that implements an
interface Student which has two methods
displayGrade() and attendance(). Implement
two classes PG_Student and UG_Student with
necessary inputs of data.
Implement Exception Handling .
a. Read two integers as strings Num1 and Num2 to
perform division. The program would throw a
Number Format Exception if Num1 or Num2 cannot
be converted to integers nad If Num2 is Zero throw
7 an Arithmetic Exception. Display the exception
message.
b. In the Custom Exception Test class, the age is
expected to be a positive number. It would throw
Analyze exceptions
the user defined exception Negative Age Exception
and multithreading
if the age is assigned a negative number.
and handle them
Develop applications on Multithreaded
Programming and thread synchronization.
a. Create a multithreaded java program by creating a
subclass of Thread and then creating, initializing,
8 and staring two Thread objects from your class.
b. The threads will execute concurrently and display
“Java is object oriented” in console window.
c. Implement the concept of producer consumer
problem using thread synchronization.
Implement Collection Frameworks to retrieve data.
a. Use an Array List to manage Employee objects for
9 insertion, display and remove.
b. Use HashSet methods to perform operations on Develop Collection
collection of data. frameworks and
Implement Mouse and Key events. handle events
a. Implement Mouse Listener and Mouse Motion
10
Listener to handle various mouse events.
b. Implement Key Listener to handle key events.
Develop GUI applications using AWT. Develop GUI
11
a. Create a Simple login window to validate a user applications using
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Tools and Expected
S.No Title of the Experiment
Techniques Skills/Ability
with name and password. AWT and Swings
b. Using Grid Layout design a Simple calculator with
appropriate event handling.
Develop GUI applications using Swing Controls.
a. Create a user interface to insert employee details,
12 Display the data in Text area.
b. Create a JTable to display various fields of Student
data like RollNo, Name, Branch, Year, Percentage etc.
ASSESSMENT SCHEME

Max. Marks
S.NO# EVALUATION METHOD ASSESSMENT TOOL
Marks Total

Pre-Lab Questions 1

Observations / Flow Chart 1


Day to Day Evaluation
Calculations, Graphs, Program
1 (Before CAT-I => 6 Weeks) 1 10
Execution
(Before CAT-II=> 6 Weeks)
Post-Lab Questions 1

Viva-Voce 1
2 Test 10 10
Preparatory Lab Test CAT-I
Viva-Voce 10 10

4 Alternate Assessment Laboratory Project 10 10

Test 40

5 External Lab Examination Evaluation of results 10 60


Viva-Voce 10
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
PART-1
Using Java Scanner Class to read input
Scanner is a class in “java. util” package used for obtaining the input of the primitive types like
int, double, and strings etc. It is the easiest way to read input in a Java program
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by
default. It provides many methods to read and parse various primitive values. Java Scanner class
is widely used to parse text for string and primitive types using regular expression.

Commonly used methods of Scanner class

Method Description
public String next() It returns the next token (string) from the
scanner.
public String nextLine() It moves the scanner position to the next line and
returns the value as a string.
public byte nextByte() It scans the next token as a byte.
public short nextShort() It scans the next token as a short value.
public int nextInt() It scans the next token as an int value.
public long nextLong() It scans the next token as a long value.
public float nextFloat() It scans the next token as a float value.
public double nextDouble() It scans the next token as a double value.

// Example to read and display data

import java.util.*;
import java.io.*;
public class DataRead
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");


int rollno=sc.nextInt();

System.out.println("Enter your name");


String name=sc.next();

System.out.println("Enter your fee");


(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
double fee=sc.nextDouble();

System.out.println(“Roll No : “ +rollno);
System.out.println(“Name is “ +name);
System.out.println(“Feee is “ +fee);

//System.out.println("Rollno:"+rollno +" name:" +name + " fee:" +fee);

sc.close();

}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
PART-2

WEEKLY LAB EXCERCISES

WEEK-1

Objective: After the completion of the practice session, the student will be able to implement
Control statements

a) Program to find Grade of a Student in 4 Subjects

import java.util.*;
public class GradeDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Marks in 4 Subjects");
int m1= sc.nextInt();
int m2= sc.nextInt();
double m3= sc.nextDouble();
double m4= sc.nextDouble();

double avg = (m1+m2+m3+m4)/4.0;

System.out.println("The average of student is " +avg);

if(avg >= 70)


System.out.println("Distinction");
else if (avg >=60 && avg <70)
System.out.println("First Class");
else if (avg >=50 && avg < 60)
System.out.println("Second Class");
else if (avg >=40 && avg < 50)
System.out.println("Second Class");
else
System.out.println("Fail");

}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

Output:

b) Program to check a Number is Amstrong or Not


import java.util.*;
class AmstrongDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
int s=0, r , m;
m=n;
while(n > 0)
{
r = n % 10;
s = s + (r*r*r);
n = n/10;
}

if (s==m)
System.out.println("The number " +m + " -> is Amstrong");
else
System.out.println("The number " +m + " -> is Not Amstrong");

}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:

C) Program to display Prime Numbers from m to n


import java.util.*;
public class PrimeDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to start -m ");
int m = sc.nextInt();
System.out.println("Enter a number to end -n ");
int n = sc.nextInt();
int i , num;
System.out.println("prime numbers from " + m + " to "+n+"are:");
for (i = m; i <= n; i++)
{
int count=0;
for(num =1; num<=i; num++)
{
if(i%num==0)
count = count + 1;
}
if (count ==2)
System.out.println(i);
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-2
Objective: After the completion of the practice session, the student will be able toimplement OOP
First principle – Encapsulation.
a) Define a class Rectangle with data member’s length and width. Write methods to find
perimeter and area of a rectangle. (class and object)
import java.util.*;
class Rect
{
private double len,wid;
public void setData(double d1 , double d2)
{
len=d1; wid=d2;
}
public double perimeter( )
{
double res= 2*(len+wid);
return res;
}
public double area( )
{
double res=(len*wid);
return res;
}
public void display( )
{
System.out.println("The Rectangle dimensions are " +len +", " + wid);
}
} //close Rect

public class RectDemo


{
public static void main(String args[])
{

Rect r1 ; //class variable declaration


//r1.len=2.3; //error -private member
r1 = new Rect(); // Object
r1.setData(3.5,4.5);
r1.display();
double x = r1.perimeter();
System.out.println("The perimeter of the Rectangle is " );
System.out.println(x);
System.out.println("The area of the Rectangle is " +r1.area());

//reading data from keyboard


System.out.println("Enter the dimensions");
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Scanner sc = new Scanner(System.in);
double x1 = sc.nextDouble( );
double x2 = sc.nextDouble( );
Rect r2 = new Rect( ); // declartion and creation
r2.setData(x1,x2);
r2.display();
System.out.println("The perimeter of the Rectangle is "+r2.perimeter());
System.out.println("The area of the Rectangle is " +r2.area());

Rect r3 = r2; //reference variable


System.out.println("The perimeter of the Rectangle is "+r3.perimeter());
System.out.println("The area of the Rectangle is " +r3.area());
sc.close();
}
}

Output:

b) Create a class Account with data members name, acno and balance. Use appropriate
methods to perform various operations like deposit,withdraw, balnceCheck.
class Account
{
int acno;
String name;
double balance;
public void setData(int x , String y , double z)
{
acno=x;
name=y;
balance=z;
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
public double getBal( )
{
return (balance);
}
public void deposit( double amt)
{
balance = balance + amt;
}
public void withdraw( double amt)
{
balance = balance -amt;
}
public void display()
{
System.out.println("The account details are");
System.out.println("Account No -> " +acno);
System.out.println("Account Name -> " +name);
System.out.println("Account Balance -> " + balance);
}
}

public class AccDemo


{
public static void main(String[] args)
{
Account ac1 = new Account();
ac1.setData(1102 , "Ramesh A" , 345678.75);
ac1.display();
System.out.println("The balance is " + ac1.getBal());
ac1.deposit(10000);
System.out.println("The balance after deposit " + ac1.getBal());
ac1.withdraw(10000);
System.out.println("The balance after withdraw " + ac1.getBal());
}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

c) Create a class Student with appropriate data and methods using constructor.
class Student
{
int rollno; String name, dept;
double avg;
Student()
{ }
Student(int x)
{
rollno = x;
}
Student(int x , String y)
{
this(x);
name=y;
}
Student(int x , String y , double z )
{
this(x,y);
avg=z;
}
Student(int x , String y , double z , String p )
{
this(x,y,z);
dept=p;
}

public void display()


{
System.out.println("The Student Data is");
System.out.println(rollno + " , " +name +"," +avg + " ," +dept );
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
}

public class StudentDemo


{
public static void main(String args[])
{
Student s1 = new Student(501, "Ramesh" );
s1.avg = 87.5;
s1.dept = "CSE";
s1.display();
Student s2 = new Student(502, "Suresh" , 78.5 , "ECE");
s2.display();
}

}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-3

Objective: After the completion of the practice session, the student will be able toimplement OOP
Second principle – Polymorphism.
a) Create overloaded methods to find volume of Sphere, Cylinder & Cone.
/* Use Method overloading concept to solve the problem.
• Volume of Sphere: 4/3 p r3
• Volume of Cylinder: p r2h
• Volume of Cone: 1/3 p r2h */
class Volume
{
final double PI= 3.142; //final to define constants
double getVolume(double r)
{
return(4.0/3 * PI * r*r*r);
}
void getVolume(double r , double h)
{
System.out.print("The volume of Cylinder is ");
double res = PI*r*r*h;
System.out.println(res);
}
double getVolume(int r , int h)
{
return(1/3.0 * PI *r*r*h);
}
}
public class VolumeDemo
{
public static void main(String args[])
{
Volume v1 = new Volume();
System.out.println("The volume of Sphere is " + v1.getVolume(3.67));
v1.getVolume(5.6,8.9);
System.out.println("The volume of Cone is " +v1.getVolume(8,10));
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:

b) To sort given list of elements in ascending order.


import java.util.*;
public class SortDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of Elements");


int n = sc.nextInt();
int s[] = new int[n];
System.out.println(" Enter the Elements");
for(int i=0; i< n;i++)
s[i] = sc.nextInt();
System.out.println(" The Elements before sorting are");
for(int i=0; i< s.length;i++)
System.out.print(s[i] + " ");
for(int i= 0; i < s.length; i++)
{
for(int j = i + 1; j < s.length; j++)
{
if( s[i] >s[j])
{
int tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
}
System.out.println(" \n The Elements After Sorting are");
for(int i=0; i< s.length;i++)
System.out.print(s[i] + " “);
}
}
Output:

c) Read two matrices of size m*n , p*q , perform the multiplication of matrices.

import java.util.*;
public class MatrixDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of Matrix A - m * n");
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println("Enter the size of Matrix B - p * q");
int p = sc.nextInt();
int q = sc.nextInt();
if (n != p)
{
System.out.println("Multiplication cannot be performed");
System.exit(0);
}
int a[][] = new int[m][n];
int b[][] = new int[p][q];
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
int c[][] = new int[m][q];

System.out.println("Enter the elements of Matrix-A");


for(int i =0; i<m;i++)
for(int j=0;j<n;j++)
a[i][j] = sc.nextInt();
System.out.println("Enter the elements of Matrix-B");
for(int i =0; i<p;i++)
for(int j=0;j<q;j++)
b[i][j] = sc.nextInt();
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] = c[i][j] + a[i][k]*b[k][j];
}
}
System.out.println("The Product 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:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-4
Objective: After the completion of the practice session, the student will be able toImplement Java
String Class.
a) Check a string is palindrome or not.
import java.util.*;
public class Palindrome
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String s = sc.next();
int len = s.length();
int i , j=len-1;
boolean flag=true;
for(i=0 ; i < len/2 ; i++)
{
if(s.charAt(i) != s.charAt(j))
{
flag=false;
}
j--;
}
if(flag==true)
System.out.println("The string " +s + " is Palindrome");
else
System.out.println("The string " +s + " is Not a Palindrome");
}
}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

b) Given a string and an int n, return a string made of n repetitions of the last n characters of
the string. You may assume that n is between 0 and the length of the string, inclusive.
Write a Java program.
repeatEnd("Hello",3)→"llollollo
repeatEnd("Hello",2)→"lolo"
repeatEnd("Hello", 1) → "o"
import java.util.*;
public class String1
{
public static String repeatEnd(String str, int n)
{
int len = str.length();
String res = " ";
for (int i = 0; i < n; i++)
{
res = res+str.substring(len - n, len);
}
return res;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String str = sc.next();
System.out.println("Enter the number of Chars");
int n = sc.nextInt();
String res = repeatEnd( str , n);
System.out.println("The result is " +res);

}
}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
c) We'll say that a "triple" in a string is a char appearing three times in a row. Return the
number of triples in the given string. The triples may overlap. Write a Java program.
countTriple("abcXXXabc")→1,
countTriple("xxxabyyyycd")→3
countTriple("a") → 0

import java.util.*;
public class String2
{
public static int countTriple(String str)
{
int len = str.length();
int count = 0;
for (int i = 0; i < len-2; i++)
{
char tmp = str.charAt(i);
if (tmp == str.charAt(i+1) && tmp == str.charAt(i+2))
count++;
}
return count;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String");
String str = sc.next();
int res = countTriple( str );
System.out.println("The result is " +res);
}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

d) Read array of City names and Sort in dictionary order.(Ascending order).

import java.util.*;
public class SortDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of City Strings");
int n = sc.nextInt();
String s[] = new String[n];
System.out.println("\n\n Enter the City names");
for(int i=0; i< n;i++)
s[i] = sc.next();
System.out.println("\n\n The cities before sorting are");
for(int i=0; i< s.length;i++)
System.out.println(s[i]);
for(int i= 0; i < s.length; i++)
{
for(int j = i + 1; j < s.length; j++)
{
if( s[i].compareTo(s[j]) > 0 )
{
String tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
}
System.out.println("\n\n The citiesAfter Sorting are");
for(int i=0; i< s.length;i++)
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
System.out.println(s[i]);

}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-5

Objective: After the completion of the practice session, the student will be able to implement
OOP Third principle – Inheritance.

a) Declare a class called Employee having employee _id and employee_name as members.
Extend class Employee to have a subclass called Salary having designation and
monthly_salary as members. Define following:
• Required constructor
• A method to find and display all details of employees drawing salary more than
Rs.20000/-
• main () method to create an array.

import java.util.*;
class Emp
{
int empid;
String empname;
Emp(int no)
{
empid = no;
}
Emp(int no , String name)
{
this(no);
empname = name;
}
}

class Salary extends Emp


{
String designation;
double sal;
Salary(int no , String name , String des , double salary)
{
super(no,name);
designation = des;
sal = salary;
}
void display()
{
System.out.println(empid + " , " + empname + "," +designation + " , " +sal);
}
}
public class EmpInheritDemo
{
public static void main(String args[])
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of employees");
int n = sc.nextInt();
Salary s[] = new Salary[n];
for(int i =0 ; i <n ; i++)
{
System.out.println("Enter the Employee details of " +(i+1));
int id = sc.nextInt();
String name = sc.next();
String desg = sc.next();
double sal = sc.nextDouble();
s[i] = new Salary(id,name,desg,sal);
}

System.out.println("The Employee details having > 20000 are");


for(int i=0;i<n ; i++)
{
if(s[i].sal >20000)
s[i].display();
}
System.out.println("The Employee details in Salary wise Sorting are");

//sorting objects - additional


for(int i=0; i<n; i++) {
for(int j=i+1;j<n;j++) {
if(s[i].sal > s[j].sal)
{
Salary temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for(int i=0;i<n;i++)
s[i].display();

}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:

b) Write a Java program that create an abstract base class Shape with two members base
and height, a member function for initialization and a function to compute shapeArea().
Derive two specific classes Triangle and Rectangle which override the function
shapeArea(). Write a driver classes (main) to display the area of the triangle and the
rectangle.(Use super keyword).

abstract class Shape


{
double base;
double hgt;
Shape(double b , double h)
{
base = b;
hgt = h;
}
abstract double shapeArea();
public void display()
{
System.out.println("dimenstions are " + base + " ," +hgt);
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
class Triangle extends Shape
{
Triangle(double b , double h)
{
super(b,h);
}
double shapeArea()
{
return(0.5*base*hgt);
}
}

class Rectangl extends Shape


{
Rectangl (double b , double h)
{
super(b,h);
}

double shapeArea()
{
return(base*hgt);
}
}

public class AreaDemo


{
public static void main(String args[])
{
Shape t = new Triangle(34.5,89.75); //upcasting
t.display();
System.out.println("The area of triangle is "+t.shapeArea());

Shape r = new Rectangl(34.5 , 75); //upcasting


r.display();
System.out.println("The area of Rectangle is "+r.shapeArea());

}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

WEEK-6

Objective:After the completion of the practice session, the student will be able toimplement Packages and
Interfaces.

a) Create a Package Measure; in which store a class named Convertor that contains
methods to convert mm to cm, cm to m and m to km. Define a class Need_Convertor
that imports the Convertor class, now store Need_Convertor outside the package
Measure. Perform path settings accordingly.
package Measure;
public class Converter
{
public float mmtom(float mm)
{
float m=(mm/1000);
return m;
}
public float cmtom(float cm)
{
float m=(cm/100);
return m;
}
public float mtokm(float m)
{
float km=(m/1000);
return km;
}
}

import Measure.*;
public class NeedConverter
{
public static void main(String args[])
{
Converter c=new Converter();
System.out.println(" mm to m is "+c.mmtom(100));
System.out.println(" cm to m is "+c.cmtom(1000));
System.out.println(" m to km is "+c.mtokm(3000));
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:

b) Write a Java program that implements an interface Student which has two methods
displayGrade() and attendance(). Implement two classes PG_Student and UG_Student
with necessary inputs of data.

interface Student
{
void displayGrade();
void attendence();
}

class PGStudent implements Student


{
String name;
int rollno;
String grade;
double att;
PGStudent(String n , int r , String g , double a)
{
name = n;
rollno=r;
grade=g;
att = a;
}

public void display()


{
System.out.println("The PG Student data is ");
System.out.println(" Name : " +name +" : "+ "Rollno " + rollno);
}
public void displayGrade()
{
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
System.out.println("The Grade of PG Student is " +grade);
}

public void attendence()


{
System.out.println("The attendence of PG Student is " +att);
}

}
class UGStudent implements Student
{
String name;
int rollno;
String grade;
double att;

UGStudent(String n , int r , String g , double a)


{
name = n;
rollno=r;
grade=g;
att = a;
}

public void display()


{
System.out.println("The UG Student data is ");
System.out.println(" Name : " +name +" : "+ "Rollno " + rollno);
}

public void displayGrade()


{
System.out.println("The Grade of UG Student is :" +grade);
}

public void attendence()


{
System.out.println("The attendence of UG Student is : " +att);
}

}
public class IntDemo
{
public static void main(String args[])
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
{
PGStudent s = new PGStudent("Harsha", 1101, "A",78.5);
s.display();
s.attendence();
s.displayGrade();

UGStudent u = new UGStudent("Varsha",5101,"B",68.5);


u.display();
u.attendence();
u.displayGrade();

}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-7

Objective: After the completion of the practice session, the student will be able toimplement Exception
Handling .
a) Creates a user interface to perform integer divisions. The user enters two numbers in the text
fields, Num1 and Num2. The division of Num1 andNum2 is displayed in the Result field when
the Div- id button is clicked. If Num1 or Num2 were not an integer, the program would throw
a NumberFormatException. If Num2 is Zero, the program would throw an
ArithmeticException. Display the exception in a message dialog box.
import java.util.*;
public class ExcepDemo1
{
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number num1");
String s1 = sc.next();
System.out.println("Enter the number2");
String s2=sc.next();
try
{
int num1 = Integer.parseInt(s1);
int num2 = Integer.parseInt(s2);
System.out.println("num1 is " +num1);
System.out.println("num2 is " +num2);
if(num2 ==0)
throw new ArithmeticException ("Division Error");

int res = num1/num2;


System.out.println("The result is " +res);
}
catch(NumberFormatException e)
{
System.out.println("The numbers must be numeric data");
System.out.println("Exception " +e);
}

catch(ArithmeticException e)
{
System.out.println("num2 must not be zero");
System.out.println("Exception" +e);
}

finally
{
System.out.println("Finally block is executed");
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
System.out.println("Remaining statements");
}
}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

b) In the CustomExceptionTest class, the age is expected to be a positive number. It would


throw the user defined exception NegativeAgeException if the age is assigned a negative
number.

class NegativeAgeException extends Exception


{
NegativeAgeException(String s)
{
super(s);
}

public String toString()


{
return "Age Exception";
}
}

public class ExcepDemo2


{
static void validate(int age) throws NegativeAgeException
{
if(age<0)
throw new NegativeAgeException(" not valid "+age);
else
System.out.println(" welcome to the world " +age);
}
public static void main(String args[])
{
try{
validate(23);
validate(17);
validate(-12);
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
validate(25); // Not Executed
}
catch(Exception m)
{
System.out.println("Exception occured: No Negative Age");
System.out.println( m ); // Description of Message
}
finally {
System.out.println("Finally block executed");
}
System.out.println("rest of the code...");
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-8

Objective: After the completion of the practice session, the student will be able todevelop applications on
Multithreaded Programming and thread synchronization.

a) Create a multithreaded java program by creating a subclass of Thread and then creating,
initializing, and staring two Thread objects from your class. The threads will execute
concurrently and display “Java is object oriented” in console window.
class NewThread extends Thread
{
NewThread(String name)
{
super(name);
//start();
}

public void run()


{
try
{
for(int i=1;i<=4;i++ )
{
System.out.println("Java is object oriented" + getName());
sleep(1000);
}
}
catch (InterruptedException ie)
{
System.out.println("Child Thread - Exception caught");
}
}
}
public class ThreadDemo
{
public static void main(String args[])
{
NewThread t1 = new NewThread("First");
NewThread t2 = new NewThread("Second");

t1.start();
t2.start();
System.out.println("Main Program");
}
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

Output:

b) Implement the concept of producer consumer problem using thread synchronization.

class Buffer
{
int item;
boolean produced = false;
synchronized void produce(int x)
{
if(produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught");
}
}

item =x;
System.out.println("Producer - Produced-->" +item);
produced =true;
notify();
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

synchronized int consume()


{
if(!produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught " +ie);
}
}

System.out.println("Consumer - Consumed " +item);


produced = false;
notify();
return item;
}
}

class Producer extends Thread


{

Buffer b;
Producer( Buffer b)
{
this.b = b;
start();
}

public void run()


{
b.produce(10);
b.produce(20);
b.produce(30);
b.produce(40);
b.produce(50);

}
}

class Consumer extends Thread


{
Buffer b;
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
Consumer(Buffer b)
{
this.b = b;
start();
}

public void run()


{

b.consume();
b.consume();
b.consume();
b.consume();

}
}

public class PCDemo


{
public static void main(String args[])
{
Buffer b = new Buffer(); //Synchronized Object
new Producer(b);
new Consumer(b);
}
}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-9
Objective: After the completion of the practice session, the student will be able toimplement Collection
Frameworks to retrieve data.
a) Use an ArrayList to manage Employee objects for insertion, display and remove.

import java.util.*;
class Employee
{
int eid;
String ename;
double sal;

public Employee(int x, String y, double z)


{
eid=x;
ename=y;
sal = z;
}
}

public class EmpArrayList


{
public static void main(String[] args)
{
ArrayList<Employee> list =new ArrayList<Employee>();
//Creating Employees
Employ e1=new Employee(101,"A.Harsha",75000.50);
Employee e2=new Employee(102,"B.Varsha",85000.50);
Employee e3=new Employee(103,"C.Sirisha",95000.50);
Employee e4=new Employee(104,"D.Sandeep",195000.50); //Adding
Employees to list
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);

//Displaying Number of Employees


System.out.println("\n The number of employees is ->" +list.size());

//Displaying Details of Employees


System.out.println("\n The employess data is \n");
for(Employee e:list)
{
System.out.println(e.eid+":"+e.ename+":"+e.sal);
System.out.println();
}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
//Deleting an Employee
list.remove(2);
System.out.println("\n After removing number of employees are ->" + list.size());
//Displaying Details of Employees
System.out.println("\n The employess data after removing is \n");
for(Employee e:list)
{
System.out.println(e.eid+":"+e.ename+":"+e.sal);
System.out.println();
}
}
}
Output:

b) Use HashSet methods to perform operations on collection of data.

import java.util.*;
class HashDemo
{
public static void main(String args[])
{
//Creating HashSet
HashSet<String> set=new HashSet<String>();

//Adding Elements to HashSet - ignores duplicates


set.add("hyderabad");
set.add("hyderabad");
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
set.add("bangalore");
set.add("chennai");
set.add("kolkata");
set.add("kolkata");
set.add("pune");

Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}

//Removing specific element from HashSet


set.remove("hyderabad");
//Displaying set
System.out.println("\n The list after remove ->" +set);

//adding another set


HashSet<String> set1=new HashSet<String>();
set1.add("Panjab");
set1.add("Delhi");
set.addAll(set1);
System.out.println("\n Updated List is -> "+set);
//removing new set from list
set.removeAll(set1);
System.out.println("\n Updated List is -> "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("\n After clear the set is -> "+set);

}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
WEEK-10

Objective: After the completion of the practice session, the student will be able to implement Collection
Frameworks to retrieve data.
a) Implement MouseListener and MouseMotionListener.

import java.awt.*;
import java.awt.event.*;

public class MouseDemo extends Frame implements MouseListener,MouseMotionListener


{

int x=0, y=0;


String msg= "";

MouseDemo(String title)
{
super(title);
addMouseListener(this);
addMouseMotionListener(this);
setSize(500,500);
setVisible(true);
//window close
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
} );

public void mouseClicked(MouseEvent e)


{

msg= "MouseClicked";
x = e.getX();
y = e.getY();
repaint();
}

public void mousePressed(MouseEvent e)


{
msg= "MousePressed";
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
x = e.getX();
y = e.getY();
repaint();

public void mouseReleased(MouseEvent e)


{
msg = "MouseReleased";
x = e.getX();
y = e.getY();
repaint();

public void mouseEntered(MouseEvent e)


{
msg= "MouseEntered";
x = e.getX();
y = e.getY();
repaint();

public void mouseExited(MouseEvent e)


{
msg= "MouseExited";
x = e.getX();
y = e.getY();
repaint();
}

public void mouseMoved(MouseEvent e)


{
msg= "*";
x = e.getX();
y = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)


{
msg= "#";
x = e.getX();
y = e.getY();
repaint();
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
}

public void paint(Graphics g)


{
g.drawString(msg + " at " + x + "," + y, 100,50);
}

public static void main(String[] args)


{

MouseDemo f = new MouseDemo("Mouse Events Handling");


}

Output:

b) Implement KeyListener to handle key events.


import java.awt.*;
import java.awt.event.*;
public class KeyDemo extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyDemo()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
area.addKeyListener(this);

add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}

public void keyPressed(KeyEvent e)


{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}

public void keyTyped(KeyEvent e)


{
l.setText("Key Typed");
}

public static void main(String[] args)


{
new KeyDemo();
}
}
Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

WEEK-11

Objective: After the completion of the practice session, the student will be able to Develop GUI
applications using AWT.

a) Create a Simple login window to validate a user with name and password.
import java.awt.*;
import java.awt.event.*;
public class LoginDemo extends Frame implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2;
Button b1;
LoginDemo(String name)
{
super(name);
l1=new Label("User Name");
l1.setBounds(20,50,100,20);
//x,y -> top left point , width,height are dimensions
l2=new Label("Password");
l2.setBounds(20,100,100,20);

t1= new TextField();


t1.setBounds(130,50,100,20);

t2= new TextField();


t2.setBounds(130,100,100,20);
t2.setEchoChar('*');

b1= new Button("login");


(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
b1.setBounds(80,150,80,20);

l3 = new Label("->");
l3.setBounds(80,200,200,20);
add(l1);add(t1);
add(l2);add(t2);
add(b1);add(l3);

b1.addActionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}});

}
public void actionPerformed(ActionEvent e)
{
String uname = t1.getText();
String pwd = t2.getText();

if(uname.equals("vce") && pwd.equals("root"))


l3.setText("Welcome to VCE");
else
l3.setText("Invalid Username or Password");
}

public static void main(String[] args)


{
new LoginDemo("Login Window");
}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

b) Using Grid Layout design a Simple calculator with appropriate event handling.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

//<applet code = "CalsiDemo.class" width = 350 height = 350></applet>

public class CalsiDemo extends Applet implements ActionListener


{
TextField t1;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,mul,div, eql,clr,rem;
String msg="",tmp;
int a, b;
public void init()
{
Color c1 = new Color(100,250,100);
setBackground(c1);

GridLayout gl= new GridLayout(5,4,8,8);


setLayout(gl);
t1=new TextField();
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
b0=new Button("0");
add=new Button("+");
sub=new Button("-");
div=new Button("/");
mul=new Button("*");
eql=new Button("=");
clr = new Button("C");
rem = new Button("%");

add(b7);
add(b8);
add(b9);
add(t1);
add(b4);
add(b5);
add(b6);
add(mul);

add(b1);
add(b2);
add(b3);
add(sub);
add(b0);
add(eql);
add(add);
add(div);
//t1.setBounds(30,30,200,40);
add(clr);
add(rem);

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
div.addActionListener(this);
mul.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eql.addActionListener(this);
clr.addActionListener(this);
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
rem.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();
if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/") || str.equals("%"))
{
String str1 = t1.getText();
tmp=str;
a = Integer.parseInt(str1);
msg="";
}
else if(str.equals("="))
{
String str2 = t1.getText();
b = Integer.parseInt(str2);
int sum=0;
if(tmp=="+")
sum=a+b;
else if(tmp=="-")
sum=a-b;
else if(tmp=="*")
sum=a*b;
else if(tmp=="/")
sum=a/b;
else if(tmp=="%")
sum=a%b;
else
sum=0;
//String s=String.valueOf(sum); //Converts value to string
t1.setText(""+sum);
msg="";
}
else if(str=="C")
{
t1.setText("");
}
else
{
msg+=str;
t1.setText(""+msg);
}
}

}
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

Output:

WEEK-12

Objective: After the completion of the practice session, the student will be able to Develop GUI
applications using Swing Controls.

a) Create a user interface to insert employee details, Display the data in Text area.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class EmpDemo implements ActionListener


{
String data="EMP:" ;
JFrame jf;
JPanel jp;
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3;
JRadioButton r1,r2;
ButtonGroup bg;
JComboBox jc;
JCheckBox c1,c2,c3;
JButton b1;
JTextArea ta1;
String cities[] = {"HYD", "BNGL","PUNE","DELHI"};

EmpDemo( )
{
jf = new JFrame( ); //Top or High Level Window
jf.setSize(300,300);
jf.setTitle("Demo");
jp = new JPanel(); // lower or second level window

l1 = new JLabel("EMP-ID");

l2 = new JLabel("EMP-NAME");

l3 = new JLabel("Designation");

l4 = new JLabel("Gender");

l5 = new JLabel("CITY");

l6= new JLabel("COMPANY");

t1= new JTextField(30);

t2= new JTextField(30);

t3= new JTextField(30);

r1= new JRadioButton("Male");

r2= new JRadioButton("FeMale");

bg = new ButtonGroup();

bg.add(r1);
bg.add(r2);
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
jc = new JComboBox(cities);

c1= new JCheckBox("Apple");

c2= new JCheckBox("Google");

c3= new JCheckBox("Microsoft");

b1 = new JButton("Submit");

ta1 = new JTextArea(30,10);

jf.setLayout(new GridLayout(5,4));

jp.add(l1); jp.add(t1);
jp.add(l2); jp.add(t2);
jp.add(l3); jp.add(t3);
jp.add(l4); jp.add(r1);jp.add(r2);
jp.add(l5); jp.add(jc);

jp.add(l6); jp.add(c1); jp.add(c2); jp.add(c3);


jp.add(b1); jp.add(ta1);

jf.add(jp);
jf.setSize(1000,600);
jf.setVisible(true);
b1.addActionListener (this);

public void actionPerformed(ActionEvent e)


{
data= data + t1.getText() + ":";
data= data + t2.getText() + ":";
data= data + t3.getText() + ":";

if(r1.isSelected())
data= data+ "Male" +";";
else
data= data+ "FeMale" +";";

String str = (String) jc.getSelectedItem();

data = data + str + ":";


(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
if(c1.isSelected())
data= data + c1.getText();
else if(c2.isSelected())
data=data +c2.getText();
else
data=data+c3.getText();

ta1.setText(data);

}
public static void main(String args[])
{
new EmpDemo();
}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

b) Create a JTable to display various fields of Student data like RollNo, Name, Branch
,Year, Percentage etc.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/* import javax.swing.*/

public class JStudent


{

JFrame f;
JTable j;

JStudent()
{

f = new JFrame();

f.setTitle("JTable Example");

String[][] data = {
{ "101", "Rajesh", "CSE","II","78.5"},
{ "102", "Harsha", "CSE","II","87.5"},
{ "103", "Varsha", "CSE","II","65.5"},
{ "104", "Kiran", "IT","II","75.5"},
{ "105", "Karan", "IT","II","87.5"},
};
// Column Names
String[] head = { "RollNo", "Name", "Department","Branch" , "Percentage"};

// Initializing the JTable


j = new JTable(data, head);
j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
f.setSize(500, 200);

f.setVisible(true);
}

public static void main(String[] args)


{
new JStudent();
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
}
}

Output:
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

PART-3

ONLINE RESOURCES

OBJECTIVE

To help students on acquiring more practice on the course using various online resources

DESCRIPTION

These open tools form an excellent practice platform for the students, which he can explore anytime
from anywhere. The links of the websites providing OOP tutorials are given. Students are needed to
explore the websites.

LINKS

1. https://www.geeksforgeeks.org/java/
2. https://www.tutorialspoint.com/java/java_tutorial.pdf
3. https://www.pdfdrive.com/java-tutorial-e19074086.html
4. https://www.tutorialspoint.com/java/index.htm
5. https://www.tutorialspoint.com/java/index.htm
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

PART-4

POSSIBLE VIVA QUESTIONS

POSSIBLE VIVA QUESTIONS

Description

Possible viva questions include answers are provided. The student can have a practice of them.

What is the range of the random number r generated by the code below?
1
int r = (int)(Math.floor(Math.random() * 8)) + 2;

Ans 2 <= r <= 9


What is the value of y when the code below is executed?
2 int x = 4;
int y = (int)Math.ceil(x % 5 + x / 5.0);
Ans. 5
String str = "P";
3 System.out.print(str.length() + "80");
s what is the output of this cone snippet?
Ans. 180
What is the value of ’n’ after executing the following code?
int n = 20;
switch(n)
{
case 10: n = n + 1;
4
case 15: n = n + 2;
case 20: n = n + 3;
case 25: n = n + 4;
case 30: n = n + 5;
}
Ans. 32
What will be printed by the code fragment below?
double height = 5.5;
5
if(height-- >= 5.0)
System.out.print("tall ");
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
if(--height >= 4.0)
System.out.print("average ");
if(height-- >= 3.0)
System.out.print("short ");
else
System.out.print("very short ");
Ans. Tall short
What will be the output of the program?
public class CommandArgsThree
{ public static void main(String args[])
{
String [][] argCopy = new String[2][2];
int x;
argCopy[0] = args;
x = argCopy[0].length;
6
for (int y = 0; y < x; y++)
{
System.out.print(" " + argCopy[0][y]);
}
}
}
and the command-line invocation is
> java CommandArgsThree 1 2 3
Ans. 123

7 What is an Exception in java?


An Exception is a failure condition that occurs during the execution of a program and
Ans. disrupts the normal flow of the program. It has to be handled properly, failing which
program will be terminated abruptly.
8 How the exceptions are handled in java?
Exceptions handling can be done using try, catch and finally blocks.
try : The code or set of statements that may raise exception should be try block.
Ans. catch : This block catches the exceptions thrown in the try block.
finally : This block of code is always executed whether an exception has occurred in the
try block or not except in one scenario explained in below question.
9 Is finally block always get executed in the java program?
finally block is always executed but there is one scenario when finally block does not
execute.
Ans. By using System.exit(0) in the try or catch block, results in finally block does not
execute. The reason is System.exit(0) line terminates the running java virtual machine.
Termination leads to no more execution of the program.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
10 What are the differences between Error and Exception in java?
Errors are caused by the JVM environment in which the application is running.
Example: OutOfMemoryError while Exceptions are caused by the application itself.
Ans. Example:NullPointerException.
b. Errors can only occur at runtime while Exceptions can occur at compile time or
runtime. You can find more differences between Error and Exception
11 What statements can exist in between try, catch and finally blocks?

No, try, catch and finally forms a single unit and no other statements should exist in
Ans.
between try, catch and finally blocks.

What are Checked and Unchecked exceptions in java?


Exceptions which are known to the compiler are called Checked exceptions. Checked
exceptions are checked at compile-time only.
Ans. Unchecked exceptions occur only at run time. Unchecked exceptions are also called as
run time exceptions. All subclasses of java.lang.RuntimeException and java.lang.Error
is of Unchecked type.
12 What is the difference between Checked and Unchecked exceptions in java?
This is one of the most popular interview questions for java developers. Make sure this
question is in your to-do list before appearing for the interview.
Main differences between Checked and Unchecked exceptions are:
Ans. a. Checked exceptions are checked at compile time while Unchecked exceptions are
checked at run time.
b. Checked exceptions must be handled by try/catch block or throws keyword while
Unchecked exceptions are not necessary to handle.
13 What is the difference between final, finally and finalize in java?
Final: By declaring a variable as final, the value of final variable cannot be changed.
By declaring a method as final, method cannot be overridden.
By declaring a class as final, class cannot be extended.
Ans. finally:Used after try or try-catch block, will get executed after the try and catch blocks
without considering whether an exception is thrown or not.
finalize:Finalize method is the method that Garbage Collector always calls just before
the deletion/destroying the object which is no longer in use in the code.
14 What is RuntimeException in java. Give example?
The exceptions which occur at runtime are called as RuntimeException. These
exceptions are unknown to the compiler. All subclasses of java.lang.RuntimeException
Ans. are RuntimeExceptions.
Example:NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException etc.
What is the difference between ClassNotFoundException and NoClassDefFoundError
15
in java?
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
This question is important because very few Java developers are aware of the
difference between ClassNotFoundException and NoClassDefFoundError.
ClassNotFoundException:
An exception that occurs when you try to load a class at run time using Class.forName()
Ans. or loadClass() methods and mentioned classes are not found in the classpath is called
ClassNotFoundException.
NoClassDefFoundError:
An exception that occurs when a particular class is present at compile-time but was
missing at run time is called NoClassDefFoundError.
16 What is the use of throws keyword in java?

Ans. throws keyword is used to declare an exception. You can find a detailed explanation

Why it is always recommended that clean up activities like closing the DB connections
and I/O resources to keep inside a finally block?
finally block will always be executed by ensuring the cleanup operations in finally
Ans. block, you will assure that those operations will be always executed irrespective of
whether an exception has occurred or not.
17 What is OutOfMemoryError in Exception Handling?

OutOfMemoryError is the subclass of java.lang.Error. It occurs when JVM runs out of


Ans.
memory.

What is ClassCastException in Exception Handling?

RunTimeException which occurs when JVM not able to cast an object of one type to
Ans.
another type is called ClassCastException.

18 What is the difference between throws and throw in java?


This is one of the most frequently asked interview questions for java developers.
Main differences between throws and throw are: a. throws keyword is used when
writing methods, to declare that the method in question throws the specified (checked)
Ans.
exception.
throw is used when an instruction is to explicitly throw the exception.
b. throws is used with a method signature while the throw is used inside a method.
19 What is StackOverflowError in Exception Handling?

Ans. StackOverflowError is thrown by the JVM when stack overflows in a program.

Which class is the root class for all types of errors and exceptions in Exception
20
Hierarchy?

Ans. java.lang.Throwable is the superclass for all types of errors and exceptions in java.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
21 When do we use printStackTrace() method in java?

printStackTrace() function is used to print the detailed information about the


Ans.
exception thrown by the try/catch block.

22 Give some examples of Checked exceptions?

Ans SQLException, ClassNotFoundException, IOException

23 Give some examples of Unchecked exceptions?


ArrayIndexOutOfBoundsException,
Ans NullPointerException,
NumberFormatException
24 List the Methods in the Throwable class?
Below are the important methods of Throwable class:
• getMessage()
• getCause()
Ans.
• toString()
• printStackTrace()
• StackTraceElement [] getStackTrace()
25 What is a SQLException in Exception Handling?

An exception that provides information related to database access error or other


Ans.
errors is called SQL Exception.

26 What is NumberFormatException in java?

Ans. NumberFormatException is thrown when you try to convert a String into a number.

What is ArrayIndexOutOfBoundsException in java?

ArrayIndexOutOfBoundsException arises while trying to access an index of the array


Ans.
that does not exist or out of the bound of this array.

27 What will happen if an exception is thrown by the main method?

When an exception is thrown by the main method then JVM terminates the program.
Ans.
As a result, you will find the exception message and stack trace in the system console.

28 What is multithreading?
Multithreading is a process of executing multiple threads simultaneously.
Multithreading is used to obtain the multitasking. It consumes less memory and gives
Ans.
the fast and efficient performance. Its main advantages are:
 Threads share the same address space.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
 The thread is lightweight.
 The cost of communication between the processes is low.

29 What is the thread?


A thread is a lightweight sub process. It is a separate path of execution because each
Ans. thread runs in a different stack frame. A process may contain multiple threads. Threads
share the process resources, but still, they execute independently.
30 Differentiate between process and thread?
There are the following differences between the process and thread.
 A Program in the execution is called the process whereas; A thread is a subset
of the process
 Processes are independent whereas threads are the subset of process.
 Process have different address space in memory, while threads contain a
Ans. shared address space.
 Context switching is faster between the threads as compared to processes.
 Inter-process communication is slower and expensive than inter-thread
communication.
 Any change in Parent process doesn't affect the child process whereas changes
in parent thread can affect the child thread.
31 What do you understand by inter-thread communication?
 The process of communication between synchronized threads is termed as
inter-thread communication.
 Inter-thread communication is used to avoid thread polling in Java.
Ans.
 The thread is paused running in its critical section, and another thread is
allowed to enter (or lock) in the same critical section to be executed.
 It can be obtained by wait(), notify(), and notifyAll() methods.
32 What is the purpose of wait() method in Java?
The wait() method is provided by the Object class in Java. This method is used for
inter-thread communication in Java. The java.lang.Object.wait() is used to pause the
Ans. current thread, and wait until another thread does not call the notify() or notifyAll()
method. Its syntax is given below.
public final void wait()
33 Why must wait () method be called from the synchronized block?
We must call the wait method otherwise it will throw
java.lang.IllegalMonitorStateException exception. Moreover, we need wait() method
Ans.
for inter-thread communication with notify() and notify All(). Therefore It must be
present in the synchronized block for the proper and correct communication.
34 What are the advantages of multithreading?

Multithreading programming has the following advantages:


Ans.
 Multithreading allows an application/program to be always reactive for input,
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
even already running with some background tasks
 Multithreading allows the faster execution of tasks, as threads execute
independently.
 Multithreading provides better utilization of cache memory as threads share
the common memory resources.
Multithreading reduces the number of the required server as one server can execute
multiple threads at a time.
35 What are the states in the lifecycle of a Thread?
A thread can have one of the following states during its lifetime:
1. New: In this state, a Thread class object is created using a new operator, but the
thread is not alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start()
method. However, the thread is not yet selected by the thread scheduler.
Ans 3. Running: In this state, the thread scheduler picks the thread from the ready
state, and the thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is
waiting for the other thread to finish.
Dead/Terminated: A thread is in terminated or dead state when the run() method
exits.
36 What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time
Ans slicing, a task executes for a predefined slice of time and then reenters the pool of
ready tasks. The scheduler then determines which task should execute next, based on
priority and other factors
37 What is context switching?
In Context switching the state of the process (or thread) is stored so that it can be
Ans. restored and execution can be resumed from the same point later. Context switching
enables the multiple processes to share the same CPU.
38 Differentiate between the Thread class and Runnable interface for creating a Thread?
The Thread can be created by using two ways.
 By extending the Thread class
 By implementing the Thread class
However, the primary differences between both the ways are given below:
 By extending the Thread class, we cannot extend any other class, as Java does
not allow multiple inheritances while implementing the Runnable interface; we
Ans.
can also extend other base class(if required).
 By extending the Thread class, each of thread creates the unique object and
associates with it while implementing the Runnable interface; multiple threads
share the same object
Thread class provides various inbuilt methods such as getPriority(), isAlive and many
more while the Runnable interface provides a single method, i.e., run().
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
39 What does join() method?
The join() method waits for a thread to 1) The wait() method is defined in Object class.
The sleep() method is defined in Thread class.
2) The wait() method releases the lock.
The sleep() method doesn't release the lock.
When we call the sleep() method, it pauses the execution of the current thread for the
given time and gives priority to another thread(if available). Moreover, when the
waiting time completed then again previous thread changes its state from waiting to
runnable and comes in running state, and the whole process works so on till the
execution doesn't complete.
 public static void sleep(long milliseconds)throws InterruptedException
 public static void sleep(long milliseconds, int nanos)throws
Ans.
InterruptedException
The sleep() method in java is used to block a thread for a particular time, which means
it pause the execution of a thread for a specific time. There are two methods of doing so
completes its task. Join method is overloaded in Thread class in the following ways.
 public void join()throws InterruptedException
 public void join(long milliseconds)throws InterruptedException
die. In other words, it causes the currently running threads to stop executing until the
thread it joins with completes its task. Join method is overloaded in Thread class in the
following ways.
 public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
40 Describe the purpose and working of sleep() method?
 The sleep() method in java is used to block a thread for a particular time, which
means it pause the execution of a thread for a specific time. There are two
methods of doing so.
Ans.
Syntax:
 public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos)throws InterruptedException
41 Describe working of sleep() method?
When we call the sleep() method, it pauses the execution of the current thread for the
given time and gives priority to another thread(if available). Moreover, when the
Ans. waiting time completed then again previous thread changes its state from waiting to
runnable and comes in running state, and the whole process works so on till the
execution doesn't complete.
42 What is the difference between wait() and sleep() method?
The wait() method is defined in Object class. The wait() method releases the lock
Ans. The sleep() method is defined in Thread class, The sleep() method doesn't release the
lock.
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)

PART-5

KNOWLEDGE BASE

Description

Knowledge basncludes possible viva questions whose answers are not provided. The student has to
explore for the answers.

POSSIBLE VIVA QUESTIONS (WITHOUT ANSWERS)

1. What is the order of the three top level elements of the java source file?
2. What are the states associated with the thread?

3. Discuss a Thread Life Cycle?


4. What are the thread states?

5. What are the major differences between Thread and Process?

6. What do you mean by thread starvation?

7. What is context-switching in multi-threading?

8. What happens if we don’t override a run method?


9. What is the major difference between Thread.start() & Thread?run() method?

10. How to create a thread in java?

11. What is the meaning of Thread Priority?

12. What join() method does?

13. How can you share data between two thread in Java?
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
14. How can multiple threads be controlled simultaneously?

15. What is a blocking method in Java?

16. What is the main difference between wait () and sleep () method?

17. What is an immutable object? How can it help in writing a concurrent application?
18. What is ThreadPool?

19. What is the use of Synchronized keyword?

20. What are the main differences between notify and notifyAll in Java?

21. Can you start a thread twice in Java?


22. When can we say that threads are not lightweight process in java?
23. Can It is possible to synchronize the constructor of a Java Class?

24. What is transient variable?

25. What is a volatile keyword?

26. Why thread is soo called as light weight Process?

27. What is Exception in Java?


28. What are the Exception Handling Keywords in Java?
29. Can we have a try block without a catch?
30. Difference between Error and Exception in Java?

31. Does finally runs always? On which case finally doesn't run?

32. What is difference between final, finally and finalize in Java?

33. What are different scenarios causing “Exception in thread main”?


34. What is difference between throw and throws keyword in Java?

35. Explain Java Exception Hierarchy?

36. What are important methods of Java Exception Class?


37. Explain Java multi-catch block?

38. What is difference between Checked and Unchecked Exception in Java?

39. How to compare two Strings in java program?


40. Why String is immutable?
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
41. How do you check if two Strings are equal in Java?

42. Write a method that will remove given character from the String?

43. What is the difference between an argument and a parameter?

44. What is the difference between this () and super ()?


45. What is the difference between constructor and method?

46. What are methods and how are they defined?-

47. What are the different scopes for Java variables?

48. How to Split String in java?


49. Can we use String in switch case?
50. What are different ways to create String Object?

51. What is the first argument of the String array in main method?

52. Can main method be declared final?

53. What is a constructor?

54. What is the difference between constructor and method?


55. What is constructor overloading and Method Overloading?
56. What is the Command to execute a compiled java program?
57. What is the order of the three top level elements of the java source file?

58. The minimum value of char type variable is------

59. When Widening conversion is possible in java

60. How do you create array of objects?


61. What is inheritance?

62. What are the types of inheritance?

63. What do you mean by abstract method and abstract class?


64. What is the difference between abstract class and interface?

65. Can you have an inner class inside a method and what variables can you access?-

66. Can a abstract class be declared final?


67. Can a method inside a Interface be declared as final?
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
68. Can a Class extend more than one Class?

69. Can a abstract class be defined without any abstract methods?


If the class that implements an interface doesn’t override all the methods then can
70.
we access the class?
71. Can you declare a non final variable in an interface?
72. Can an interface be final?

73. Multiple-inheritance is possible through interfaces in java. Justify.

74. Can you instantiate an interface?


75. What are the advantages of using exception handling?

76. How to create custom exceptions?


77. If I want an object of my class to be thrown as an exception object, what should I do?

78. Is it necessary that each try block must be followed by a catch block?
79. If I write return at the end of the try block, will the finally block still execute?

80. What is the type of argument that the sleep() method of Thread class takes.
81. What type of Exception is thrown by Thread.sleep()?

82. Different methods of Object class?

83. What is daemon thread and which method is used to create the daemon thread?-
84. What is use of assigning priority to a thread?

85. What is the default priority number assigned to main thread?

86. What is Serialization and deserialization?


87. What is source and listener?

88. What are the advantages of the model over the event-inheritance model?
89. What is source and listener?

90. What is meant by controls and what are different types of controls in AWT?

91. What is meant by controls and what are different types of controls in AWT?
92. What is the difference between choice and list?
What is a layout manger and what are different types of layout managers available
93.
in java AWT?
94. How are the elements of different layouts organized?
(AUTONOMOUS)
Affiliated to JNTUH, Approved by AICTE, Accredited by NAAC with A++ Grade, ISO
9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(DATA SCIENCE)
95. Which containers use a Border layout as their default layout?

96. What is difference between Swing and AWT in Java?

97. What is difference between paint and repaint in Java Swing?

98. What is difference between Container and Component ?


99. What is difference between BorderLayout and GridLayout ?

100. Why Swing is called light weight ?

101. Is Swing Thread safe in Java?

102. Explain about different layout mangers?


103. Explain the swing delegation event model?
104. What is the difference between applications and applets?

105. How does applet recognize the height and width?

106. When do you use codebase in applet?

107. What is the lifecycle of an applet?

108. How do you set security in applets?


109. What are the attributes of Applet tags? Explain the purposes.
What are the methods that control an applet’s on-screen appearance? I.e. update
110.
and paint?

You might also like