Uploaded by Dr. Prakash Kumar Sarangi

OOPS LAB MANNUAL

advertisement
VARDHAMAN COLLEGE OF ENGINEERING
(AUTONOMOUS)
Affiliated to JNTUH, approved by AICTE, Accredited by NAAC with A++ Grade
ISO 9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
Laboratory Manual
Object Oriented Programming
(II B. Tech- I SEMESTER)
(VCE-R22)
Course Code-A8602
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (AI & ML)
VARDHAMAN COLLEGE OF ENGINEERING
(AUTONOMOUS)
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
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.
COURSE OVERVIEW:
This 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 frontend 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 Implement Object Oriented Programming Principles for a given problem.
A8602.2 Write Programs using exception handling and multi-threading to achieve robustness.
A8602.3 Make use of collections framework for organizing data.
A8602.4 Design GUI using swing for a given real time problem.
BLOOM’S LEVEL OF THE COURSE OUTCOMES
CO#
Remember
(L1)
Understand
(L2)
Bloom’s Level
Apply
Analyze
(L3)
(L4)
A8602.1
✔
A8602.2
✔
A8602.3
✔
A8602.4
✔
Evaluate
(L5)
Create
(L6)
A8602.3
A8602.4
PO12
PO11
PO10
2
2
3
2
2
2
3
2
2
2
Note: 1-Low, 2-Medium, 3-High
PO9
2
PO8
3
PO7
2
PO6
2
PO5
2
PO4
2
PO3
PSO2
A8602.2
PSO1
A8602.1
PO2
CO#/
POs
PO1
COURSE ARTICULATION MATRIX
LIST OF PROGRAMS FOR PRACTICE:
No
1
2
Title of the Experiment
Program using Control statements:
a) Read the marks of a student in 4 subjects and
find grade.
b) Program to check a number is Armstrong or
not.
c) Program to display prime numbers from m to n.
Implement 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).
b) Create a class Account with data members
name, acno and balance. Use appropriate
methods to perform various operations like
deposit, withdraw, and balance check.
c) Create a class Student with appropriate data and
methods using constructor.
3
Implement
OOP
Second
principle
–
Polymorphism and Arrays
a) Create overloaded methods to find volume of
Sphere, Cylinder and Cone.
b) To sort given list of elements in ascending
order.
c) Read two matrices of size mxn, pxq, perform
the multiplication of matrices.
Implement Java String Class.
4
Tools and Techniques
a. Check a string is palindrome or not.
b. Given a string and an integer 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", 1) → "o"
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).
Expected
Skills/Ability
Apply OOP
principles to
solve problems
Implement
Encapsulation
Open source Java Tool
kit: JDK 8 and above
versions,
Open Source IDE:
Eclipse / NetBeans
Implement
Polymorphism
OS: Windows / Linux
Web browser: Internet
Explorer/ Google/
Firefox
Use String class
to handle
strings.
No
Title of the Experiment
Tools and Techniques
Expected
Skills/Ability
Implement OOP Third principle – Inheritance.
5
6
7
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.
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).
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 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 throw a Number
Format Exception if Num1 or Num2 cannot be
converted to integers and If Num2 is Zero throw
an Arithmetic Exception. Display the exception
message.
b) In the CustomExceptionTestclass, 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.
Implement
Inheritance
Build Packages
and Interfaces
For reusability
Handle
Runtime Errors
No
8
Title of the Experiment
Develop
applications
on
Multithreaded
Programming
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.
b) Write a program to implement thread
synchronization using synchronized block and
synchronized method.
Tools and Techniques
Expected
Skills/Ability
Perform
Multitasking
Using threads
c) Implement the concept of Bounded Buffer problem
using Inter thread communication.
9
Implement Collection Frameworks
a) Use an ArrayList to manage Employee objects
for insertion, display and remove.
b) Use HashSet to organize list of products and
perform operations on them.
Implement
Collections
Framework
10
Implement Collection Frameworks
a) Use a HashMap to access student names using
roll number. Perform insert, delete and update
operations using rollno.
b) Use Arrays class to perform the manipulation
on array.
Implement
Collections
Framework
11
Implement Mouse and Key events.
a)
Implement
MouseListener
and
MouseMotionListener to handle various mouse
events.
b) Implement KeyListener to handle key events.
Handle Events
using
Delegation
Event Model
Develop GUI applications using Swing Controls.
a) Create a Simple login window to validate a user
with name and password.
b) Using CardLayout design a user interface to
access the Programs and Courses offered
by the College and use appropriate event
handling.
Develop GUI applications using Swing Controls.
Develop GUI
applications
using Swings
12
13
a) Create a user interface to insert employee details,
Display the data in Text Area.
b) Create a JTable to display various fields of Student
data like RollNo, Name, Branch,
Year, Percentage
etc.
Develop GUI
applications
using Swings
ASSESSMENT SCHEME R22
S.NO#
1
2
EVALUATION METHOD
Continuous Internal Evaluation
(CIE)
Semester End Examination (SEE)
ASSESSMENT TOOL
A write-up on day-to-day
experiment in the laboratory
Viva-voce (or) tutorial (or) case
study (or) application (or) poster
presentation of the course
Internal practical examination
Laboratory
Project,
which
consists of the Design (or)
Software / Hardware Model
Presentation (or) App Developm
(or) Prototype Presentation
Write-up
Experiment/program
Evaluation of results
Presentation on another
experiment/program
Viva-Voce
Max. Marks
Marks
Total
10
10
10
40
10
10
15
15
10
10
60
LAB SESSION PLAN
No Title of the Experiment
Implement Control statements
1
CO-1
BLOOM’s
LEVEL
L-3
CO-1
L-3
CO-1
L-3
CO-1
L-3
CO-1
L-3
a) Read the marks of a student in 4 subjects and find grade.
b) Program to check a number is Armstrong or not.
c) Program to display prime numbers from m to n.
Implement OOP First principle - Encapsulation
2
CO
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).
b) Create a class Account with data members name, acno and balance.
Use appropriate methods to perform various operations like deposit,
withdraw, and balance check.
c) Create a class Student with appropriate data and methods using constructor.
Implement OOP Second principle – Polymorphism and Arrays
3
a) Create overloaded methods to find volume of Sphere, Cylinder and
Cone.
b) To sort given list of elements in ascending order.
c) Read two matrices of size mxn, pxq, perform the multiplication of
matrices.
Implement Java String Class.
4
a) Check a string is palindrome or not.
b) Given a string and an integer 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", 1) → "o"
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).
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.
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).


