0% found this document useful (0 votes)
4 views64 pages

Java Lab Manual

The document outlines the Java Programming Lab course (CS-306) for the Department of Computer Science & Engineering, detailing its educational objectives, outcomes, syllabus, and course structure. It covers key topics such as object-oriented programming, multithreading, GUI programming, and database connectivity, along with specific experiments and course outcomes. The course aims to equip students with both technical and soft skills necessary for real-world applications in software development.
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)
4 views64 pages

Java Lab Manual

The document outlines the Java Programming Lab course (CS-306) for the Department of Computer Science & Engineering, detailing its educational objectives, outcomes, syllabus, and course structure. It covers key topics such as object-oriented programming, multithreading, GUI programming, and database connectivity, along with specific experiments and course outcomes. The course aims to equip students with both technical and soft skills necessary for real-world applications in software development.
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/ 64

JAVA PROGRAMMING LAB

Subject code: CS-306


Department of Computer Science & Engineering

July-Dec 2024

Deepak Kumar Mishra


Assistant Professor
Department of Computer Science & Engineering

1|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Table of Content
S. No. Particulars Page No.

1 Programme Educational Objectives (PEOs) 3

2 Programme Outcomes (POs) 4-5

3 Programme Specific Outcomes (PSOs) 6

4 Syllabus 7-8

5 Course Outcomes (COs) 9

6 CO- PO and CO-PSO mapping 9

7 Course Overview 10

8 List of Experiments mapped with COs 11-12

9 DOs and DON’Ts 13

10 General Safety Precautions 14

11 Guidelines for students for report preparation 15

12 Lab Experiments 17-50

13 VIVA Questions 51-64

2|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Programme Educational Objectives (PEOs)

PE01-ANALYTICAL SKILLS: Using a solid foundation in mathematical, scientific,


engineering, and current computing principles, formulate, analyse, and resolve engineering
issues in real-world domain.

PEO2-TECHNICAL SKILLS: Apply artificial intelligence theory and concepts to analyse the
requirements, realise technical specifications, and design engineering solutions.

PEO3-SOFT SKILLS: Through inter-disciplinary projects and a variety of professional


activities, demonstrate technical proficiency, AI competency, and foster collaborative learning
and a sense of teamwork.

PEO4-PROFESSIONAL ETHICS: Excel as socially responsible engineers or entrepreneurs


with high moral and ethical standards, competence, and soft skills that will enable them to
contribute to societal demands and achieve sustainable advancement in emerging computer
technologies.

3|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Programme Outcomes (POs)

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


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

PO9: Individual and teamwork: Function effectively as an individual, and as a member or


leader in diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and

4|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
P11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

P12: 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.

5|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Programme Specific Outcomes (PSOs)

PSO1: Fundamentals and critical knowledge of the Computer System:


Apply the knowledge gained pertaining to build, asses, and analyze the software and hardware
aspects of the program to solve real world business problems.

PSO2: Comprehensive and applicative knowledge of Software Development:


Ability to evaluate and apply knowledge of data engineering, methodologies, and able to plan,
develop, test, analyze, and manage required aspects in heterogenous platforms individually
or in team work.

PSO3: Applications in Computing Domain:


Ability to acquire computational knowledge and project development abilities using novel tools
and methodologies to tackle challenges in the fields related to Deep Learning, Machine
learning, Artificial Intelligence.

PSO4: Applications in Innovations and Research:


Capacity to direct a team or firm that develops products and to use the knowledge learned to
recognize actual research issues

6|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Syllabus
Course Objective:
The objective of this course is to study and understand Core of Java Technology. The course
provides the basics oops concept, development of desktop and network and Multithreaded
Database centric applications.

Course Contents:
Module I: (07 Hours)
Object Oriented Programming: Concept and features of object-oriented programming, create
classes and objects and add methods to a class, Real World Comparison. Evolution of JAVA:
History of Java, Requirements and Environment (JDK), Comparison with other languages,
Basic Features & Java Architecture-Java Virtual Machine (JVM), Installing Java Development
Kit.
Program Structure- Data types, Variables and Operators. Arrays. Classes and Objects in Java:
Understanding Constructors, Dealing with Garbage Collection.
Working with Inheritance in Java: Understanding Abstract Classes and Interfaces.
Packages: Introduction to packages, How to implement a package? CLASSPATH Setting for
Packages, Types and understanding packages.

Module II: (07 Hours)


Multithreaded Programming: Basic concepts and needs of multi-threading, Life Cycle of a
Thread, How to create a thread? Handling Thread Priorities, Enforcing Thread
Synchronization, Maintaining Inter-thread Communication. Exception Handling: The Idea
behind Exception, Exceptions & Errors, Types of Exception, Control Flow in Exceptions, Use
of try, catch, finally, throw, throws in Exception Handling.

Module III: (06 Hours)


GUI Programming -Introduction to AWT, Window Fundamentals, Working with Graphics,
Using AWT Controls and Menus, Understanding Layout Managers. JFC and Swing – A Higher
Level of User Interaction, Features of the Java Foundation Classes, Overview of Swing,
Components and Containers, Swing Packages, Exploring Swing components, Generating
Swing Application. Event Handling -The Delegation Event Model, Event Classes, Event
Listener Interfaces Handling Various Events.

Module IV: (05 Hours)


Input/Output : Exploring Java i.o., Directories, stream classes, The Byte stream : Input
stream, output stream, file input stream, file output stream, print stream, Random access
file, the character streams, Buffered reader, buffered writer, print writer, serialization.
JAVA Database Connectivity (JDBC); JDBC Drivers, Connection Interface, Resultset types of
ResultSet, applying insert, delete, display and update operation

7|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Module V: (05 Hours)
Networking & RMI: Java Networking: Networking Basics: Socket, Client server, reserved
sockets, proxy servers, Inet address, TCP sockets, UDP sockets. RMI for distributed
computing; RMI registry services; Steps of creating RMI Application and an example.

Course Outcomes:
After completion of this syllabus Learner will be able to:
 Express the power of a platform independent technology.
 Explain comparison between java and C++.
 Introduce the use of client site programming using Applet.
 Explain the Fundamental of Access specifies, constructor and packages.
 Express the power of method overloading and method overriding and uses of abstract
classes.
 Role and Need of Interfaces to develop real time Application.
 Creating thread with the thread class and runnable interface.
 Implement the concept of exception handling Real time Application.
 Implement Web Application using Applet.
 Implement Window Application using AWT Swing and JDBC.
 Implement Real World Application by handling mutable objects using file Handling.
 Connect a Application to A remote database through JAVA database connectivity.
 Express the power of java in Distributed Application through Networking, socket and
