1.
Write a Java program that declares a class with a class variable, instance
variable, and a local variable inside a method. Print their values.
class VariableDemo {
static int classVar = 100;
int instanceVar = 50;
void display() {
int localVar = 10;
[Link]("Class Variable: " + classVar);
[Link]("Instance Variable: " + instanceVar);
[Link]("Local Variable: " + localVar);
}
public static void main(String[] args) {
VariableDemo obj = new VariableDemo();
[Link]();
}
}
Output:
Class Variable: 100
Instance Variable: 50
Local Variable: 10
2. Create a class with a default constructor and a parameterized constructor.
Print values using both constructors.
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
Student(String n, int a) {
name = n;
age = a;
}
void show() {
[Link](name + " " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Rahul", 22);
[Link]();
[Link]();
}
}
Output:
Unknown 0
Rahul 22
3. Write a program that demonstrates public and private methods inside a
class.
class AccessDemo {
public void showPublic() {
[Link]("Public Method Called");
privateMethod();
}
private void privateMethod() {
[Link]("Private Method Called");
}
public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
[Link]();
}
}
Output:
Public Method Called
Private Method Called
4. Create a superclass and a subclass. Use the super keyword to call
superclass constructor and method.
class Animal {
Animal() {
[Link]("Animal Created");
}
void sound() {
[Link]("Generic Animal Sound");
}
}
class Dog extends Animal {
Dog() {
super();
[Link]("Dog Created");
}
void sound() {
[Link]();
[Link]("Dog Barks");
}
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output:
Animal Created
Dog Created
Generic Animal Sound
Dog Barks
5. Write a program with a final method and try overriding it. Observe
behavior.
class Parent {
final void display() {
[Link]("Final Method");
}
}
class Child extends Parent {
// Method overriding not allowed for final method
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}
Output:
Final Method
6. Create an abstract class with an abstract method and implement it in a
subclass.
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
}
}
public class TestAbstract {
public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}
Output:
Drawing Circle
7. Write a program to demonstrate aggregation. One class should refer to
another.
class Address {
String city, state;
Address(String c, String s) {
city = c;
state = s;
}
}
class Employee {
String name;
Address address;
Employee(String n, Address a) {
name = n;
address = a;
}
void show() {
[Link](name + " stays in " + [Link] + ", " +
[Link]);
}
public static void main(String[] args) {
Address ad = new Address("Mumbai", "Maharashtra");
Employee emp = new Employee("Amit", ad);
[Link]();
}
}
Output:
Amit stays in Mumbai, Maharashtra
8. Create two threads using the Thread class. Set different priorities and
print their execution.
class Worker extends Thread {
Worker(String name) {
super(name);
}
public void run() {
for(int i = 1; i <= 3; i++) {
[Link](getName() + " running");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Worker t1 = new Worker("Thread A");
Worker t2 = new Worker("Thread B");
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]();
[Link]();
}
}
Output:
Thread A running
Thread A running
Thread A running
Thread B running
Thread B running
Thread B running
9. Create an interface and implement it in two classes. Use interface
reference to call methods.
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
[Link]("Car Starts");
}
}
class Bike implements Vehicle {
public void start() {
[Link]("Bike Starts");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Vehicle v;
v = new Car();
[Link]();
v = new Bike();
[Link]();
}
}
Output:
Car Starts
Bike Starts
10. Demonstrate synchronization by creating two threads accessing the
same method.
class Bank {
synchronized void withdraw(int amount) {
[Link]("Withdrawing " + amount);
try {
[Link](500);
} catch(Exception e) {}
[Link]("Withdraw Completed");
}
}
class User extends Thread {
Bank bank;
int amount;
User(Bank b, int a) {
bank = b;
amount = a;
}
public void run() {
[Link](amount);
}
}
public class SyncDemo {
public static void main(String[] args) {
Bank b = new Bank();
User u1 = new User(b, 1000);
User u2 = new User(b, 2000);
[Link]();
[Link]();
}
}
Output:
Withdrawing 1000 Withdraw Completed
Withdrawing 2000 Withdraw Completed
11. Write a program that reads an integer from the user. Trigger and handle
an ArithmeticException if the number is zero and you attempt division. Print
an error message and continue program execution
import [Link];
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
try {
int result = 50 / num;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error. Division by zero is not allowed.");
}
}
}
Output:
Error. Division by zero is not allowed
12. Create a program that catches both NumberFormatException and
ArrayIndexOutOfBoundsException when reading command line
arguments. Print separate messages for each exception.
public class Test {
public static void main(String[] args) {
try {
int num = [Link](args[0]);
[Link]("Value is " + num);
} catch (NumberFormatException e) {
[Link]("Invalid number format.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("No argument entered.");
}
}
}
Output:
Input: hello
Invalid number format
13. Define a custom exception InvalidAgeException. Throw it if the age
entered is below 18. Handle it in the main method.
class InvalidAgeException extends Exception {
public InvalidAgeException(String msg) {
super(msg);
}
}
public class Main {
public static void main(String[] args) {
int age = 15;
try {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
}
[Link]("Valid age.");
} catch (InvalidAgeException e) {
[Link]([Link]());
}
}
}
Output:
Age must be 18 or above.
14. Write a program that reads a file named [Link] using
FileInputStream. Print the contents to the console. Handle IOException.
import [Link].*;
public class FileRead {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("[Link]")) {
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
} catch (IOException e) {
[Link]("File read error.");
}
}
}
Output:
Hello World
15. Write a program that writes user input to a file using FileWriter and
handles exceptions.
import [Link].*;
import [Link];
public class WriteFile {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
try (FileWriter fw = new FileWriter("[Link]")) {
[Link]("Enter text: ");
String data = [Link]();
[Link](data);
[Link]("Written successfully.");
} catch (IOException e) {
[Link]("Writing error.");
}
}
Output:
Enter text: JAVA
Written successfully.
16. Serialize an object of a Student class and store it in a file [Link].
import [Link].*;
class Student implements Serializable {
String name;
int id;
}
public class SaveObject {
public static void main(String[] args) {
Student s = new Student();
[Link] = "Ravi";
[Link] = 101;
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("[Link]"))) {
[Link](s);
[Link]("Object saved.");
} catch (IOException e) {
[Link]("Serialization error.");
}
}
}
Output:
Object saved.
17. Create a TCP client that connects to localhost on port 5000 and sends a
string message.
import [Link].*;
import [Link].*;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000)) {
OutputStream os = [Link]();
[Link]("Hello Server".getBytes());
[Link]("Message sent.");
} catch (Exception e) {
[Link]("Connection failed.");
}
}
}
Output:
Message sent.
18. Write a URL reader program using URL and BufferedReader to display
content from a public website.
import [Link].*;
import [Link].*;
public class URLTest {
public static void main(String[] args) {
try {
URL url = new URL("[Link]
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (Exception e) {
[Link]("Failed to load URL.");
}
}
}
Output:
Failed to load URL.
19. Implement a simple TCP server that listens on port 6000 and receives
a message from a client.
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(6000)) {
Socket socket = [Link]();
InputStream is = [Link]();
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
} catch (Exception e) {
[Link]("Server error.");
}
}
}
Output:
Hello Server
20. Create a Datagram sender that sends a message "Hi" to localhost port
7000
import [Link].*;
public class UDPSender {
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
byte[] data = "Hi".getBytes();
InetAddress address = [Link]("localhost");
DatagramPacket packet = new DatagramPacket(data, [Link],
address, 7000);
[Link](packet);
[Link]("Datagram sent.");
[Link]();
} catch (Exception e) {
[Link]("Error sending datagram.");
}
}
}
Output:
Datagram sent.
21. Write an AWT program with a button and text field. When you click the
button, the text "Button Clicked" appears in the text field.
import [Link].*;
import [Link].*;
public class ButtonEventDemo extends Frame implements ActionListener {
TextField tf;
Button b;
public ButtonEventDemo() {
tf = new TextField(20);
b = new Button("Click");
add(tf);
add(b);
setLayout(new FlowLayout());
[Link](this);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked");
}
public static void main(String[] args) {
new ButtonEventDemo();
}
}
22. Create a Swing application with a label and two buttons. Clicking each
button changes the label text.
import [Link].*;
import [Link].*;
public class SwingButtonDemo extends JFrame implements ActionListener {
JLabel label;
JButton b1, b2;
public SwingButtonDemo() {
label = new JLabel("Press a button");
b1 = new JButton("Hello");
b2 = new JButton("Goodbye");
add(label);
add(b1);
add(b2);
setLayout(new [Link]());
[Link](this);
[Link](this);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if([Link]() == b1) {
[Link]("Hello");
} else {
[Link]("Goodbye");
}
}
public static void main(String[] args) {
new SwingButtonDemo();
}
}
23. Create a program that demonstrates the use of BorderLayout with
five buttons.
import [Link].*;
public class BorderLayoutDemo extends Frame {
public BorderLayoutDemo() {
setLayout(new BorderLayout());
add("North", new Button("North"));
add("South", new Button("South"));
add("East", new Button("East"));
add("West", new Button("West"));
add("Center", new Button("Center"));
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args) {
new BorderLayoutDemo();
}
}
24. Create a GUI with a checkbox and label. Update text when the checkbox
is selected or deselected.
import [Link].*;
import [Link].*;
public class CheckBoxDemo extends Frame implements ItemListener {
Checkbox cb;
Label lbl;
public CheckBoxDemo() {
cb = new Checkbox("Accept Terms");
lbl = new Label("Status: Not selected");
add(cb);
add(lbl);
setLayout(new FlowLayout());
[Link](this);
setSize(300, 200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
[Link]("Status: " + ([Link]() ? "Selected" : "Not selected"));
}
public static void main(String[] args) {
new CheckBoxDemo();
}
}
25. Write a Swing application using JTextField and KeyListener that shows
typed characters count.
import [Link].*;
import [Link].*;
public class TypingCount extends JFrame implements KeyListener {
JTextField tf;
JLabel lbl;
int count = 0;
public TypingCount() {
tf = new JTextField(20);
lbl = new JLabel("Characters typed: 0");
add(tf);
add(lbl);
setLayout(new [Link]());
[Link](this);
setSize(300, 200);
setVisible(true);
}
public void keyTyped(KeyEvent e) {
count++;
[Link]("Characters typed: " + count);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String[] args) {
new TypingCount();
}
}