0% found this document useful (0 votes)
2K views50 pages

Java Practical Questions With Answers

The document contains solutions to 6 Java programming questions involving Fibonacci series, pattern printing, division based on marks, overloaded methods, constructors, and a subclass with a menu to perform calculations on an integer array. Key methods and concepts demonstrated include for loops, if/else statements, method overloading, getter/setter methods, and inheritance.

Uploaded by

masoom raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2K views50 pages

Java Practical Questions With Answers

The document contains solutions to 6 Java programming questions involving Fibonacci series, pattern printing, division based on marks, overloaded methods, constructors, and a subclass with a menu to perform calculations on an integer array. Key methods and concepts demonstrated include for loops, if/else statements, method overloading, getter/setter methods, and inheritance.

Uploaded by

masoom raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

1

INSTITUTE OF MANAGEMENT STUDIES, NOIDA


SCHOOL OF IT
Academic Session: 2020-2023
Java Programming & Dynamic Webpage Design
List of Practical

Q1. Write a program to print Fibonacci series.

Ans.

public class FibonacciSeries {

public static void main(String[] args) {

int n1 = 0, n2 = 1, n3, i, count = 10;

System.out.print(n1 + " " + n2);//printing 0 and 1

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

Q2. Write a program to print the following pattern: -

1 1 1

22 12 12

333 123 123

4444 1234 1234

55555 12345 12345


2

Ans. Pattern1:

public class Pattern {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(i);

System.out.println();

// Output:

// 1

// 22

// 333

// 4444

// 55555

Pattern 2:

public class LeftAlignedTriangle {

public static void main(String[] args) {

System.out.println("Pattern: Left-Aligned Triangle");

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(j);

System.out.println();
3

Output:

Pattern: Left-Aligned Triangle

12

123

1234

12345

Pattern 3:

public class RightAlignedTriangle {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print(j);

// Print the space needed to align the output in right direction

for (int k = 5; k > i; k--) {

System.out.print(" ");

// Print the new line

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

>= 60 and <= 79 First Division

>= 40 and <= 59 Second Division

>= 30 and <= 39 Third Division

Else False

Ans.

public class MarksDivision {

public static void main(String[] args) {

int marks[] = {100, 80, 65, 42, 35, 25};

for(int i=0;i<marks.length;i++)

if(marks[i]>=80)

System.out.println("Honors");

else if(marks[i]>=60 && marks[i]<=79)

System.out.println("First Division");

else if(marks[i]>=40 && marks[i]<=59)

System.out.println("Second Division");

else if(marks[i]>=30 && marks[i]<=39)

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,

public class OverloadedMethods {

public static void main(String[] args) {

// Call the overloaded methods

beautifulFlower();

beautifulFlower("Sunflower");

beautifulFlower("Marigold", 3);

// Method with no arguments

public static void beautifulFlower() {

System.out.println("Rose is a beautiful flower");

System.out.println("Rose is a beautiful flower");

// Method with one string argument

public static void beautifulFlower(String flower) {

System.out.println(flower + " is a beautiful flower");

System.out.println(flower + " is a beautiful flower");

System.out.println(flower + " is a beautiful flower");

System.out.println(flower + " is a beautiful flower");

System.out.println(flower + " is a beautiful flower");


6

// Method with a string and integer argument

public static void beautifulFlower(String flower, int numTimes) {

for (int i = 0; i < numTimes; i++) {

System.out.println(flower + " is a beautiful flower");

Q5. Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.

Ans.

public class Sample {

private String name;

private int age;

//constructor

public Sample(){

this.name = "";

this.age = 0;

//overloaded constructor

public Sample(String name, int age){

this.name = name;

this.age = age;

//getter and setter methods

public String getName(){

return name;

public void setName(String name){

this.name = name;
7

public int getAge(){

return age;

public void setAge(int age){

this.age = age;

//method to display data

public void display(){

System.out.println("Name: " + name);

System.out.println("Age: " + age);

public class Main {

public static void main(String[] args) {

//instantiating an object using default constructor

Sample sample1 = new Sample();

//setting values of the object

sample1.setName("John");

sample1.setAge(25);

//displaying values of the object

sample1.display();

//instantiating an object using overloaded constructor

Sample sample2 = new Sample("Mary", 30);

//displaying values of the object

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

a) Display numbers entered

b) Sum of the numbers


c) Average of the numbers

d) Maximum of the numbers

e) Minimum of the numbers

Ans.

public class Numeral{

int[] numbers = new int[10];

public Numeral(){

public void setNumbers(int[] numbers){

this.numbers = numbers;

public int[] getNumbers(){

return numbers;

public class NumberPlay extends Numeral{

public NumberPlay(){

public void displayNumbers(){

System.out.println("The numbers are: ");

for(int i=0; i < numbers.length; i++){

System.out.print(numbers[i] + " ");

}
9

public int sum(){

int sum = 0;

for(int i=0; i < numbers.length; i++){

sum += numbers[i];

return sum;

public double average(){

int sum = 0;

for(int i=0; i < numbers.length; i++){

sum += numbers[i];

return (double)sum/numbers.length;

public int max(){

int max = numbers[0];

for(int i=0; i < numbers.length; i++){

if(numbers[i] > max){

max = numbers[i];

return max;

public int min(){

int min = numbers[0];

for(int i=0; i < numbers.length; i++){

if(numbers[i] < min){

min = numbers[i];

}
10

return min;

public void menu(){

System.out.println("Menu:");

System.out.println("a) Display numbers entered");

System.out.println("b) Sum of the numbers");

System.out.println("c) Average of the numbers");

System.out.println("d) Maximum of the numbers");

System.out.println("e) Minimum of the numbers");

public static void main(String[] args){

NumberPlay np = new NumberPlay();

np.menu();

np.displayNumbers();

System.out.println("\nSum: " + np.sum());

System.out.println("Average: " + np.average());

System.out.println("Maximum: " + np.max());

System.out.println("Minimum: " + np.min());

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.

public class Weight {

private int weightInKg;

private int weightInGram;

public Weight(int kg, int gram) {

System.out.println("Weight of bundle- 5 kgs");


11

this.weightInKg = kg;

this.weightInGram = gram;

public void displayWeight() {

System.out.println("Weight in Kg: " + this.weightInKg);

System.out.println("Weight in Grams: " + this.weightInGram);

public static void main(String[] args) {

Weight wt = new Weight(5, 100);

wt.displayWeight();

Output:

Weight of bundle- 5 kgs

Weight in Kg: 5

Weight in Grams: 100

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.

public abstract class Shape {

public abstract void displayArea();

class Rectangle extends Shape {

private double length;

private double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

}
12

public double getArea() {

return length * width;

@Override

public void displayArea() {

System.out.println("Area of Rectangle: " + getArea());

class Triangle extends Shape {

private double base;

private double height;

public Triangle(double base, double height) {

this.base = base;

this.height = height;

public double getArea() {

return (base * height) / 2;

@Override

public void displayArea() {

System.out.println("Area of Triangle: " + getArea());

public class Main {

public static void main(String[] args) {

Shape shape;

shape = new Rectangle(5, 8);

shape.displayArea();

shape = new Triangle(5, 8);

shape.displayArea();
13

Output:

Area of Rectangle: 40.0

Area of Triangle: 20.0

Q9. Write a program to create an array of string and sort the array elements in alphabetical
order.

Ans.

public class SortArray {

public static void main(String[] args) {

// create an array of strings

String[] strings = {"Apple", "Banana", "Cherry", "Grape"};

// sort the array

Arrays.sort(strings);

// print the sorted array

System.out.println("Sorted array:");

for (String str : strings) {

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.

public class Shape {

double dim1, dim2;

Shape(double a, double b)

dim1 = a;

dim2 = b;

double area()

System.out.println("Area for Shape not available");

return 0;

class Rectangle extends Shape {

Rectangle(double a, double b)

super(a, b);

double area()

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

class Triangle extends Shape {

Triangle(double a, double b)

super(a, b);

}
15

double area()

System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

public class Test {

public static void main(String args[])

Shape s1 = new Rectangle(2, 3);

Shape s2 = new Triangle(2, 3);

System.out.println("Area of Rectangle is " + s1.area());

System.out.println("Area of Triangle is " + s2.area());

Output:

Area of Rectangle is 6.0

Inside Area for Triangle.

Area of Triangle is 3.0

Q11. Write a program to demonstrate use of implementing interfaces.

Ans.

public interface Animal {

public void move();

public void eat();

public class Dog implements Animal {

public void move() {

System.out.println("Dogs can move.");

}
16

public void eat() {

System.out.println("Dogs can eat.");

public class Test {

public static void main(String[] args) {

Dog d = new Dog();

d.move();

d.eat();

Output:

Dogs can move.

Dogs can eat.

Q12. Write a Java Program to implement multilevel inheritance by applying various access
controls to its data members and methods.

Ans.

public class MultilevelInheritance {

public static void main(String[] args) {

// create Parent class object

ParentClass parentObj = new ParentClass();

// create Child class object

ChildClass childObj = new ChildClass();

// create GrandChild class object

GrandChildClass grandChildObj = new GrandChildClass();

// access parent class data

System.out.println("Parent Class Data: ");

System.out.println(parentObj.parentData);

// access parent class method


17

parentObj.parentMethod();

// access child class data

System.out.println("\nChild Class Data: ");

System.out.println(childObj.childData);

// access child class method

childObj.childMethod();

// access grandchild class data

System.out.println("\nGrandChild Class Data: ");

System.out.println(grandChildObj.grandChildData);

// access grandchild class method

grandChildObj.grandChildMethod();

class ParentClass {

// private data member of parent class

private int parentData = 100;

// public method of parent class

public void parentMethod() {

System.out.println("Parent Class Method");

class ChildClass extends ParentClass {

// private data member of child class

private int childData = 200;

// public method of child class

public void childMethod() {

System.out.println("Child Class Method");

class GrandChildClass extends ChildClass {


18

// private data member of grandchild class

private int grandChildData = 300;

// public method of grandchild class

public void grandChildMethod() {

System.out.println("GrandChild Class Method");

Output:

Parent Class Data:

100

Parent Class Method

Child Class Data:

200

Child Class Method

GrandChild Class Data:

300

GrandChild Class Method

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.

public class A extends Thread {

int[] arr;

A(int[] arr) {

this.arr = arr;

public void run() {

for (int x : arr) {

System.out.println("Value from A: " + x);

}
19

public class B extends Thread {

public void run() {

for (int i = 0; i < 10; i++) {

System.out.println("Message from B: This is the message!");

public class C extends Thread {

public void run() {

for (int i = 0; i <= 10; i++) {

System.out.println("Value from C: " + i);

if (i == 5) {

try {

Thread.sleep(2000);

} catch (InterruptedException ex) {

ex.printStackTrace();

public class Main {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

A threadA = new A(arr);

B threadB = new B();

C threadC = new C();

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

Message from B: This is the message!

Value from A: 6

Value from A: 7

Value from A: 8

Value from A: 9

Value from A: 10

Message from B: This is the message!

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

Message from B: This is the message!


21

Q14. Write a program using HTML to create a virtual lab related to any subject of your
choice.

Ans. <!DOCTYPE html>

<html>

<head>

<title>Virtual Lab</title>

</head>

<body>

<h1>Introduction to Physics Lab</h1>

<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>

<li>Explore the different types of forces.</li>

<li>Learn how to calculate motion.</li>

<li>Discover the different forms of energy.</li>

</ul>

<h2>Materials</h2>

<ul>

<li>Computer</li>

<li>Internet access</li>

<li>Calculator</li>

</ul>

<h2>Instructions</h2>

<ol>

<li>Go to the website <a href="https://www.physicsclassroom.com/">The Physics


Classroom</a> to explore the basics of physics.</li>

<li>Use the calculator to calculate the motion of an object.</li>

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

Introduction to Physics Lab

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

• Explore the different types of forces.

• Learn how to calculate motion.

• Discover the different forms of energy.

Materials

• Computer

• Internet access

• Calculator

Instructions

1. Go to the website The Physics Classroom to explore the basics of physics.

2. Use the calculator to calculate the motion of an object.

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.

Q15. Write a program using HTML to prepare a simple student registration

form.
23

Ans. <!DOCTYPE html>

<html>

<head>

<title>Student Registration Form</title>

</head>

<body>

<h1>Student Registration Form</h1>

<form action="">

<fieldset>

<legend>Personal Info</legend>

<label for="name">Name:</label>

<input type="text" name="name" id="name"><br>

<label for="fatherName">Father's Name:</label>

<input type="text" name="fatherName" id="fatherName"><br>

<label for="dob">Date of Birth:</label>

<input type="date" name="dob" id="dob"><br>

</fieldset>

<fieldset>

<legend>Contact Info</legend>

<label for="address">Address:</label>

<textarea name="address" id="address" cols="30"

rows="3"></textarea><br>

<label for="phone">Phone:</label>

<input type="tel" name="phone" id="phone"><br>

<label for="email">Email:</label>
24

<input type="email" name="email" id="email"><br>

</fieldset>

<input type="submit" value="Submit">

</form>

</body>

</html>

OUTPUT:

Student Registration Form

Personal Info

Name:

Father's Name:

Date of Birth:

Contact Info

Address:

Phone:

Email:

Submit

Q16. Write a program to show the functioning of at least 10 string handling

function.

Ans.

public class StringHandling {

public static void main(String[] args) {

// Declaring a string

String str = "This is a string handling program";


25

// 1. length()

System.out.println("The length of the given string is: " + str.length());

// 2. charAt()

System.out.println("The character at position 5 is: " + str.charAt(5));

// 3. indexOf()

System.out.println("The index of first 's' is: " + str.indexOf('s'));

// 4. substring()

System.out.println("The substring from 14 to end is: " + str.substring(14));

// 5. toLowerCase()

System.out.println("The string in lowercase: " + str.toLowerCase());

// 6. toUpperCase()

System.out.println("The string in uppercase: " + str.toUpperCase());

// 7. trim()

String s = " Trim the spaces ";

System.out.println("The string after trimming the spaces: " + s.trim());

// 8. replace()

System.out.println("The string after replacing 'program' with 'application':

"

+ str.replace("program", "application"));

// 9. equals()

String str1 = "Hello World";

String str2 = "Hello World";

System.out.println("Checking if both strings are equal: " +

str1.equals(str2));

// 10. contains()

System.out.println("Checking if the string contains 'string': " +

str.contains("string"));

}
26

Output:

The length of the given string is: 31

The character at position 5 is: s

The index of first 's' is: 3

The substring from 14 to end is: handling program

The string in lowercase: this is a string handling program

The string in uppercase: THIS IS A STRING HANDLING PROGRAM

The string after trimming the spaces: Trim the spaces

The string after replacing 'program' with 'application': This is a string handling

application

Checking if both strings are equal: true

Checking if the string contains 'string': true

Q17. Write a program to show the functioning of vector.

Ans.

import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

// Creating a Vector of Strings

Vector<String> vector = new Vector<String>();

// Adding elements to a Vector

vector.add("Apple");

vector.add("Mango");

vector.add("Orange");

vector.add("Strawberry");

vector.add("Grapes");

// Displaying the Vector elements

System.out.println("Vector elements are: ");

for (String str : vector) {

System.out.println(str);
27

// Adding an element at the specified index

vector.add(2,"Lemon");

// Displaying the Vector elements after adding the new element

System.out.println("Vector elements after adding the new element are:");

for (String str : vector) {

System.out.println(str);

Output:

Vector elements are:

Apple

Mango

Orange

Strawberry

Grapes

Vector elements after adding the new element are:

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.*;

public class CheckboxExample extends JApplet implements ItemListener {

// Declare Checkbox Variables

JLabel label;

JCheckBox checkBox1;

JCheckBox checkBox2;

public void init() {

// Set layout

setLayout(new FlowLayout());

// Initialize checkboxes

checkBox1 = new JCheckBox("Show Text");

checkBox2 = new JCheckBox("Show Image");

// Add checkboxes to the form

add(checkBox1);

add(checkBox2);

// Add ItemListener to checkboxes

checkBox1.addItemListener(this);

checkBox2.addItemListener(this);

// Initialize label

label = new JLabel();

add(label);

// Handle Item Events

public void itemStateChanged(ItemEvent ie) {

// Get checkbox state

boolean showText = checkBox1.isSelected();

boolean showImage = checkBox2.isSelected();

// Set label text

label.setText("The checkbox states are: " + showText + ", " + showImage);

// Set label image


29

if (showImage)

label.setIcon(new ImageIcon("image.png"));

else

label.setIcon(null);

// Output

// Initially, both checkboxes are unchecked, and the output is:

// The checkbox states are: false, false

// If the user checks both checkboxes, the output is:

// The checkbox states are: true, true

Q19. Write a program using applet to handle the button click event.

Ans.

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class ButtonEvent extends Applet implements ActionListener{

Button b;

public void init(){

b=new Button("Click Here");

add(b);

b.addActionListener(this);

public void actionPerformed(ActionEvent e) {

b.setLabel("You clicked me");

public void paint(Graphics g){

g.drawString("Welcome to the button event handling program",20,20);

}
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".

Q20.Write a program using AWT to implement a simple calculator.

Ans.

import java.awt.*;

import java.awt.event.*;

public class Calculator extends Frame implements ActionListener {

Label l1, l2, l3;

TextField t1, t2, t3;

Button b1, b2, b3, b4;

Calculator() {

setLayout(new FlowLayout());

l1 = new Label("First Number");

add(l1);

t1 = new TextField(10);

add(t1);

l2 = new Label("Second Number");

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);

public void actionPerformed(ActionEvent e) {

int n1 = Integer.parseInt(t1.getText());

int n2 = Integer.parseInt(t2.getText());

int result = 0;

if (e.getSource() == b1)

result = n1 + n2;

else if (e.getSource() == b2)

result = n1 - n2;

else if (e.getSource() == b3)

result = n1 * n2;

else if (e.getSource() == b4)

result = n1 / n2;
32

t3.setText(result + "");

public static void main(String[] args) {

new Calculator();

OUTPUT:

Enter the two numbers:

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.*;

public class StudentRegistrationForm extends Applet implements ActionListener {

Label lName, lId, lAge;

TextField tName, tId, tAge;

Button bSubmit;

String name, id, age;

public void init() {

lName = new Label("Name: ");

lId = new Label("Id: ");

lAge = new Label("Age: ");

tName = new TextField(20);

tId = new TextField(20);

tAge = new TextField(20);

bSubmit = new Button("Submit");

add(lName);
33

add(tName);

add(lId);

add(tId);

add(lAge);

add(tAge);

add(bSubmit);

bSubmit.addActionListener(this);

public void actionPerformed(ActionEvent ae) {

name = tName.getText();

id = tId.getText();

age = tAge.getText();

System.out.println("Student Registration Details:");

System.out.println("Name: "+name);

System.out.println("Id: "+id);

System.out.println("Age: "+age);

Output:

Student Registration Details:

Name: John Doe

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.*;

public class DecimalToBinary {


34

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter a decimal number : ");

int decimalNumber = input.nextInt();

int[] binaryNumber = new int[50];

int i = 0;

while (decimalNumber > 0) {

binaryNumber[i] = decimalNumber % 2;

decimalNumber = decimalNumber / 2;

i++;

System.out.print("Binary Number : ");

for (int j = i - 1; j >= 0; j--) {

System.out.print(binaryNumber[j]);

System.out.println();

//Binary to Decimal

import java.util.*;

public class BinaryToDecimal {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter a binary number : ");

String binaryNumberInput = input.nextLine();

int binaryNumber = Integer.parseInt(binaryNumberInput);

int decimalNumber = 0;

int i = 0;

while (binaryNumber != 0) {

decimalNumber += (binaryNumber % 10) * Math.pow(2, i);


35

binaryNumber /= 10;

i++;

System.out.println("Decimal Number : " + decimalNumber);

Output

//Enter a decimal number :

//15

//Binary Number : 1111

//Enter a binary number :

//1111

//Decimal Number : 15

Q23. Write a program using AWT to implement a notepad application.

Ans.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Notepad extends Frame implements ActionListener

TextArea textArea;

MenuBar menuBar;

Menu fileMenu, editMenu;

MenuItem newItem, openItem, saveItem, exitItem, copyItem, pasteItem, cutItem;

public Notepad()

setTitle("Notepad");

setSize(500, 400);
36

setLocationRelativeTo(null);

setVisible(true);

setLayout(new BorderLayout());

textArea = new TextArea();

add(textArea, BorderLayout.CENTER);

menuBar = new MenuBar();

fileMenu = new Menu("File");

editMenu = new Menu("Edit");

newItem = new MenuItem("New");

openItem = new MenuItem("Open");

saveItem = new MenuItem("Save");

exitItem = new MenuItem("Exit");

copyItem = new MenuItem("Copy");

pasteItem = new MenuItem("Paste");

cutItem = new MenuItem("Cut");

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);

public void actionPerformed(ActionEvent e)

if(e.getSource() == newItem)

textArea.setText("");

else if(e.getSource() == openItem)

// TODO: Add code for opening a file

else if(e.getSource() == saveItem)

// TODO: Add code for saving a file

else if(e.getSource() == exitItem)

System.exit(0);

else if(e.getSource() == copyItem)

textArea.copy();

else if(e.getSource() == pasteItem)

textArea.paste();
38

else if(e.getSource() == cutItem)

textArea.cut();

public static void main(String[] args)

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.*;

public class JDBCExample {

public static void main(String[] args) {

try {

//Registering the Driver

Class.forName("com.mysql.jdbc.Driver");

//Getting the connection

String mysqlUrl = "jdbc:mysql://localhost/employeedb";

Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

//Creating a Statement Object


39

Statement stmt = con.createStatement();

//Executing the query

String query = "SELECT * FROM Employees WHERE salary > 5000";

ResultSet rs = stmt.executeQuery(query);

//Processing the Result

while (rs.next()) {

System.out.println("Employee ID: " + rs.getInt("EmployeeID"));

System.out.println("Employee Name: " + rs.getString("Name"));

System.out.println("Employee Salary: " + rs.getInt("Salary"));

System.out.println("Employee Address: " + rs.getString("Address"));

System.out.println("-------------------------------------");

//Closing the connection

con.close();

} catch (Exception e) {

System.out.println(e);

Output:

Employee ID: 101

Employee Name: John

Employee Salary: 10000

Employee Address: New York

-------------------------------------

Employee ID: 102

Employee Name: Mary

Employee Salary: 7000


40

Employee Address: Los Angeles

-------------------------------------

Employee ID: 103

Employee Name: Adam

Employee Salary: 8000

Employee Address: London

-------------------------------------

Q25. Write a program using JDBC to fetch the detail of required student from existing
database whose id > 4.

Ans.

import java.sql.*;

public class StudentFetch {

public static void main(String[] args) {

// Establishing Connection

String url = "jdbc:mysql://localhost:3306/studentdb";

String username = "root";

String password = "****";

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection(url,username,password);

//Creating Statement

Statement stmt = con.createStatement();

//Executing query

String sql = "SELECT * FROM student WHERE id > 4";

ResultSet rs = stmt.executeQuery(sql);

//Fetching Results

while(rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");


41

int age = rs.getInt("age");

String course = rs.getString("course");

//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.*;

public class NetworkServer {

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

ServerSocket serverSocket = null;

try {

serverSocket = new ServerSocket(4444);

} catch (IOException e) {

System.err.println("Could not listen on port: 4444.");

System.exit(1);

Socket clientSocket = null;

try {

System.out.println("Waiting for client on port: 4444.");

clientSocket = serverSocket.accept();

} catch (IOException e) {

System.err.println("Accept failed.");

System.exit(1);

System.out.println("Connection successful");

System.out.println("Waiting for input.....");

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),

true);
43

BufferedReader in = new BufferedReader(

new InputStreamReader(clientSocket.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {

System.out.println("Server: " + inputLine);

out.println(inputLine);

if (inputLine.equals("Bye."))

break;

out.close();

in.close();

clientSocket.close();

serverSocket.close();

//Client

import java.net.*;

import java.io.*;

public class NetworkClient {

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

Socket kkSocket = null;

PrintWriter out = null;

BufferedReader in = null;

try {

kkSocket = new Socket("localhost", 4444);

out = new PrintWriter(kkSocket.getOutputStream(), true);

in = new BufferedReader(new InputStreamReader(kkSocket

.getInputStream()));

} catch (UnknownHostException e) {
44

System.err.println("Don't know about host: localhost.");

System.exit(1);

} catch (IOException e) {

System.err.println("Couldn't get I/O for the connection to: localhost.");

System.exit(1);

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

String fromServer;

String fromUser;

while ((fromServer = in.readLine()) != null) {

System.out.println("Server: " + fromServer);

if (fromServer.equals("Bye."))

break;

fromUser = stdIn.readLine();

if (fromUser != null) {

System.out.println("Client: " + fromUser);

out.println(fromUser);

out.close();

in.close();

stdIn.close();

kkSocket.close();

Output:

Waiting for client on port: 4444.

Connection successful

Waiting for input.....


45

Server: Hello

Client: Hi

Server: How are you?

Client: I'm doing good.

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.*;

public class ChatServer

public static void main(String[] args) throws IOException

ServerSocket serverSocket = new ServerSocket(8080);

System.out.println("Chat server is running on port 8080...");


47

Socket clientSocket = serverSocket.accept();

System.out.println("A new client is connected : " + clientSocket);

DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());

DataOutputStream outputStream = new


DataOutputStream(clientSocket.getOutputStream());

String messageIn = "";

String messageOut = "";

while (!messageIn.equals("bye"))

messageIn = inputStream.readUTF();

System.out.println("Client: " + messageIn);

messageOut = "You said: " + messageIn;

outputStream.writeUTF(messageOut);

outputStream.flush();

inputStream.close();

outputStream.close();

clientSocket.close();

serverSocket.close();

//Output

Chat server is running on port 8080...

A new client is connected : Socket[addr=/127.0.0.1,port=45454,localport=8080]

Client: Hi, how are you?

Client: I'm good. How about you?

Client: bye

Q29. Write a program to understand the servlet processing.

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;

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Servlet Processing Example";

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " +

"transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor=\"#f0f0f0\">\n" +

"<h1 align=\"center\">" + title + "</h1>\n" +

"<ul>\n" +

" <li><b>Request Method</b>: "

+ request.getMethod() + "\n" +

" <li><b>Request URI</b>: "

+ request.getRequestURI() + "\n" +

" <li><b>Context Path</b>: "


49

+ request.getContextPath() + "\n" +

" <li><b>Servlet Path</b>: "

+ request.getServletPath() + "\n" +

" <li><b>Path Info</b>: "

+ request.getPathInfo() + "\n" +

" <li><b>Query String</b>: "

+ request.getQueryString() + "\n" +

"</ul>\n" +

"</body></html>");

Output:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en">

<html>

<head><title>Servlet Processing Example</title></head>

<body bgcolor="#f0f0f0">

<h1 align="center">Servlet Processing Example</h1>

<ul>

<li><b>Request Method</b>: GET

<li><b>Request URI</b>: /MyServlet

<li><b>Context Path</b>:

<li><b>Servlet Path</b>: /MyServlet

<li><b>Path Info</b>: null

<li><b>Query String</b>: null

</ul>

</body></html>

Q30. Write a program to understand the JSP processing.

Ans.
50

//This is a simple example of a JSP program.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>JSP Processing Example</title>

</head>

<body>

<h1>JSP Processing Example</h1>

<%

//This section is the Java code.

String message = "Hello World!";

%>

<p>

<%= message %>

</p>

</body>

</html>

//Output:

JSP Processing Example

Hello World!

You might also like