RMI Programming.
 Role of RMI Programming for distributed computing.

Text & References:


Text:
 JAVA The Complete Reference by Patrick Naughton & Herbert Schild, TMH
 Introduction to JAVA Programming a primar, Balaguruswamy.
 Deitel “Java- How to Program:” Pearson Education, Asia
References:
 “Introduction to JAVA Programming” Daniel/Young PHI
 Jeff Frentzen and Sobotka, “Java Script”, Tata McGraw Hill,1999
 Horstmann & Cornell “Core Java 2” (Vol I & II), Sun Microsystems

8|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Course Outcomes (COs)

CO1: Understand the basics of object-oriented programming using JAVA.


CO2: Apply the concept of classes, Java, JDK Components and develop Simple Java
Programs.
CO3: Develop Simple Java Programs using inheritance and Exception handling.
CO4: Develop Multi-threading Programming and Interfaces.
CO5: Develop GUI applications using Applet classes, Swing components and Event handling
programs.

CO-PO Mapping

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 1 1 1 2 2
CO2 1 1 1 2 2
CO3 2 2 2 2 2 2
CO4 2 2 3 3 2 3 2
CO5 3 3 3 3 3 3 3 3 3

CO- PSO Mapping

CO PSO1 PSO2 PSO3 PSO4


CO1 1 2 1
CO2 1 2 1
CO3 2 2 2
CO4 2 2 2 2
CO5 3 3 3 3

*3-HIGH
*2-MEDIUM
*1-LOW

9|Page

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Course Overview
Lab assignment will be based on the following:

Object Oriented Programming (OOP) is a programming paradigm that treats data and the
functions that operate on that data as a single unit. In Java, objects are the basic building
blocks of all programs.

An object-oriented programming course in Java typically covers the following topics:


Objects and classes: Objects are instances of classes, which are templates for creating
objects. Classes contain data members (variables) and methods (functions) that define the
behavior of objects.
Inheritance: Inheritance is the ability of one class to inherit the properties of another class.
This allows for code reuse and makes it easier to create complex programs.
Polymorphism: Polymorphism is the ability of an object to take on different forms. This is
achieved through the use of abstract classes and interfaces.
Encapsulation: Encapsulation is the hiding of data members from other parts of the program.
This helps to protect data and make programs more secure.
Exception handling: Exception handling is a way of dealing with errors that occur during
program execution. This helps to prevent programs from crashing and makes them more
robust.
In addition to these core concepts, an object-oriented programming course in Java may also
cover topics such as:
GUI programming: GUI programming is the development of graphical user interfaces. This is
a key skill for Java developers, as many Java applications use GUIs.
Collections: Collections are data structures that store and organize data. Java provides a
number of different collection classes, which can be used to store and manipulate data in a
variety of ways.
Algorithms: Algorithms are step by step procedures for solving problems. Java developers
need to be familiar with a variety of algorithms in order to write efficient and effective
programs.
Object oriented programming is a powerful programming paradigm that can be used to create
complex and sophisticated programs. A course in object-oriented programming in Java can
provide you with the skills and knowledge you need to become a successful Java developer.

10 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
List of Experiments mapped with COs
S. N EXPERIMENT CO BL PI

Use Eclipse or Net bean platform and acquaint with the various
menus. Create a test project, add a test class, and run it. See how
you can use auto suggestions, auto fill. Try code formatter and code CO1, 1.3.1,
1 L3
refactoring like renaming variables, methods, and classes. Try CO2 1.4.1
debug step by step with a small program of about 10 to 15 lines
which contains at least one if else condition and a for loop.

CO1, 1.3.1,
2 WAP to demonstrate data types available in java CO2
L3
1.4.1
CO1, 1.3.1,
3 WAP to design a simple calculator using switch case statement CO2
L3
1.4.1
CO1, 1.3.1,
4 WAP to print all prime numbers between 1 to 1000 CO2
L3
1.4.1
CO1, 1.3.1,
5 WAP to implement linear search in 1D array CO2
L3
1.4.1
CO1, 1.3.1,
6 WAP to implement bubble sort in 1 D array CO2
L3
1.4.1
CO1, 1.3.1,
7 WAP to multiply 2 matrices in java CO2
L3
1.4.1
CO1, 1.3.1,
8 WAP to implement recursion function in java CO2
L3
1.4.1
CO1, 1.3.1,
9 WAP to demonstrate some in-built functions on Strings CO2
L3
1.4.1
CO1, 1.3.1,
10 WAP to demonstrate concept of Class, Object, and methods in java. CO2
L3
1.4.1
CO1, 1.3.1,
11 WAP to demonstrate method overloading in java CO2
L3
1.4.1
CO1, 1.3.1,
12 WAP to demonstrate inheritance in java CO3
L3
1.4.1
CO1, 1.3.1,
13 WAP to demonstrate multiple inheritance using interface CO3
L3
1.4.1
CO1, 1.3.1,
14 WAP to demonstrate method over riding in java CO3
L3
1.4.1

11 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
CO1, 1.3.1,
15 WAP to demonstrate exception handling in java CO3
L3
1.4.1
CO1, 1.3.1,
16 WAP to demonstrate multi-threading in java CO4
L3
1.4.1
1.3.1,
17 WAP to read, write, append data in files CO1 L3
1.4.1
1.3.1,
18 WAP to demonstrate database connectivity using JDBC CO4 L3
1.4.1

1.3.1,
19 WAP to create a Swing Application with JDBC CO4 L3
1.4.1
1.3.1,
1.4.1,
20 WAP to design a Menu using Swing in Java CO4 L6
2.2.3,
3.4.2,

12 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
DOs and DON’Ts

DOs
1. Login-on with your username and password.
2. Log off the computer every time when you leave the Lab.
3. Arrange your chair properly when you are leaving the lab.
4. Put your bags in the designated area.
5. Ask permission to print.

DON’Ts
1. Do not share your username and password.
2. Do not remove or disconnect cables or hardware parts.
3. Do not personalize the computer setting.
4. Do not run programs that continue to execute after you log off.
5. Do not download or install any programs, games or music on computer in Lab.
6. Personal Internet use chat room for Instant Messaging (IM) and Sites is strictly
prohibited.
7. No Internet gaming activities allowed.
8. Tea, Coffee, Water & Eatables are not allowed in the Computer Lab.

13 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
General Safety Precautions

Precautions (In case of Injury or Electric Shock)


