Java Practical Questions With Answers
Java Practical Questions With Answers
Ans.
for(i = 2; i < count; ++i)//loop starts from 2 because 0 and 1 are already printed
n3 = n1 + n2;
System.out.print(" "+n3);
n1 = n2;
n2 = n3;
Output:
0 1 1 2 3 5 8 13 21 34 55
1 1 1
22 12 12
Ans. Pattern1:
System.out.print(i);
System.out.println();
// Output:
// 1
// 22
// 333
// 4444
// 55555
Pattern 2:
System.out.print(j);
System.out.println();
3
Output:
12
123
1234
12345
Pattern 3:
System.out.print(j);
System.out.print(" ");
System.out.println();
}
4
Output:
12
123
1234
12345
Q3. Write a program to read the given input array of marks and find the allocated division
as follows: -
Marks Division
>= 80 Honours
Else False
Ans.
for(int i=0;i<marks.length;i++)
if(marks[i]>=80)
System.out.println("Honors");
System.out.println("First Division");
System.out.println("Second Division");
System.out.println("Third Division");
5
else
System.out.println("Fail");
Q4. Write a program that has overloaded methods. The first method should accept no
arguments, the second method will accept one string and the third method will accept a
string and an integer. The first method should display the message “Rose is beautiful
flower” twice. The second method should display the message “Sunflower is a beautiful
flower” five times. The third method should display the message “Marigold is a beautiful
flower” by number of times values received in the argument.
Ans,
beautifulFlower();
beautifulFlower("Sunflower");
beautifulFlower("Marigold", 3);
Q5. Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.
Ans.
//constructor
public Sample(){
this.name = "";
this.age = 0;
//overloaded constructor
this.name = name;
this.age = age;
return name;
this.name = name;
7
return age;
this.age = age;
sample1.setName("John");
sample1.setAge(25);
sample1.display();
sample2.display();
Output:
Name: John
8
Age: 25
Name: Mary
Age: 30
Q6. Create a class called Numeral that has an array of 10 integers. Create a subclass called
Number Play which has a menu as follows: -
Ans.
public Numeral(){
this.numbers = numbers;
return numbers;
public NumberPlay(){
}
9
int sum = 0;
sum += numbers[i];
return sum;
int sum = 0;
sum += numbers[i];
return (double)sum/numbers.length;
max = numbers[i];
return max;
min = numbers[i];
}
10
return min;
System.out.println("Menu:");
np.menu();
np.displayNumbers();
Q7. Write a program that will display the message “Weight of bundle- 5 kgs” in a
constructor and display the weight in kilograms and grams passed as an argument.
Ans.
this.weightInKg = kg;
this.weightInGram = gram;
wt.displayWeight();
Output:
Weight in Kg: 5
Q8. Create an abstract class Shape to describe a shape with two dimensions. Define a
method to display the area of shape. Create two subclasses: Rectangle and Triangle. Call
the display function using reference variable of the class shape.
Ans.
this.length = length;
this.width = width;
}
12
@Override
this.base = base;
this.height = height;
@Override
Shape shape;
shape.displayArea();
shape.displayArea();
13
Output:
Q9. Write a program to create an array of string and sort the array elements in alphabetical
order.
Ans.
Arrays.sort(strings);
System.out.println("Sorted array:");
System.out.println(str);
Output:
Sorted array:
Apple
Banana
Cherry
Grape
Q10. Write a Java Program to implement inheritance and demonstrate use of method
overriding.
14
Ans.
Shape(double a, double b)
dim1 = a;
dim2 = b;
double area()
return 0;
Rectangle(double a, double b)
super(a, b);
double area()
Triangle(double a, double b)
super(a, b);
}
15
double area()
Output:
Ans.
}
16
d.move();
d.eat();
Output:
Q12. Write a Java Program to implement multilevel inheritance by applying various access
controls to its data members and methods.
Ans.
System.out.println(parentObj.parentData);
parentObj.parentMethod();
System.out.println(childObj.childData);
childObj.childMethod();
System.out.println(grandChildObj.grandChildData);
grandChildObj.grandChildMethod();
class ParentClass {
Output:
100
200
300
Q13. Write a program to create three thread class A, B and C. Thread class A will print each
value of defined array, B class will print a message 10 time. Class C will responsible for
printing the value from 1 to 10 and sleep for few times when reached the value 5.
Ans.
int[] arr;
A(int[] arr) {
this.arr = arr;
}
19
if (i == 5) {
try {
Thread.sleep(2000);
ex.printStackTrace();
threadA.start();
20
threadB.start();
threadC.start();
Output:
Value from A: 1
Value from A: 2
Value from A: 3
Value from A: 4
Value from A: 5
Value from A: 6
Value from A: 7
Value from A: 8
Value from A: 9
Value from A: 10
Value from C: 0
Value from C: 1
Value from C: 2
Value from C: 3
Value from C: 4
Value from C: 5
Value from C: 6
Value from C: 7
Value from C: 8
Value from C: 9
Value from C: 10
Q14. Write a program using HTML to create a virtual lab related to any subject of your
choice.
<html>
<head>
<title>Virtual Lab</title>
</head>
<body>
<p>Welcome to the Introduction to Physics Lab! This virtual lab will give you an
introduction to the basics of physics. You will learn about the different types of forces,
motion, and energy. </p>
<h2>Objectives</h2>
<ul>
</ul>
<h2>Materials</h2>
<ul>
<li>Computer</li>
<li>Internet access</li>
<li>Calculator</li>
</ul>
<h2>Instructions</h2>
<ol>
<li>Research the different forms of energy and how they are used.</li>
22
</ol>
<h2>Conclusion</h2>
<p>Congratulations! Now you know the basics of physics and how to calculate motion and
energy. You are now ready to explore more of the fascinating world of physics.</p>
</body>
</html>
OUTPUT:
Welcome to the Introduction to Physics Lab! This virtual lab will give you an introduction to
the basics of physics. You will learn about the different types of forces, motion, and energy.
Objectives
Materials
• Computer
• Internet access
• Calculator
Instructions
3. Research the different forms of energy and how they are used.
Conclusion
Congratulations! Now you know the basics of physics and how to calculate motion and
energy. You are now ready to explore more of the fascinating world of physics.
form.
23
<html>
<head>
</head>
<body>
<form action="">
<fieldset>
<legend>Personal Info</legend>
<label for="name">Name:</label>
</fieldset>
<fieldset>
<legend>Contact Info</legend>
<label for="address">Address:</label>
rows="3"></textarea><br>
<label for="phone">Phone:</label>
<label for="email">Email:</label>
24
</fieldset>
</form>
</body>
</html>
OUTPUT:
Personal Info
Name:
Father's Name:
Date of Birth:
Contact Info
Address:
Phone:
Email:
Submit
function.
Ans.
// Declaring a string
// 1. length()
// 2. charAt()
// 3. indexOf()
// 4. substring()
// 5. toLowerCase()
// 6. toUpperCase()
// 7. trim()
// 8. replace()
"
+ str.replace("program", "application"));
// 9. equals()
str1.equals(str2));
// 10. contains()
str.contains("string"));
}
26
Output:
The string after replacing 'program' with 'application': This is a string handling
application
Ans.
import java.util.Vector;
vector.add("Apple");
vector.add("Mango");
vector.add("Orange");
vector.add("Strawberry");
vector.add("Grapes");
System.out.println(str);
27
vector.add(2,"Lemon");
System.out.println(str);
Output:
Apple
Mango
Orange
Strawberry
Grapes
Apple
Mango
Lemon
Orange
Strawberry
Grapes
Q18. Write a program using applet to handle the various checkbox event.
Ans.
import java.awt.*;
import java.awt.event.*;
28
import javax.swing.*;
JLabel label;
JCheckBox checkBox1;
JCheckBox checkBox2;
// Set layout
setLayout(new FlowLayout());
// Initialize checkboxes
add(checkBox1);
add(checkBox2);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
// Initialize label
add(label);
if (showImage)
label.setIcon(new ImageIcon("image.png"));
else
label.setIcon(null);
// Output
Q19. Write a program using applet to handle the button click event.
Ans.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Button b;
add(b);
b.addActionListener(this);
}
30
Output:
A window will open with text "Welcome to the button event handling program" and a button
"Click Here". When the button is clicked, the text of the button changes to "You clicked me".
Ans.
import java.awt.*;
import java.awt.event.*;
Calculator() {
setLayout(new FlowLayout());
add(l1);
t1 = new TextField(10);
add(t1);
add(l2);
t2 = new TextField(10);
add(t2);
b1 = new Button("+");
add(b1);
b1.addActionListener(this);
b2 = new Button("-");
add(b2);
b2.addActionListener(this);
31
b3 = new Button("*");
add(b3);
b3.addActionListener(this);
b4 = new Button("/");
add(b4);
b4.addActionListener(this);
l3 = new Label("Result");
add(l3);
t3 = new TextField(10);
t3.setEditable(false);
add(t3);
setTitle("Calculator");
setSize(250, 300);
setVisible(true);
int n1 = Integer.parseInt(t1.getText());
int n2 = Integer.parseInt(t2.getText());
int result = 0;
if (e.getSource() == b1)
result = n1 + n2;
result = n1 - n2;
result = n1 * n2;
result = n1 / n2;
32
t3.setText(result + "");
new Calculator();
OUTPUT:
23
Q21. Write a program using AWT to implement a simple students’ registration form.
Ans.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Button bSubmit;
add(lName);
33
add(tName);
add(lId);
add(tId);
add(lAge);
add(tAge);
add(bSubmit);
bSubmit.addActionListener(this);
name = tName.getText();
id = tId.getText();
age = tAge.getText();
System.out.println("Name: "+name);
System.out.println("Id: "+id);
System.out.println("Age: "+age);
Output:
Id: 12345
Age: 25
Q22. Write a program to convert a decimal number into binary and vice versa.
Ans.
//Decimal to Binary
import java.util.*;
int i = 0;
binaryNumber[i] = decimalNumber % 2;
decimalNumber = decimalNumber / 2;
i++;
System.out.print(binaryNumber[j]);
System.out.println();
//Binary to Decimal
import java.util.*;
int decimalNumber = 0;
int i = 0;
while (binaryNumber != 0) {
binaryNumber /= 10;
i++;
Output
//15
//1111
//Decimal Number : 15
Ans.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
TextArea textArea;
MenuBar menuBar;
public Notepad()
setTitle("Notepad");
setSize(500, 400);
36
setLocationRelativeTo(null);
setVisible(true);
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);
newItem.addActionListener(this);
openItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);
copyItem.addActionListener(this);
pasteItem.addActionListener(this);
cutItem.addActionListener(this);
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.add(cutItem);
37
menuBar.add(fileMenu);
menuBar.add(editMenu);
setMenuBar(menuBar);
if(e.getSource() == newItem)
textArea.setText("");
System.exit(0);
textArea.copy();
textArea.paste();
38
textArea.cut();
new Notepad();
/Output:
// A Notepad application will be launched with a blank text area and the menu bar
containing the File and Edit menus. The File menu will contain New, Open, Save, and Exit
options and the Edit menu will contain Copy, Paste, and Cut options.
Q24.Write a program using JDBC to fetch the detail of employees from existing database
whose salary > 5000.
Ans.
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println("-------------------------------------");
con.close();
} catch (Exception e) {
System.out.println(e);
Output:
-------------------------------------
-------------------------------------
-------------------------------------
Q25. Write a program using JDBC to fetch the detail of required student from existing
database whose id > 4.
Ans.
import java.sql.*;
// Establishing Connection
try {
Class.forName("com.mysql.jdbc.Driver");
//Creating Statement
//Executing query
ResultSet rs = stmt.executeQuery(sql);
//Fetching Results
while(rs.next()) {
int id = rs.getInt("id");
//Printing Results
System.out.println("ID: "+id);
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Course: "+course+"\n");
//Closing Connection
con.close();
catch(Exception ex) {
System.out.println(ex);
/* Output:
ID: 5
Name: John
Age: 20
Course: Java
ID: 6
Name: Jake
Age: 21
Course: Python
ID: 7
Name: Jack
42
Age: 22
Course: C++ */
Q26. Write a program using socket programming for data communication between client
and server over socket.
Ans.
//server
import java.net.*;
import java.io.*;
try {
} catch (IOException e) {
System.exit(1);
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
System.out.println("Connection successful");
true);
43
new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
out.println(inputLine);
if (inputLine.equals("Bye."))
break;
out.close();
in.close();
clientSocket.close();
serverSocket.close();
//Client
import java.net.*;
import java.io.*;
BufferedReader in = null;
try {
.getInputStream()));
} catch (UnknownHostException e) {
44
System.exit(1);
} catch (IOException e) {
System.exit(1);
String fromServer;
String fromUser;
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
out.println(fromUser);
out.close();
in.close();
stdIn.close();
kkSocket.close();
Output:
Connection successful
Server: Hello
Client: Hi
Server: Bye.
Q27. Write a program using socket programming in which client will receive a value from
the user and send it to server over socket connection. Server is responsible for generating
the factorial of the given number as well as find the Fibonacci series up to that limit.
Ans.
//Server side
import java.io.*;
import java.net.*;
public class Server {
public static void main(String arg[]) throws Exception {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is running on port 5000");
Socket socket = serverSocket.accept();
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new
DataOutputStream(socket.getOutputStream());
int number = dataInputStream.readInt();
System.out.println("Number received from client: " + number);
//Calculating factorial
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
//Calculating Fibonacci series
int a = 0;
int b = 1;
String fibonacciSeries = "";
for (int i = 0; i < number; i++) {
int c = a + b;
a = b;
b = c;
fibonacciSeries += c + " ";
}
//Sending result to Client
dataOutputStream.writeInt(factorial);
dataOutputStream.writeUTF(fibonacciSeries);
dataOutputStream.flush();
}
}
46
//Client side
import java.io.*;
import java.net.*;
public class Client {
public static void main(String arg[]) throws Exception {
Socket socket = new Socket("localhost", 5000);
DataInputStream dataInputStream = new DataInputStream(System.in);
DataOutputStream dataOutputStream = new
DataOutputStream(socket.getOutputStream());
//Receiving value from user
System.out.println("Enter the number to calculate factorial and Fibonacci series:");
int number = dataInputStream.read();
//Sending the value to server
dataOutputStream.writeInt(number);
dataOutputStream.flush();
//Receiving result from server
DataInputStream dataInputStream1 = new DataInputStream(socket.getInputStream());
int factorial = dataInputStream1.readInt();
String fibonacciSeries = dataInputStream1.readUTF();
//Printing the result
System.out.println("Factorial of " + number + " is " + factorial);
System.out.println("Fibonacci series up to " + number + " is " + fibonacciSeries);
}
}
Output:
Enter the number to calculate factorial and Fibonacci series:
5
Factorial of 5 is 120
Fibonacci series up to 5 is 1 1 2 3 5
Q28. Write a program using socket programming to create a chat server application.
Ans.
import java.net.*;
import java.io.*;
while (!messageIn.equals("bye"))
messageIn = inputStream.readUTF();
outputStream.writeUTF(messageOut);
outputStream.flush();
inputStream.close();
outputStream.close();
clientSocket.close();
serverSocket.close();
//Output
Client: bye
Ans.
48
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
HttpServletResponse response)
response.setContentType("text/html");
String docType =
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<ul>\n" +
+ request.getMethod() + "\n" +
+ request.getRequestURI() + "\n" +
+ request.getContextPath() + "\n" +
+ request.getServletPath() + "\n" +
+ request.getPathInfo() + "\n" +
+ request.getQueryString() + "\n" +
"</ul>\n" +
"</body></html>");
Output:
<html>
<body bgcolor="#f0f0f0">
<ul>
<li><b>Context Path</b>:
</ul>
</body></html>
Ans.
50
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<%
%>
<p>
</p>
</body>
</html>
//Output:
Hello World!