5
No Title of the Experiment
Implement Packages and Interfaces.
6
L-3
CO-2
L-3
CO-3
L-3
CO-3
L-3
CO-4
L-3
CO-4
L-3
CO-4
L-3
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.
b) Write a program to implement thread synchronization using
synchronized block and synchronized method.
c) Implement the concept of Bounded Buffer problem using Inter thread
communication.
Implement Collection Frameworks
9
CO-2
a) Read two integers as strings Num1 and Num2 to perform division. The
program throw a Number Format Exception if Num1 or Num2 cannot be
converted to integers and If Num2 is Zero throw an Arithmetic Exception.
Display the exception message.
b) Custom Exception handling
Develop applications on Multithreaded Programming
8
CO-1
BLOOM’s
LEVEL
L-3
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.
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.
7
CO
a) Use an ArrayList to manage Employee objects for insertion, display and
remove.
b) Use HashSet to organize list of products and perform operations on them.
Implement Collection Frameworks
10
a) Use a HashMap to access student names using roll number. Perform
insert, delete and update operations using rollno.
b) Use Arrays class to perform the manipulation on array.
Implement Mouse and Key events.
11
a) Implement MouseListener and MouseMotionListener to handle various
mouse events.
b) Implement KeyListener to handle key events.
Develop GUI applications using Swing Controls.
12
a) Create a Simple login window to validate a user with name and
password.
b) Using Card Layout design a user interface to access the Programs and
Courses offered by the College and use appropriate event handling.
Develop GUI applications using Swing Controls.
a) Create a user interface to insert employee details, Display the data in
13
Text Area.
b) Create a JTable to display various fields of Student data like RollNo,
Name, Branch, Year, Percentage etc.
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");
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();
}
}
Week-1
Program using Control statements:
a) Read the marks of a student in 4 subjects and find grade.
b) Program to check a number is Armstrong or not.
c) Program to display prime numbers from m to n.
Pre-Lab
Questions
1. What are the principles of Object Oriented Programming?
2. What is JVM? Describe the need of it.
3. Is java platform independent or not? How to Justify.
4. What are the fundamental data types supported?
5. List the various types of operators in Java.
Program Code / Snippet / Algorithm / Description
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");
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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);
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. List the various conditional statements of Java.
2. What are the various loop statements supported by java.
3. How to check a number is perfect or not?
4. Is java supports switch statement? How it differs from C.
5. How to copile and run a java file. What is the need of byte code?
Week-2
Pre-Lab
Questions
Implement 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).
b) Create a class Account with data members name, acno and balance.
Use appropriate methods to perform various operations like deposit,
withdraw, and balance check.
c) Create a class Student with appropriate data and methods using
constructor.
1. What is encapsulation?
2. Write the syntax to define a class.
3. What is the difference between class and object.
4. Why do we use new operator in Java.
5. What is constructor? Define the role of it.
Program Code / Snippet / Algorithm / Description
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");
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();
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Create a class Account with data members name, acno and balance. Use appropriate methods to
perform various operations like deposit, withdraw, and balance check.
class Account
{
int acno;
String name;
double balance;
public void setData(int x , String y , double z){
acno=x;
name=y;
balance=z;
}
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());
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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 );
}
}
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();
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How to create objects in Java?
2. Describe the various types of constructors.
3. Is Java constructor used for only initialization? Justify.
4. Define a class to describe product information.
5. Compare method and constructor.
Week-3
Pre-Lab
Questions
Implement OOP Second principle–Polymorphism and Arrays
a) Create overloaded methods to find volume of Sphere, Cylinder and
Cone.
b) To sort given list of elements in ascending order.
c) Read two matrices of size mxn, pxq, perform the multiplication of
matrices.
1. What is Polymorphism? How to achieve in Java.
2. Define method overloading.
3. Is the constructor can be overloaded or not.
4. Does java supports to overload main() method? Justify.
5. How array in Java differs from C.
Program Code / Snippet / Algorithm / Description
a) Create overloaded methods to find volume of Sphere, Cylinder and Cone.
import java.util.*;
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));
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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;
}
}
}
System.out.println(" \n The Elements After Sorting are");
for(int i=0; i< s.length;i++)
System.out.print(s[i] + " “);
}
}
{
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
c) Read two matrices of size mxn, pxq, 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];
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();
}
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How to initialize a 2-D array?
2. What are the alternative methods for array initialization.
3. Write a java program to search for an element.
4. Is implicit type promotion takes place during method overloading?
Week-4
Pre-Lab
Questions
Implement programs using Java String Class.
a) Check a string is palindrome or not.
b) Repeat End
c)Count Triplet
d) Read array of City names and Sort in dictionary order.
1. What is string in Java? How it differs from C.
2. List any 4 methods of String Class.
3. String class is defined in which package?
4. What do you mean by immutable? How it relates to String object.
5. Can we modify a string in Java? If so , how it is?
Program Code / Snippet / Algorithm / Description
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");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Given a string and a number n, return a string made of n repetitions of the last n characters of the
string.
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);
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
c) A "triple" in a string is a character appearing three times consecutively. Write a program to return
number of triples in the given string, the triples may overlap.
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);
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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++)
System.out.println(s[i]);
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How the split() method works in String class?
2. What is the return value of compareTo() method?
3. The method to display names starts with a given string.
4. How equals() method differs from ==?
5. How to create mutable strings?
6. Compare between String and StringBuffer class.
7. List any 4 methods of StringBuffer class.
8. What are the different constructors supported for String class.
Week-5
Pre-Lab
Questions
Implement OOP Third Principle-Inheritance.
1. What is inheritance? List the advantages of it.
2. The keyword used to implement inheritance in java ……
3. How many types of inheritance possible with Java?
4. Why do we need abstract class? Describe about it.
5. What is abstraction how to achieve in Java.
Program Code / Snippet / Algorithm / Description
a) Declare a class called Employee having employee-id and employee-name as members. Extend class
Employee to have a sub class called Salary having designation and monthly-salary as members.
Define the appropriate constructors and methods, use this and super keywords, display the
employees drawing salary more than 30000.
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[])
{
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();
}
}
{
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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 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);
}
}
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());
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. What is the keyword to define abstract class?
2. Is abstract class object can be created or not? Justify.
3. The abstract method implementation is responsibility of which class
4. If an abstract class is not implemented by sub class how to resolve
compile time error.
5. What is the reason for java not supporting multiple inheritance.
6. Why do we use super keyword with inheritance?
7. How the constructors are invoked in a class hierarchy.
Week-6
Pre-Lab
Questions
Implement Packages and Interfaces.
1. What is a package? What are the advantages of it?
2. The keyword used to define a package is….
3. How to achieve complete abstraction in Java? Describe it.
4. What are the keywords to define and implement interfaces.
5. By default variables in an interface are….
6. By default the methods of an interface are…
Program Code / Snippet / Algorithm / Description
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.
//Define the project structure for package execution.
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));
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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() {
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[]) {
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();
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. Access protection modifiers in java are …..
2. The keyword to access a package in java is…
3. Does package allows interfaces are or not?
4. How java achieves multiple inheritance. Describe on it.
5. Can the interface is extended or not?
6. Is interface method can have body or not?
7. How do you differentiate interface and abstract class.
Week-7
Implement Exception Handling.
Pre-Lab
Questions
1. What is an exception?
2. List the keywords in java for exception handling.
3. Why do we use finally block?
4. Does Java allows user defined exceptions.
5. Difference between run time error and logical error.
6. List any four unchecked exceptions.
Program Code / Snippet / Algorithm / Description
a) Read two integers as strings Num1 and Num2 to perform division. The program throw a Number
Format Exception if Num1 or Num2 cannot be converted to integers and If Num2 is Zero throw an
Arithmetic Exception. Display the exception message.
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");
}
System.out.println("Remaining statements");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) In the CustomExceptionTestclass, 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);
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...");
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. Can Java allows multiple catch blocks?
2. What is chained exception?
3. Differentiate between throw and throws keywords.
4. Compare checked and unchecked exceptions.
5. Why do we get null pointer exception.
6. What is the purpose of Exception class?
7. What is the super class for all exceptions in Java.
8. Describe the need of throws keyword.
Week-8
Develop applications on Multithreaded Programming.
Pre-Lab
Questions
1. List any two applications of multi-threading?
2. What are the states of thread life cycle?
3. In how many ways threads are created?
4. What is thread synchronization?
5. List any four methods of Thread class.
Program Code / Snippet / Algorithm / Description
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");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Write a program to implement thread synchronization using synchronized block and synchronized
method.
//Synchronized method
class Table
{
synchronized void printTable(int n)
{
try{
for(int i=1;i<=10;i++) {
System.out.println(n*i);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println(e);
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t) {
this.t=t;
}
public void run() {
t.printTable(8);
}
}
class MyThread2 extends Thread
Table t;
MyThread2(Table t) {
this.t=t;
}
public void run() {
t.printTable(9);
}
}
{
public class SyncDemo1 {
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
//Synchronized block
class Table {
void printTable(int n)
{
System.out.println("*****Hello -not synched");
//synchronized block
synchronized(this) {
for(int i=1;i<=10;i++) {
System.out.println(n*i);
try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e);
}
}
} //end of sync block
System.out.println("Hello -not synched");
} //end of the method
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run() {
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run() {
t.printTable(100);
}
}
public class SyncDemo2 {
public static void main(String args[]) {
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
c) Implement the concept of Bounded Buffer problem using Inter thread communication. (ProducerConsumer Problem).
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();
}
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;
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);
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How to assign priority to a thread?
2. What is the difference between synchronized block and methods?
3. The methods used for Inter thread communication are ….
4. wait() and notify() are defined in which class?
5. after sleep time out, thread moves to which state?
Week-9
Pre-Lab
Questions
Implement Collection Framework
1. Which package defines packages in Java?
2. What is the top of collections hierarchy?
3. Differences between List and Set?
4. List any four methods of Collection interface.
5. Which class does not allow duplicates in a list?
Program Code / Snippet / Algorithm / Description
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();
}
//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();
}
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Use HashSet to organize list of products and perform operations on them.
import java.util.*;
class Product {
int pid;
String pname;
double price;
public Product(int pid, String pname, double price) {
this.pid = pid;
this.pname = pname;
this.price = price;
}
}
public class HashSetDemo {
public static void main(String[] args) {
HashSet<Product> set=new HashSet<Product>();
//Creating Products
Product p1 = new Product(1010,"Mobile",12345.75);
Product p2 = new Product(1012,"Watch", 2345.75);
Product p3 = new Product(1013,"wallet",345.75);
//Adding Books to HashSet
set.add(p1);
set.add(p2);
set.add(p3);
//Accessing HashSet
System.out.println("The Products list is");
for(Product p :set){
System.out.println(p.pid+" "+p.pname+" "+p.price);
}
set.remove(p2);
System.out.println("The Products list after remove");
for(Product p :set){
System.out.println(p.pid+" "+p.pname+" "+p.price);
}
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How to differentiate ArrayList and HashSet?
2. The insertion order is maintained in which collection?
3. The collection in which the elements are not accessed using index is.
4. What is an iterator? How to use it.
5. Does collections allow user defined types as elements?
Week-10
Pre-Lab
Questions
Implement Collection Framework
1. How the HashMap differs from other collection classes?
2. What are the methods defined in Arrays class?
3. Arrays class defined in ….. package.
4. List any four methods of HashMap.
Program Code / Snippet / Algorithm / Description
a) Use a HashMap to access student names using roll number. Perform insert, delete and update
operations using rollno.
import java.util.HashMap;
public class MapDemo{
public static void main(String[] args)
{
HashMap<Integer, String> map = new HashMap<>();
// Adding elements to the Map
// using standard put() method
map.put(101,"vishal");
map.put(301,"sachin");
map.put(201,"vaibhav");
// Print size and content of the Map
System.out.println("Size of map is "+map.size());
// Printing elements in object of Map
System.out.println(map);
if (map.containsKey(301)) {
// Mapping
String name = map.get(301);
// Printing value for the corresponding key
System.out.println("value for key is " +name);
map.remove(301);
System.out.println(map);
}
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Use Arrays class to perform the manipulation on array.
import java.util.Arrays;
public class ArrDemo {
public static void main(String[] args) {
int intArr[] = { 10, 20, 15, 22, 35 };
Arrays.sort(intArr);
int key = 22;
System.out.println(key + " found at index = " + Arrays.binarySearch(intArr, key));
int intArr1[] = { 10, 20, 15, 22, 35 };
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. What are the applications of HashMap?
2. Is Arrays class defines all static methods?
3. Why to collections are Generic?
Week-11
Pre-Lab
Questions
Implement Mouse and Key events.
1. What is delegation event model?
2. List any four sources of events.
3. What is a Listener? Why it is required in Event handling?
4. List any four event classes.
Program Code / Snippet / Algorithm / Description
a) Implement MouseListener and MouseMotionListener to handle various mouse events.
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);
}
public void mouseClicked(MouseEvent e)
{
msg= "MouseClicked";
x = e.getX();
y = e.getY();
repaint();
}
public void mousePressed(MouseEvent e)
{
msg= "MousePressed";
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();
}
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");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
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);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
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();
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. What are the methods defined in MouseListener?
2. What is the argument for keyTyped() method?
3. List the event classes for mouse and key events.
4. Why do we use setBounds() method on GUI.
Week-12
Pre-Lab
Questions
Develop GUI applications using Swings.
1. List any four components in swing.
2. What is the package for swings and its awt?
3. Difference between JCheckBox and JRadioButton.
4. How Radio buttons are added to added to GUI?
5. JScrollPane is used for……...
6. Difference between JList and JComboBox.
Program Code / Snippet / Algorithm / Description
a) Create a Simple login window to validate a user with name and password.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class LoginDemo extends JFrame implements ActionListener {
JLabel l1,l2,l3;
JTextField t1,t2;
JButton b1;
LoginDemo(String name) {
super(name);
l1=new JLabel("User Name");
l1.setBounds(20,50,100,20);
//x,y -> top left point , width,height are dimensions
l2=new JLabel("Password");
l2.setBounds(20,100,100,20);
t1= new JTextField();
t1.setBounds(130,50,100,20);
t2= new JTextField();
t2.setBounds(130,100,100,20);
//t2.setEchoChar('*');
b1= new JButton("login");
b1.setBounds(80,150,80,20);
l3 = new JLabel("->");
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");
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Using CardLayout design a user interface to access the Programs and Courses offered
by the College and use appropriate event handling.
import java.awt.*;
import java.awt.event.*;
public class CardDemo extends Frame implements ActionListener,MouseListener {
Checkbox c1,c2,c3,c4; //B.Tech
Checkbox c5,c6,c7; //M.Tech
Panel deck; //deck-main panel
Panel p1,p2; //cards
CardLayout cl;
Button b1,b2;
public CardDemo()
{
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());
b1 = new Button("B.Tech");
b2 = new Button("M.Tech");
add(b1); //Frame window
add(b2); //Frame Window
cl = new CardLayout(5,5);
deck = new Panel();
deck.setLayout(cl); // set main panel layout to card layout
c1 = new Checkbox("CSE", true);
c2 = new Checkbox("ECE");
c3 = new Checkbox("EEE");
c4 = new Checkbox("MECH");
p1 = new Panel(); //first card as Panel
p1.add(c1);
p1.add(c2);
p1.add(c3);
p1.add(c4);
c5 = new Checkbox("Neural Networks", true);
c6 = new Checkbox("Digital Image Processing");
c7 = new Checkbox("Machine Design");
p2 = new Panel(); //second card as panel
p2.add(c5);
p2.add(c6);
p2.add(c7);
//Adding panel cards to main panel
deck.add(p1,"B.Tech");
deck.add(p2,"M.Tech");
// add main panel (deck) to Frame
add(deck);
b1.addActionListener(this);
b2.addActionListener(this);
addMouseListener(this);
public void mousePressed(MouseEvent me)
{
cl.next(deck);
}
public void mouseClicked(MouseEvent me)
{
}
public void mouseEntered(MouseEvent me)
{
cl.first(deck);
}
public void mouseExited(MouseEvent me)
{
cl.last(deck);
}
public void mouseReleased(MouseEvent me)
{
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() ==b1) //returns the clicked button object
cl.show(deck, "B.Tech");
else
cl.show(deck, "M.Tech");
}
public static void main(String args[]) {
new CardDemo();
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. What is a Layout Manager? List the various Layout Managers?
2. How the Border Layout organizes the components?
3. What are the constructors for Layout Managers?
4. How to set layout manager to a GUI window?
5. What are the advantages of swings?
Week-13
Pre-Lab
Questions
Develop GUI applications using Swings.
1. ActionEvnet is generated by which swing controls?
2. What are light weight and heavy weight components?
3. Difference between JFrame and JPanel?
4. Describe the Delegation Event Model.
5. Difference between run time error and logical error.
Program Code / Snippet / Algorithm / Description
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;
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);
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 + ":";
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();
}
}
Program Output/ Expected Output
Program Code / Snippet / Algorithm / Description
b) Create a JTable to display various fields of Student data like RollNo, Name, Branch,
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);
Year,
// 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();
}
}
Program Output/ Expected Output
Post-Lab
Questions
1. How many arguments in JTable creation.
2. How JTextField and JTextArea differs?
3. Why do we need JScrollPane in GUI?
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?
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;
}
1
Ans.
32
What will be printed by the code fragment below?
double height = 5.5;
if(height-- >= 5.0)
System.out.print("tall ");
if(--height >= 4.0)
5
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;
6
x = argCopy[0].length;
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. 1 2 3
7
What is an Exception in java?
An Exception is a failure condition that occurs during the execution of a program
Ans. and 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.
Ans.
9
Ans.
10
Ans.
11
Ans.
Ans.
12
Ans.
13
Ans.
try : The code or set of statements that may raise exception should be try block.
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.
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.
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.
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.
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
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
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.
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.
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:
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.
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.
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
Ans. java.lang.RuntimeException are RuntimeExceptions.
Example: NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException etc.
What
is
the
difference
between
ClassNotFoundException
and
15
NoClassDefFoundError in java?
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
Ans. Class.forName() or loadClass() methods and mentioned classes are not found in the
classpath is called ClassNotFoundException.
16
Ans.
Ans.
17
Ans.
Ans.
18
Ans.
NoClassDefFoundError:
An exception that occurs when a particular class is present at compile-time but was
missing at run time is called NoClassDefFoundError.
What is the use of throws keyword in java?
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
block, you will assure that those operations will be always executed irrespective of
whether an exception has occurred or not.
What is OutOfMemoryError in Exception Handling?
OutOfMemoryError is the subclass of java.lang.Error. It occurs when JVM runs out
of memory.
What is ClassCastException in Exception Handling?
RunTimeException which occurs when JVM not able to cast an object of one type to
another type is called ClassCastException.
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) 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.
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?
Ans ArrayIndexOutOfBoundsException,
24
Ans.
25
Ans.
26
Ans.
Ans.
27
Ans.
28
Ans.
29
Ans.
30
Ans.
31
NullPointerException,
NumberFormatException
List the Methods in the Throwable class?
Below are the important methods of Throwable class:
• getMessage()
• getCause()
• toString()
• printStackTrace()
• StackTraceElement [] getStackTrace()
What is a SQLException in Exception Handling?
An exception that provides information related to database access error or other
errors is called SQL Exception.
What is NumberFormatException in java?
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 that does not exist or out of the bound of this array.
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.
As a result, you will find the exception message and stack trace in the system
console.
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 the fast and efficient performance. Its main advantages are:
 Threads share the same address space.
 The thread is lightweight.
 The cost of communication between the processes is low.