1. To break the victim with live electric source, use an insulator such as fire wood
or plastic to break the contact. Do not touch the victim with bare hands to avoid
the risk of electrifying yourself.
2. Unplug the risk of faulty equipment. If main circuit breaker is accessible, turn
the circuit off.
3. If the victim is unconscious, start resuscitation immediately, use your hands to
press the chest in and out to continue breathing function. Use mouth-to-mouth
resuscitation if necessary.
4. Immediately call medical emergency and security. Remember! Time is critical;
be best.

Precautions (In case of Fire)


1. Turn the equipment off. If power switch is not immediately accessible, take plug
off.
2. If fire continues, try to curb the fire, if possible, by using the fire extinguisher
or by covering it with a heavy cloth, if possible, isolate the burning equipment
from the other surrounding equipment.
3. Sound the fire alarm by activating the nearest alarm switch located in the
hallway.
4. Call security and emergency department immediately:
Emergency: (Reception)
Security: (Gate No.4)

14 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Guidelines for students for report preparation

All students are required to maintain a record of the experiments conducted by


them. Guidelines for its preparation are as follows: -
1) All files must contain a title page followed by an index page. The files will not be
signed by the faculty without an entry in the index page.
2) Student’s Name, roll number and date of conduction of experiment must be
written on all pages.
3) For each experiment, the record must contain the following
(i) Aim/Objective of the experiment
(ii) Pre-experiment work (as given by the faculty)
(iii) Lab assignment questions and their solutions
(iv) Test Cases (if applicable to the course)
(v) Results/ output
Note:
1. Students must bring their lab record along with them whenever they come
for the lab.
2. Students must ensure that their lab record is regularly evaluated.

15 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
LAB EXPERIMENTS

16 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
PROGRAM -1
Steps To Execute Simple Java Program Using Eclipse

Step1: Begin by creating a new Java project.

There are few different ways of accomplishing this. Click the arrow next to the left-
most icon on the toolbar and select “Project” from the drop-down menu. Alternately
Start a new Java Project by choosing “File” then “New” followed by “Java Project”. Also
use the shortcut Alt+Shift+N.

17 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step2: Enter a Project Name

You will see a window titled “Create a Java Project”. The buttons “Next” and “Finish”
at the bottom of the window will be grayed out until a project name is entered in
the first field. To processed, give project name and enter it into this field then click
“Finish”. New project will appear on the left-hand side of the screen under “Package
Explorer” among existing projects. Projects are listed in alphabetical order.

18 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step3: Start a new java class.

Before begin writing code, need to create a new Java class. A class is a blueprint
for an object. It defines the data stored in the object as well as its actions. Create a
class by clicking the “New Java Class” icon, which looks like a green circle with the
letter “C” in the center of it.

19 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
4: Enter the name of your class.

You will see a window titled “Java Class.” To proceed, enter the name of class into the
field “Name”. Since the class will be main class of the simple project, check
theselection box labeled “public static void main(String[] args)” to include the method
stub. Afterwards, click “Finish”.

20 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step5: Enter Java Code.

Here new class Welcome.java is created. It appears with the method stub “public static
void main(String[] args)” along with some automatically generated comments. A
method will contain a sequence of instructions to be executed by the program. A
comment is a statement that is ignored by the compiler. Comments are used by
programmers to document their code. Edit this file and insert the code for Java
Program.

21 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step6: Watch out for errors in code.

Any errors will be underlined in red, and icon with an ”X” will show up on the left. Fix
errors. By mousing over an error icon.can see a suggestion box that lists the ways can
fix the error.

22 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step7: Ensure that entire program is free of errors.

There are three types of errors must beware of: syntax errors, run-time errors and
logic errors. The compiler will alert syntax errors. Examples of syntax errors are
misspelled variable names or missing semi-colons. Until remove all syntax errors from
code program will not compile. The compiler will not catch run-time errors or logic
errors.

23 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step8: Compile Java Program.

Now the program is free for errors, click the triangular icon to run program. Another
way to run program is to select “Run” from the main menu and then select “Run”
again from the drop-down menu. The shortcut is Ctrl+F11.

Step9: Verify the output is what you expected.

When program runs, the output will be displayed on console at the bottom of the
screen.

24 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Step10: Fix any run-time or logic errors.

If the output is different from what you excepted, then there might have been an
error even though the program compiled. For example, if the output was zero instead
of four, then there was a mistake in the program’s calculation.

25 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
PROGRAM – 1 (self Work)

Create a test project, add a test class, and run it

Aim: Use Eclipse or Net bean platform and acquaint with the various menus. Create
a testproject, add a test class, and run it. See how you can use auto suggestions, auto
fill. Try code formatter and code refactoring like renaming variables, methods, and
classes. Try debug step by step with a small program of about 10 to 15 lines which
contains at least one if else condition and a for loop.

