0% found this document useful (0 votes)
7 views11 pages

23BCE10333 Java Experiments

The document contains various Java programming experiments by Uttakarsh Barnwal, including basic programs for printing 'Hello World', accepting user input, and calculating the area and perimeter of a circle. It also covers advanced topics such as inheritance, exception handling, serialization, threading, and event handling in graphical user interfaces. Each section includes code snippets and expected outputs for clarity.

Uploaded by

Aadiy Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

23BCE10333 Java Experiments

The document contains various Java programming experiments by Uttakarsh Barnwal, including basic programs for printing 'Hello World', accepting user input, and calculating the area and perimeter of a circle. It also covers advanced topics such as inheritance, exception handling, serialization, threading, and event handling in graphical user interfaces. Each section includes code snippets and expected outputs for clarity.

Uploaded by

Aadiy Khan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Experiments

Name :- Uttakarsh Barnwal


Reg. No. :- 23BCE10333

Q. 1 Java program to print “Hello World”.

Ans:-
public class JavaExperiment {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Output :-

Q. 1.1 How to accept input from keyboard in Java?


a. Using Scanner Class
b. Using Console Class
c. Using InputStreamReader and
d. BufferedReader Class

Ans :-

a.
import [Link];
public class JavaExperiment {
public static void main(String[] args) {
Scanner reader = new Scanner([Link]); // Create scanner object

[Link]("Enter your name: ");


String name = [Link](); // Reads a string

[Link]("Enter your age: ");


int age = [Link](); // Reads an integer

[Link]("Hello " + name + ", you are " + age + " years old.");

[Link](); // Good practice to close the stream


}
}

Output:-

b.
public class JavaExperiment {
public static void main(String[] args) {
[Link] console = [Link]();

if (console != null) {
String username = [Link]("Enter username: ");
char[] password = [Link]("Enter password: ");

[Link]("User " + username + " logged in.");


} else {
[Link]("No console available.");
}
}
}

Output:-

c.
import [Link];
import [Link];
import [Link];

public class JavaExperiment {


public static void main(String[] args) throws IOException {
// Chain the classes: [Link] -> Reader -> Buffer
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter some text: ");


String input = [Link]();

[Link]("You typed: " + input);


}
}

Output:-

Q.2 Implement Arrays, Packages, Inheritance, Exception Handling, Serialization and Threading
in Java.

Ans :-

import [Link].*;
import [Link];

// --- INHERITANCE ---


// Base class for any item
class BaseItem implements Serializable {
String name;
BaseItem(String name) { [Link] = name; }
}

// Subclass inheriting from BaseItem


class Task extends BaseItem {
// --- SERIALIZATION ---
// serialVersionUID ensures version compatibility during saving/loading
private static final long serialVersionUID = 1L;
int priority;
Task(String name, int priority) {
super(name);
[Link] = priority;
}

@Override
public String toString() {
return "Task: " + name + " [Priority: " + priority + "]";
}
}

// --- THREADING ---


// A background worker that simulates a "Save Timer"
class SaveLogger extends Thread {
public void run() {
try {
[Link]("[Thread] Auto-save backup initialized...");
[Link](2000); // Wait 2 seconds
[Link]("[Thread] Backup complete.");
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}

public class JavaExperiment {


public static void main(String[] args) {
// --- ARRAYS ---
// Storing multiple tasks in an array
Task[] taskList = new Task[2];

// --- EXCEPTION HANDLING ---


try {
taskList[0] = new Task("Finish Project", 1);
taskList[1] = new Task("Coffee Break", 5);

[Link]("Current Tasks:");
for (Task t : taskList) {
[Link](t);
}

// SERIALIZATION: Saving the first task to a file


ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](taskList[0]);
[Link]();
[Link]("\nSuccessfully serialized 'Finish Project' to [Link]");

// START THREAD
SaveLogger logger = new SaveLogger();
[Link]();

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array capacity exceeded!");
} catch (IOException e) {
[Link]("Error: Could not save file.");
} finally {
[Link]("System Cleanup: Closing resources.");
}
}
}

Output :-

Q.3 Java program to find area and perimeter of a circle using class.

Ans :-
import [Link];
class Circle {
double radius;

// Constructor to initialize the radius


Circle(double radius) {
[Link] = radius;
}

// Method to calculate Area: π * r^2


double calculateArea() {
return [Link] * [Link](radius, 2);
}

// Method to calculate Perimeter (Circumference): 2 * π * r


double calculatePerimeter() {
return 2 * [Link] * radius;
}
}

public class CircleTest {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter the radius of the circle: ");


double r = [Link]();

// Create an object of the Circle class


Circle myCircle = new Circle(r);

// Display results formatted to 2 decimal places


[Link]("Area of the Circle: %.2f\n", [Link]());
[Link]("Perimeter of the Circle: %.2f\n", [Link]());

[Link]();
}
}

Output:-
Q.4 Java program to print a rectangle using stars.

Ans :-

import [Link];

public class JavaExperiment {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter width (columns): ");


int width = [Link]();

[Link]("Enter height (rows): ");


int height = [Link]();

[Link]("\nGenerated Rectangle:");

// Outer loop for rows


for (int i = 0; i < height; i++) {
// Inner loop for columns
for (int j = 0; j < width; j++) {
[Link]("* ");
}
// Move to the next line after finishing a row
[Link]();
}

[Link]();
}
}

Output:-

Q.5 Write a Java program using the Java Foundation Classes (JFC) to demonstrate basic event
handling in a graphical user interface. The program should create a window titled “VTOP
Bhopal” and display a button labeled “Student Login” at its center. When the user clicks this
button, the application must respond by showing a message dialog stating “Student Login
Clicked!”.

Ans :-

import [Link].*;
import [Link].*;
import [Link].*;

public class JavaExperiment {


public static void main(String[] args) {
// Create the main window (Frame)
JFrame frame = new JFrame("VTOP Bhopal");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new GridBagLayout()); // Used to center the button easily

// Create the button


JButton loginButton = new JButton("Student Login");

// --- EVENT HANDLING ---


// Add an ActionListener to the button
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Show a message dialog when clicked
[Link](frame, "Student Login Clicked!");
}
});

// Add button to the frame


[Link](loginButton);

// Make the window visible


[Link](null); // Center window on screen
[Link](true);
}
}

Output:-

You might also like