What is the thread?
A thread is a lightweight sub process. It is a separate path of execution because each
thread runs in a different stack frame. A process may contain multiple threads.
Threads share the process resources, but still, they execute independently.
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
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.
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
Ans.
33
Ans.
34
Ans.
35
Ans
36
Ans
37
Ans.
38
Ans.
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
current thread, and wait until another thread does not call the notify() or notifyAll()
method. Its syntax is given below.
public final void wait()
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
for inter-thread communication with notify() and notify All(). Therefore It must be
present in the synchronized block for the proper and correct communication.
What are the advantages of multithreading?
Multithreading programming has the following advantages:
 Multithreading allows an application/program to be always reactive for input,
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.
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.
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.
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
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
What is context switching?
In Context switching the state of the process (or thread) is stored so that it can be
restored and execution can be resumed from the same point later. Context switching
enables the multiple processes to share the same CPU.
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 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
39
Ans.
40
Ans.
41
Ans.
42
Ans.
Thread class provides various inbuilt methods such as getPriority(), isAlive and
many more while the Runnable interface provides a single method, i.e., run().
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
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
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.
Syntax:
 public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos)throws InterruptedException
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
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.
What is the difference between wait() and sleep() method?
The wait() method is defined in Object class. The wait() method releases the lock
The sleep() method is defined in Thread class, The sleep() method doesn't release the
lock.
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
What is the order of the three top level elements of the java source file?
What are the states associated with the thread?
Discuss a Thread Life Cycle?
What are the thread states?
What are the major differences between Thread and Process?
What do you mean by thread starvation?
What is context-switching in multi-threading?
What happens if we don’t override a run method?
What is the major difference between Thread.start() & Thread?run() method?
How to create a thread in java?
What is the meaning of Thread Priority?
What join() method does?
How can you share data between two thread in Java?
How can multiple threads be controlled simultaneously?
What is a blocking method in Java?
What is the main difference between wait () and sleep () method?
What is an immutable object? How can it help in writing a concurrent application?
What is ThreadPool?
What is the use of Synchronized keyword?
What are the main differences between notify and notifyAll in Java?
Can you start a thread twice in Java?
When can we say that threads are not lightweight process in java?
Can It is possible to synchronize the constructor of a Java Class?
What is transient variable?
What is a volatile keyword?
Why thread is soo called as light weight Process?
What is Exception in Java?
What are the Exception Handling Keywords in Java?
Can we have a try block without a catch?
Difference between Error and Exception in Java?
Does finally runs always? On which case finally doesn't run?
What is difference between final, finally and finalize in Java?
What are different scenarios causing “Exception in thread main”?
What is difference between throw and throws keyword in Java?
Explain Java Exception Hierarchy?
What are important methods of Java Exception Class?
37.
38.
39.
40.
41.
42.
Explain Java multi-catch block?
What is difference between Checked and Unchecked Exception in Java?
How to compare two Strings in java program?
Why String is immutable?
How do you check if two Strings are equal in Java?
Write a method that will remove given character from the String?
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
What is the difference between an argument and a parameter?
What is the difference between this () and super ()?
What is the difference between constructor and method?
What are methods and how are they defined?What are the different scopes for Java variables?
How to Split String in java?
Can we use String in switch case?
What are different ways to create String Object?
What is the first argument of the String array in main method?
Can main method be declared final?
What is a constructor?
What is the difference between constructor and method?
What is constructor overloading and Method Overloading?
What is the Command to execute a compiled java program?
What is the order of the three top level elements of the java source file?
The minimum value of char type variable is-----When Widening conversion is possible in java
How do you create array of objects?
What is inheritance?
What are the types of inheritance?
What do you mean by abstract method and abstract class?
What is the difference between abstract class and interface?
Can you have an inner class inside a method and what variables can you access?Can a abstract class be declared final?
Can a method inside a Interface be declared as final?
Can a Class extend more than one Class?
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 we
access the class?
Can you declare a non final variable in an interface?
Can an interface be final?
Multiple-inheritance is possible through interfaces in java. Justify.
Can you instantiate an interface?
What are the advantages of using exception handling?
How to create custom exceptions?
If I want an object of my class to be thrown as an exception object, what should I do?
Is it necessary that each try block must be followed by a catch block?
If I write return at the end of the try block, will the finally block still execute?
What is the type of argument that the sleep() method of Thread class takes.
What type of Exception is thrown by Thread.sleep()?
Different methods of Object class?
What is daemon thread and which method is used to create the daemon thread?What is use of assigning priority to a thread?
What is the default priority number assigned to main thread?
What is Serialization and deserialization?
What is source and listener?
What are the advantages of the model over the event-inheritance model?
What is source and listener?
What is meant by controls and what are different types of controls in AWT?
What is meant by controls and what are different types of controls in AWT?
What is the difference between choice and list?
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
What is a layout manger and what are different types of layout managers available in
java AWT?
How are the elements of different layouts organized?
Which containers use a Border layout as their default layout?
What is difference between Swing and AWT in Java?
What is difference between paint and repaint in Java Swing?
What is difference between Container and Component ?
What is difference between BorderLayout and GridLayout ?
Why Swing is called light weight ?
Is Swing Thread safe in Java?
Explain about different layout mangers?
Explain the swing delegation event model?
What is the difference between applications and applets?
How does applet recognize the height and width?
When do you use codebase in applet?
What is the lifecycle of an applet?
How do you set security in applets?
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 and
paint?
Download