Program:
class PrimeNumbers
{

public static void main(String[] args)


{
try
{
System.out.println("***** PRIME NUMBERS *****");
Scanner objScanner = new Scanner(System.in);
System.out.print("\n Enter n Value:"); long n = objScanner.nextInt();

for (long i = 2; i <= n; i++)


{
boolean isprime = isNumPrime(i); if (isprime)
{
System.out.print(i + " ");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

public static boolean isNumPrime(long number)


{
boolean result = true;
for (long i = 2; i <= number / 2; i++)

26 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
{
if ((number % i) != 0)
{
result = true;

}
else
{
result = false; break;
}
}

return result;
}
}

27 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 2

WAP to demonstrate data types available in Java

Source Code:
package oopsfile;
public class Program1
{
public static void main(String args[])
{
int a;
char c;
float b;
double d;
boolean f;
a=10;
c='A';
b=25.63f;
d=12.698f;
f=true;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d="+d);
System.out.println("f="+f);
}
}

28 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 3
WAP to design a simple calculator using switch case statement

Source Code:
package oopsfile;
import java.util.Scanner;
public class Program2 {
public static void main(String[] args) {
// TODO Auto generated method stub
System.out.println("Press 1: Addition");
System.out.println("Press 2: Subtraction");
System.out.println("Press 3: Multiply");
System.out.println("Press 4: Division");
int a,b,c;
int choice;
System.out.println("Enter your choice");
Scanner sc=new Scanner(System.in);
choice=sc.nextInt();
System.out.println("Enter First Number");
a=sc.nextInt();
System.out.println("Enter Second Number");
b=sc.nextInt();
switch (choice)
{
case 1:
c=a+b;
System.out.print("Addition is "+c);
break;
case 2:
c=a b;
System.out.print("Subtraction is "+c);
break;
case 3:
c=a*b;
System.out.print("Multiplication is "+c);
break;
case 4:
c=a/b;
System.out.print("Division is "+c);
break;
default:
System.out.println("Bad Choice");
break;
}} }
29 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 4
WAP to print all prime numbers between 1 to 1000

Source Code:
package oopsfile;
import java.util.Scanner;
public class Program3
{
public static void main(String ar[])
{
int num=2;
//Scanner sc=new Scanner(System.in);
//System.out.print("Enter any number");
//num=sc.nextInt();
for(num=2;num<100;num++)
{
int i=2;
while(i<num)
{
if(num%i==0)
{
//System.out.println("NUmber is not Prime");
if(num==2)
System.out.println(num);
break;
}
i++;
if(i==num)
System.out.println(num);
}
}}
}

30 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 5
WAP to implement linear search in 1D array

Source Code:
package oopsfile;
import java.util.Scanner;
public class Program4 {
public static void main(String[] args) {
// TODO Auto generated method stub
int a[]= {10,20,30,50,5,15,25,35,45,55,76,102,7};
int item=0;
int 1;
System.out.println("Enter the element to be search");
Scanner sc=new Scanner(System.in);
item=sc.nextInt();
for(int i=0;i<a.length;i++)
{
if(item==a[i])
{
loc=i;
break;
}
}
if( 1)
System.out.println("Item not Found");
else
System.out.println("Item found at location ="+loc);
}
}

31 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 6
WAP to implement bubble sort in 1 D array

Source Code:
package oopsfile;
public class Program5 {
public static void main(String[] args) {
// TODO Auto generated method stub
int a[]= {22,55,99,88,44,33,66,77,11,155,122};
int l=a.length;
for (int i = 0; i < l 1; i++)
for (int j = 0; j < l i 1; j++)
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
for(int i=0;i<l;i++)
System.out.println(a[i]);
}
}

32 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 7
WAP to multiply 2 matrices in java

Source Code:
package oopsfile;
import java.util.Scanner;
public class Program6 {
public static void main(String[] args) {
// TODO Auto generated method stub
int a[][]=new int[3][3];
int b[][]=new int[3][3];
int c[][]=new int[3][3];
// Data for Matrix A
System.out.println("Enter the matrix A");
Scanner sc=new Scanner(System.in);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
// Data for Matrix A
System.out.println("Enter the matrix A");
//Scanner sc=new Scanner(System.in);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j]=sc.nextInt();
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
33 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}

34 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 8
WAP to implement recursion function in java

Source Code:
package oopsfile;
import java.util.Scanner;
public class Program7 {
public static void main(String[] args) {
// TODO Auto generated method stub
int num;
Scanner sc=new Scanner(System.in);
num=sc.nextInt();
int factorial;
factorial=fact(num);
System.out.println(factorial);
}
static int fact(int num)
{
if(num==1)
return 1;
else
return num*fact(num 1);
}
}

35 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 9
WAP to demonstrate some in built functions on Strings

Source Code:
package oopsfile;
public class Program8
{
public static void main(String arg[])
{
String str=new String("Welcome to AIML Department");
//length of string
System.out.print("Length of String= "+str.length());
StringBuilder sb=new StringBuilder(str);
String str2=new String(sb.reverse());
System.out.println(str2);
str2=new String(sb.reverse());
System.out.println(str.toLowerCase());
if(str.equals(str2))
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}
System.out.println(str.toUpperCase());
if(str.equalsIgnoreCase(str2))
{
System.out.println("Strings are equal");
}
else
{
System.out.println("Strings are not equal");
}
}
}

36 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 10
WAP to demonstrate concept of Class, Object, and methods in java.

Source Code:
package oopsfile;
class Add
{
int a, b;
void getData(int x,int y)
{
a=x;
b=y;
}
int add()
{
return a+b;
}
}
class Program9
{
public static void main(String[] args)
{
Add add=new Add();
add.getData(10, 20);
System.out.println("Value of a="+add.a);
System.out.println("Value of b="+add.b);
System.out.println("Addition of and b="+add.add());
}
}

37 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 11
WAP to demonstrate method overloading in java

Source Code:
package oopsfile;
class Program10
{
public static void main(String args[])
{
CalArea ca=new CalArea();
int area;
area=ca.area(4);// one parameter
System.out.println("Area ="+area);
area=ca.area(10,5);// two parameter
System.out.println("Area ="+area);
area=ca.area(4,5,3);// three parameter
System.out.println("Area ="+area);
}
}
class CalArea
{
int area(int x)
{
return x*x;
}
int area(int x,int y)
{
return x*y;
}
int area(int x,int y,int z)
{
return x*y*z;
}
}

38 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 12
WAP to demonstrate inheritance in java

Source Code:
package oopsfile;
class Room
{
int length,breadth;
Room(int x,int y)
{
length=x;
breadth=y;
}
int area()
{
return length*breadth;
}
}
class Bedroom extends Room
{
int height;
Bedroom(int x,int y,int z)
{
super(x,y);
height=z;
}
int volume()
{
return length*breadth*height;
}
}
class Program11
{
public static void main(String args[])
{
Bedroom b=new Bedroom(14,20,10);
System.out.println("Area of Room: "+b.area());
System.out.println("Volume of Room: "+b.volume());
}
}

39 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 13
WAP to demonstrate multiple inheritance using interface

Source Code:
package oopsfile;
interface Area
{
final static float pi=3.014F;
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return x*y;
}
}
class Circle implements Area
{
public float compute(float x, float y)
{
return pi*x*x;
}
}
public class Program12
{
public static void main(String args[])
{
Rectangle r=new Rectangle();
Circle c=new Circle();
System.out.println("Area of Rectangle =:"+r.compute(5, 6));
System.out.println("Area of Circle =:"+c.compute(5, 6));
}
}

40 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 14
WAP to demonstrate method over riding in java

Source Code:
package oopsfile;
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display()
{
System.out.println("Value of x in Super:"+x);
}
}
class Sub extends Super
{
int y;
Sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println("Value of x in Super:"+x);
System.out.println("Value of y in SuB:"+y);
}
}
public class Program13
{
public static void main(String args[])
{
Sub s=new Sub(10,20);
s.display();
}
}

41 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 15
WAP to demonstrate exception handling in java

Source Code:
package oopsfile;
class MyException extends Exception
{
public MyException(String message) {
// TODO Auto generated constructor stub
super(message);
}
}
class Program14
{
public static void main(String args[])
{
int a=5;
int y=1000;
try {
float z=(a)/(y);
if(z<0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my Exception");
}
}
}

42 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 16
WAP to demonstrate multi-threading in java

Source code:
package oopsfile;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("From Thread A="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From Thread B="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From Thread C="+k);
}
System.out.println("Exit from C");
}
}
class Program15 {
public static void main(String[] args) {
// TODO Auto generated method stub
new A().start();
new B().start();
new C().start(); }}
43 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 17
WAP to read, write, append data in files

Source Code:
package oopsfile;
import java.io.*;
public class Program16
{
public static void main(String args[]) throws Exception
{
File old=new File("G:\\ITM COLLEGE\\C Codes\\Java Code\\File1.txt");
File neww=new File("G:\\ITM COLLEGE\\C Codes\\Java Code\\File2.txt");
FileInputStream fis =new FileInputStream(old);
FileOutputStream fos=new FileOutputStream(neww);
int i;
while((i=fis.1)
{
fos.write(i);
}
fis.close();
fos.close();
System.out.println("Data has been copied Successfully");
}
}

44 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 18
WAP to demonstrate database connectivity using JDBC

Source Code:
package oopsfile;
import java.sql.*;
public class Program17 {
public static void main(String[] args) {
// TODO Auto generated method stub
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtest","root","ysr@8043");
Statement stat=con.createStatement();
ResultSet rs=stat.executeQuery("select * from student");
while(rs.next())
{
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.println();
}
}
catch(ClassNotFoundException e)
{
}
catch(SQLException e)
{
}
}
}

45 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 19
WAP to create a Swing Application with JDBC

Source Code:
package oopsfile;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class Program18
{
public static void main(String[] args)
{
MyFram mf=new MyFram();
mf.setVisible(true);
mf.setTitle("Student");
mf.setSize(400, 400);
mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mf.setLocation(200, 200);
}
}
class MyFram extends JFrame implements ActionListener
{
JLabel nameLabel,branchLabel,rollLabel;
JTextField nameField,branchField,rollField;
JButton submit;
MyFram()
{
nameLabel=new JLabel("NAME");
branchLabel=new JLabel("BRANCH");
rollLabel=new JLabel("ROLL NO");
nameField=new JTextField(10);
branchField=new JTextField(10);
rollField=new JTextField(10);
submit=new JButton("SUBMIT");
setLayout(null);
add(nameLabel);
46 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
nameLabel.setBounds(50, 40, 60, 50);
add(nameField);
nameField.setBounds(150, 40, 100, 35);
add(rollLabel);
rollLabel.setBounds(50, 100, 60, 50);
add(rollField);
rollField.setBounds(150, 100, 100, 35);
add(branchLabel);
branchLabel.setBounds(50, 150, 60, 50);
add(branchField);
branchField.setBounds(150, 150, 100, 35);
add(submit);
submit.setBounds(100, 250, 100, 30);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==submit)
{
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtest","root","ysr@8043");
PreparedStatement stat=con.prepareStatement("insert into student values(?,?,?)");
String name=nameField.getText();
String branch=branchField.getText();
String roll=rollField.getText();
int rol=Integer.parseInt(roll);
stat.setInt(1, roll);
stat.setString(2, name);
stat.setString(3, branch);
int i= stat.executeUpdate();
JOptionPane.showMessageDialog(this,"Data Saved Successfully");
rollField.setText("");
nameField.setText("");
branchField.setText("");
}
catch(ClassNotFoundException ex)
{
JOptionPane.showMessageDialog(this,"Class Not Found");
}
catch(SQLException ed)
{
47 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
JOptionPane.showMessageDialog(this,"DataBase Error");
}
}
}
}

48 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Program No. 20
WAP to design a Menu using Swing in Java

Source Code:
package oopsfile;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
class Program20 {
public static void main(String[] args)
{
MenuTest2 mt=new MenuTest2();
mt.setTitle("MENU TEST");
mt.setSize(400, 400);
mt.setVisible(true);
mt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MenuTest2 extends JFrame
{
JPanel panel;
MenuTest2()
{
JMenuBar jmb=new JMenuBar();
JMenu file=new JMenu("File");
JMenuItem open=new JMenuItem("Open");
JMenuItem close=new JMenuItem("Close");
JMenuItem save=new JMenuItem("Save");
JMenuItem ne =new JMenuItem("New");
file.add(open);
file.add(close);
file.add(save);
file.add(ne);
JMenu edit=new JMenu("Edit");
JMenuItem cut=new JMenuItem("Cut");
JMenuItem copy=new JMenuItem("Copy");
JMenuItem paste=new JMenuItem("Paste");
edit.add(cut);
edit.add(copy);
edit.add(paste);
jmb.add(file);
jmb.add(edit);
49 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
panel=new JPanel();
panel.add(jmb);
add(panel);
}}

50 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Viva Voce Questions with Answers

1. What is object-oriented programming (OOP)?


OOP is a programming paradigm that treats data as objects. Objects have state and behavior,
and they can interact with each other.
2. What are the four pillars of OOP?
The four pillars of OOP are abstraction, encapsulation, inheritance, and polymorphism.
3. What is abstraction?
Abstraction is the process of hiding the implementation details of an object and only exposing
the essential details to the user.
4. What is encapsulation?
Encapsulation is the bundling of data and methods together into a single unit. This helps to
protect the data from unauthorized access.
5. What is inheritance?
Inheritance is the ability of a class to inherit the properties and methods of another class.
This allows for code reuse and makes it easier to create complex objects.
6. What is polymorphism?
Polymorphism is the ability of an object to take on different forms. This is achieved through
the use of virtual methods.
7. What is a class?
A class is a blueprint for creating objects. It defines the data and methods that objects of that
class will have.
8. What is an object?
An object is an instance of a class. It has its own state and behavior, and it can interact with
other objects.
9. What is a method?
A method is a block of code that is associated with a class or object. It is used to perform a
specific task.
10. What is a constructor?
A constructor is a special method that is used to initialize an object.
11. What is a static method?
A static method is a method that is associated with a class, not with an object. It can be called
without creating an instance of the class.
12. What is a final method?
A final method cannot be overridden by a subclass.
13. What is a final class?
A final class cannot be inherited from.
14. What is a public method?
A public method can be accessed from anywhere in the program.
15. What is a private method?
A private method can only be accessed from within the class that it is defined in.
16. What is a protected method?

51 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
A protected method can be accessed from within the class that it is defined in, and from
subclasses of that class.
17. What is an abstract method?
An abstract method is a method that has no implementation. It must be overridden by
subclasses.
18. What is an interface?
An interface is a collection of abstract methods. It cannot be instantiated, but it can be used
to define the behavior of a class.
19. What is a package?
A package is a collection of classes and interfaces. It is used to organize code and to control
access to classes and interfaces.
20. What are the advantages of object-oriented programming?
The advantages of object-oriented programming include:
a) Reusability of code
b) Increased modularity
c) Improved code readability and maintainability
d) Increased flexibility and extensibility
21. What is JDBC?
JDBC stands for Java Database Connectivity. It is a Java API that allows Java programs to
connect to a database and perform SQL operations. JDBC is a standard API, so it can be used
to connect to any database that supports JDBC.
22. What are the different types of JDBC drivers?
There are four types of JDBC drivers:
JDBC-ODBC bridge driver: This driver uses the ODBC driver to connect to the database. It is
the simplest type of JDBC driver, but it is also the least efficient.
Native-API driver: This driver uses the client-side libraries of the database. It is more efficient
than the JDBC-ODBC bridge driver, but it requires the native libraries to be installed on each
client machine.
Network Protocol driver: This driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is the most efficient
type of JDBC driver, but it requires an application server to be installed.
Thin driver: This driver converts JDBC calls directly into the vendor-specific database
protocol. It is entirely written in Java, so it is platform-independent.
23. What are the steps involved in using JDBC?
The basic steps involved in using JDBC are:
a) Import the JDBC packages.
b) Register the JDBC driver.
c) Create a connection to the database.
d) Create a statement.
e) Execute the statement.
f) Process the results.
g) Close the connection.
24. What are the different types of JDBC statements?
a) There are three types of JDBC statements:
52 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
b) Statement: This is the simplest type of JDBC statement. It can be used to execute any SQL
statement.
c) PreparedStatement: This type of statement is pre-compiled, which makes it more efficient
than a regular statement.
d) CallableStatement: This type of statement is used to execute stored procedures.
25. What are the benefits of using JDBC?
a) There are many benefits to using JDBC, including:
b) Platform independence: JDBC is a standard API, so it can be used to connect to any
database that supports JDBC.
c) Performance: JDBC is a well-optimized API, so it can be used to perform database
operations efficiently.
d) Ease of use: JDBC is a relatively easy API to use, even for beginners.

VIVA QUESTIONS:
1. What do you mean by Platform Independence?
Platform Independence you can run and compile program in one platform and can
execute in any other platform.
2. What is JIT Compiler?

53 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
Just-In-Time(JIT) compiler is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time
3. What all memory areas are allocated by JVM?
Heap, Stack, Program Counter Register and Native Method Stack
4.What is the base class of all classes?
java.lang.Object
5. What are two different ways to call garbage collector?
System.gc() OR Runtime.getRuntime().gc().
6. Use of finalize() method in java?
finalize() method is used to free the allocated resource.
7. List two java ID Es?
1. Eclipse, 2.Net beans and 3.IntelliJ
8.What are java buzzwords?
Java buzzwords explain the important features of java. They are Simple,Secured,
Portable, architecture neutral, high performance, dynamic, robust,interpreted etc.
9. Is byte code is similar to .obj file in C?
Yes, both are machine understandable codes No, .obj file directly understood by
machine, byte code requires JVM.
10. What are length and length( ) in Java?
Both gives number of char/elements, length is variable defined in Array class,length(
) is method defined in String class.

VIVA QUESTIONS:

1. What is object cloning?


The object cloning is used to create the exact copy of an object.
2. When parseInt() method can be used?
This method is used to get the primitive data type of a certain String.
3. java.util.regex consists of which classes?
java.util.regex consists of three classes − Pattern class, Matcher class and
PatternSyntaxException class.
4. Which package is used for pattern matching with regular expressions?
java.util.regex package is used for this purpose.
5. Define immutable object?
An immutable object can‟t be changed once it is created.
6. Explain Set Interface?
It is a collection of element which cannot contain duplicate elements. The Set
interface contains only methods inherited from Collection and adds the restriction
that duplicate elements are prohibited.
7. What is function overloading?
If a class has multiple functions by same name but different parameters, it is known
as Method Overloading.
8. What is function overriding?

54 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
If a subclass provides a specific implementation of a method that is already provided
by its parent class, it is known as Method Overriding.
9. What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task
invokes its sleep() method, it returns to the waiting state.
10. What are Wrapper classes?
These are classes that allow primitive types to be accessed as objects. Example:
Integer, Character, Double, Boolean etc.

VIVA QUESTIONS:
1. What is an applet? How does applet differ from applications?
A program that a Java enabled browser can download and run is an Applet.
2. What are the attributes of Applet tags? Explain the purposes?
height: Defines height of applet, width: Defines width of applet.
3. How will you initialize an Applet?
Write my initialization code in the applets init method or applet constructor.
4. What is the sequence for calling the methods by AWT for applets?
When an applet begins, the AWT calls the following methods, in this sequence:
 init()
 start()
 paint()
When an applet is terminated, the following sequence of method calls takes place :
 stop()
 destroy()
5. What is AppletStub Interface?
The applet stub interface provides the means by which an applet and the
browser communicate. Your code will not typically implement this interface.
6. What is the base class for all swing components?
JComponent (except top-level containers)
7.How will you communicate between two Applets?
All the applets on a given page share the same AppletContext. We obtain this
applet context as follows:

AppletContext ac = getAppletContext();

AppletContext provides applets with methods such as getApplet(name),


getApplets(), getAudioClip(url), getImage(url), showDocument(url) and
showStatus(status).
8. What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception
propagation.
9. What is the meaning of immutable in terms of String?

55 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
The simple meaning of immutable is unmodifiable or unchangeable. Once
string object has been created, its value can't be changed.

VIVA QUESTIONS:

1. What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors.It is mainly used to
handle checked exceptions.

2. What is difference between Checked Exception and Unchecked Exception?


i). Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions
are checked at compile-time.

ii). Unchecked Exception


The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked
at compile-time.
3. What is the base class for Error and Exception?
Throwable.
4. What is finally block?
finally block is a block that is always executed
5. Can finally block be used without catch?
Yes, by try block. finally must be followed by either try or catch.
6. Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort)
7. What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception
propagation.
8. What is nested class?
A class which is declared inside another class is known as nested class. There are 4
types of nested class member inner class, local inner class, annonymous inner class
and static nested class.
9. What is nested interface ?
Any interface i.e. declared inside the interface or class, is known as nested interface. It
is static by default.
10. Can an Interface have a class?
Yes, they are static implicitly.
VIVA QUESTIONS
1) What is multithreading?
Multithreading is a process of executing multiple threads simultaneously. Its main
advantage is:
56 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between process is low.
2)What is thread?
A thread is a lightweight subprocess.It is a separate path of execution.It is called
separate path of execution because each thread runs in a separate stack frame.
3) 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.
4) What does join() method?
The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.
5) Is it possible to start a thread twice?
No, there is no possibility to start a thread twice. If we does, it throws an exception.
6)Can we call the run() method instead of start()?
yes, but it will not work as a thread rather it will work as a normal object so there will
not be context-switching between the threads.
7) What about the daemon threads?
The daemon threads are basically the low priority threads that provides the
background support to the user threads. It provides services to the user threads.
8) Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw IllegalThreadStateException
9) What is shutdown hook?
The shutdown hook is basically a thread i.e. invoked implicitely before JVM shuts
down. So we can use it perform clean up resource.
10) When should we interrupt a thread?
We should interrupt a thread if we want to break out the sleep or wait state of a
thread.
VIVA QUESTIONS:
1. What is a Linked list?

Linked list is an ordered set of data elements, each containing a link to its successor (and
typically its predecessor).

2. Can you represent a Linked list graphically?

The fundamental data structure for the linked record involves 3 segments: the data itself and
also the link to another element. Together (data + link) this particular structure is normally
called the Node.

57 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
3. How many pointers are required to implement a simple Linked list?
You can find generally 3 pointers engaged:
 A head pointer, pointing to the start of the record.
 A tail pointer, pointing on the last node of the list. The key property in the last node is that
its subsequent pointer points to nothing at all (NULL).
 A pointer in every node, pointing to the next node element.
4.How many types of Linked lists are there?
Singly linked list, doubly linked list, multiply linked list, Circular Linked list.
5. How to delete a node from linked list?
 The following are the steps to delete node from the list at the specified position. Set the head
to point to the node that head is pointing to.
 Traverse to the desired position or till the list ends; whichever comes first
 You have to point the previous node to the next node.
6.How to reverse a singly linked list?
 First, set a pointer (*current) to point to the first node i.e. current=head.
 Move ahead until current!=null (till the end)
 set another pointer (*next) to point to the next node i.e. next=current->next
 store reference of *next in a temporary variable (*result) i.e. current->next=result
 swap the result value with current i.e. result=current
 And now swap the current value with next. i.e. current=next
 return result and repeat from step 2
 A linked list can also be reversed using recursion which eliminates the use of a temporary
variable.
7. Compare Linked lists and Dynamic Arrays
A dynamic array is a data structure that allocates all elements contiguously in memory, and keeps a
count of the present number of elements. If the area reserved for the dynamic array is exceeded, it‟s
reallocated and traced, a costly operation.
Linked lists have many benefits over dynamic arrays. Insertion or deletion of an element at a specific
point of a list, is a constant-time operation, whereas insertion in a dynamic array at random locations
would require moving half the elements on the average, and all the elements in the worst case.
Whereas one can delete an element from an array in constant time by somehow marking its slot as
vacant, this causes fragmentation that impedes the performance of iteration.

8. What is a Circular Linked list?


In the last node of a singly linear list, the link field often contains a null reference. A less common
convention is to make the last node to point to the first node of the list; in this case the list is said to
be „circular‟ or „circularly linked‟.

58 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
VIVA QUESTIONS:

1. What is GUI?
GUI stands for Graphical User Interface.
- GUI allows uses to click, drag, select graphical objects such as icons, images, buttons etc.
- GUI suppresses entering text using a command line.
- Examples of GUI operating systems are Windows, Mac, Linux.
- GUI is user friendly and increases the speed of work by the end users.
- A novice can understand the functionalities of certain application through GUI.

2. What is the difference between HashSet and TreeSet?


HashSet maintains no order whereas TreeSet maintains ascending order.
3) What is the difference between Set and Map?
Set contains values only whereas Map contains key and values both.
4) What is the difference between HashSet and HashMap?
HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be
iterated but HashMap need to convert into Set to be iterated.
5) What is the difference between HashMap and TreeMap?
HashMap maintains no order but TreeMap maintains ascending order. 6)What is the difference
between Collection and Collections?
Collection is an interface whereas Collections is a class. Collection interface provides normal
functionality of data structure to List, Set and Queue. But, Collections class is to sort and
synchronize collection elements.
7) What is the advantage of generic collection?
If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.
8) What is hash-collision in Hashtable and how it is handled in Java?
Two different keys with the same hash value is known as hash-collision. Two different entries
will be kept in a single hash bucket to avoid the collision.
9) What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
10) What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

VIVA QUESTIONS:

1. What is abstraction?
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it.
2. What is the difference between abstraction and encapsulation?
Abstraction hides the implementation details whereas encapsulation wraps code and
data into a single unit.
3. What is abstract class?
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
4. Can there be any abstract method without abstract class?

59 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
No, if there is any abstract method in a class, that class must be abstract.
5. Can you use abstract and final both with a method?
No, because abstract method needs to be overridden whereas you can't override final
method.
6. Is it possible to instantiate the abstract class?
No, abstract class can never be instantiated.
7. What is interface?
Interface is a blueprint of a class that have static constants and abstract methods.It
can be used to achieve fully abstraction and multiple inheritance.
8. Can you declare an interface method static?
No, because methods of an interface is abstract by default, and static and abstract
keywords can't be used together.
9. Can an Interface be final?
No, because its implementation is provided by another class.
10. What is marker interface?
An interface that have no data member and method is known as a marker interface.For
example Serializable, Cloneable etc.

VIVA QUESTIONS:

1. polymorphism is a feature that allows


2. polymorphism is expressed by the phrases one interface methods.
3.Method override is the basis .
4.Java implements using dynamic method dispatch.
5.A super class reference variable can refer to a object.
6.The type of object being referred to determines which version of an method.
7.Override methods allows java to support
8. Method override occurs only when the names and the type signature of the two
methods are
9. When a method in the subclass has the same name and type as the method in the
super class then the method in the subclass is said to the method in the
super class.
10. Difference between overloading and overriding is .

VIVA QUESTIONS

1. MOUSE_CLICKED events occurs when


2. MOUSE_DRAGGED events occurs when
60 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
3. events occur when mouse enters a component.
4. events occur when the mouse exists a component
5. MOUSE_MOVED event occurs when
6. MOUSE_PRESSED even occurs when
7. The events occur when mouse was released.
8. The event occurs when mouse wheel is moved.
9. An event source is
10. A is an object that describes the state change in a source

VIVA QUESTIONS
1. is a package in which Hashtable class is available
2.split is a method used for
3. capacity of hashtable can be determined by
4. method is used to insert record in to hash table
5. method is used to know the number of entries in hash table
6.alternative to hashtable is
7. is used to remove all entries of hash table
8.Hash table can be enumerated using
9.Scanner class is present in package
10.Buffered Reader is available in package

VIVA QUESTIONS
1) What is Thread in Java?
The thread is an independent path of execution. It's way to take advantage of multiple
CPU available in a machine. By employing multiple threads you can speed up CPU
bound task. For example, if one thread takes 100 milliseconds to do a job, you can use
10 thread to reduce that task into 10 milliseconds. Java provides excellent support for
multithreading at the language level, and it's also one of the strong selling points.

2) What is the difference between Thread and Process in Java?


The thread is a subset of Process, in other words, one process can contain multiple
threads. Two process runs on different memory space, but all threads share same
memory space. Don't confuse this with stack memory, which is different for the
different thread and used to store local data to that thread. For more detail see the
answer.

3) How do you implement Thread in Java?


At the language level, there are two ways to implement Thread in Java. An instance
of java.lang.Thread represent a thread but it needs a task to execute, which is an
instance of interface java.lang.Runnable. Since Thread class itself implement
Runnable, you can override run() method either by extending Thread class or just
implementing Runnable interface. For detailed answer and discussion see this article.

61 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
4) When to use Runnable vs Thread in Java?
2) This is a follow-up of previous multi-threading interview question. As we know
we can implement thread either by extending Thread class or implementing Runnable
interface, the question arise, which one is better and when to use one? This question
will be easy to answer if you know that Java programming language doesn't support
multiple inheritances of class, but it allows you to implement multiple interfaces. Which
means, it's better to implement Runnable then extends Thread if you also want to
extend another class e.g. Canvas or CommandListener. For more points and discussion
you can also refer this post.

6) What is the difference between start() and run() method of Thread class?
One of trick Java question from early days, but still good enough to differentiate
between shallow understanding of Java threading model start() method is used to start
newly created thread,
while start() internally calls run() method, there is difference calling run() method
directly. When you invoke run() as normal method, its called in the same thread, no
new thread is started, which is the case when you call start() method. Read this answer
for much more detailed discussion.

VIVA QUESTIONS

1. What is a IO stream?
It is a stream of data that flows from source to destination. Good example is file copying.
Two streams are involved – input stream and output stream. An input stream reads
from the file and stores the data in the process (generally in a temporary variable). The
output stream reads from the process and writes to the destination file.
2. What is the necessity of two types of streams – byte streams and character
streams? Byte streams were introduced with JDK 1.0 and operate on the files
containing ASCII characters. We know Java supports other language characters also
known as Unicode characters. To read the files containing Unicode characters, the
designers introduced character streams with JDK 1.1. As ASCII is a subset of Unicode,
for the files of English characters, we can go with either byte streams or character
streams.
3. What are the super most classes of all streams?
All the byte stream classes can be divided into two categories (input stream classes and
output stream classes) and all character streams classes into two (reader classes and
writer classes). There are four abstract classes from which all these streams are
derived. The super most class of all byte stream classes is java.io.InputStream and for
all output stream classes, java.io.OutputStream. Similarly for all reader classes is
java.io.Reader and for all writer classes is java.io.Writer.
4. What are FileInputStream and FileOutputStream?
These two are general purpose classes used by the programmer very often to copy file
to file. These classes work well with files containing less data of a few thousand bytes
as by performance these are very poor.
62 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
For larger data, it is preferred to use BufferedInputStream (or BufferedReader) and
BufferedOutputStream (or BufferedWriter).
5. Which you feel better to use – byte streams or character streams?
I feel personally to go with character streams as they are the latest. Many features exist
in character streams that do not in byte streams like a) using BufferedReader in place
of BufferedInputStreams and DataInputStream (one stream for two) and b) using
newLine() method to go for next line and for this effect we must go for extra coding in
byte streams etc.
6. What System.out.println()?
"println()" is a method of PrintStream class. "out" is a static object of PrintStream class
defined in "System" class. System is a class from java.lang package used to interact
with the underlying operating system by the programmer.
7. What are filter streams?
Filter streams are a category of IO streams whose responsibility is to add extra
functionality (advantage) to the existing streams like giving line numbers in the
destination file that do not exist int the source file
or increasing performance of copying etc.
8. Name the filter streams available?
There are four filter streams in java.io package – two in byte streams side and two in
character streams side. They are FilterInputStream, FilterOutputStream, FilterReader
and FilterWriter. These classes are abstract classes and you cannot create of objects of
these classes.
9. Name the filter stream classes on reading side of byte stream?
There are four classes – LineNumberInputStream (the extra functionality is it adds line
numbers in the destination file), DataInputStream (contains special methods like
readInt(), readDouble() and readLine() etc that can read an int, a double and a string at
a time), BufferedInputStream (gives buffering effect that increases the performance to
the peak) and PushbackInputStream (pushes the required character back to the
system).
10. What is the functionality of SequenceInputStream?
It is very useful to copy multiple source files into one destination file with very less code

VIVA QUESTIONS
1) Explain what is an algorithm in computing?
An algorithm is a well-defined computational procedure that take some value as input
and generate some value as output. In simple words, it‟s a sequence of computational
steps that converts input into the output.
2) Explain what is Quick Sort algorithm?
Quick Sort algorithm has the ability to sort list or queries quickly. It is based on the
principle of partition exchange sort or Divide and conquer. This type of algorithm
occupies less space, and it segregates the list into three main parts
• Elements less than the Pivot element
• Pivot element
• Elements greater than the Pivot element
63 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in
3) Explain what is time complexity of Algorithm?
Time complexity of an algorithm indicates the total time needed by the program to run
to completion. It is usually expressed by using the big O notation.
4) Mention what are the types of Notation used for Time Complexity?
The types of Notations used for Time Complexity includes
• Big Oh: It indicates “fewer than or the same as” <expression>iterations
• Big Omega: It indicates “more than or same as” <expression>iterations
• Big Theta: It indicates “the same as”<expression>iterations
• Little Oh: It indicates “fewer than” <expression>iterations
• Little Omega: It indicates “more than” <expression>iterations
5) Explain how binary search works?
In binary search, we compare the key with the item in the middle position of the array.
If the key is less than the item searched then it must lie in the lower half of the array,
if the key is greater than the item searched than it should be in upper half of the array.

64 | P a g e

ITM Campus, NH-75, Opposite Sithouli Railway Station, Gwalior (M.P.) - 475001, India
Mail: hodcseititm@itmgoi.in, web: www.itmgoi.in

You might also like