0% found this document useful (0 votes)
17 views22 pages

Java University Paper 2

Hh

Uploaded by

gyanchod23
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)
17 views22 pages

Java University Paper 2

Hh

Uploaded by

gyanchod23
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/ 22

Java University Paper 2

*******Paper-2*******

Q1) Attempt any Eight : [8 × 2 = 16]

a) What is Java? Why is Java a platform-neutral language?


Ans:-
Java is a high-level, object-oriented programming language developed by Sun Microsystems
(now owned by Oracle). It is designed to be simple, secure, and portable. Java is considered a
platform-neutral language because it uses the Java Virtual Machine (JVM) to run programs.
When Java code is compiled, it is converted into bytecode, which can be executed on any
device that has a JVM, regardless of the underlying operating system.

b) What are access specifiers? List them.


Ans:-
Access specifiers (or access modifiers) in Java determine the visibility and accessibility of
classes, methods, and variables. The main access specifiers are:
1. public: Accessible from any other class.
2. protected: Accessible within its own package and by subclasses.
3. default (no modifier): Accessible only within its own package.
4. private: Accessible only within its own class.

c) Define Keyword-Static.
Ans:-
The static keyword in Java indicates that a variable or method belongs to the class rather than
instances of the class. This means that static members can be accessed without creating an
instance of the class. Static variables are shared among all instances, while static methods can
only directly access other static members.

d) Why do we set environment variables in Java?


Ans:-
Environment variables in Java are set to configure the runtime environment for Java
applications. They help specify the location of Java installations, libraries, and other resources
needed by the JVM. For example, setting the JAVA_HOME variable points to the directory
where the JDK is installed, allowing tools and applications to locate Java executables.

e) Write advantages of Inheritance.


Ans:-
Inheritance in Java offers several advantages:
1. Code Reusability: Allows classes to reuse code from existing classes.
2. Method Overriding: Enables subclasses to provide specific implementations of methods
defined in parent classes.
3. Polymorphism: Facilitates dynamic method resolution, allowing for flexible code.
4. Hierarchical Classification: Helps organize classes in a logical hierarchy.

f) Define class and object with one example.


Ans:-
A class in Java is a blueprint or template for creating objects, defining properties (attributes) and
behaviors (methods). An object is an instance of a class.
Example:
class Car {
String color;
void displayColor() {
System.out.println("Car color: " + color);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // Creating an object of class Car
myCar.color = "Red";
myCar.displayColor(); // Output: Car color: Red
}
}

g) What is Swing?
Ans:-
Swing is a part of Java's standard library that provides a set of lightweight GUI components for
building graphical user interfaces (GUIs). Unlike AWT components, Swing components are
platform-independent and offer more flexibility and features, such as pluggable look-and-feel,
advanced controls (tables, trees), and support for drag-and-drop operations.

h) When is BufferedReader used?


Ans:-
BufferedReader is used in Java for reading text from an input stream (like files or network
connections) efficiently. It reads characters into a buffer for faster input operations, which
reduces the number of I/O operations by reading larger chunks of data at once rather than
character by character.

i) What is the main difference between exception and error?


Ans:-
The main difference between an exception and an error in Java is:
• Exception: Represents conditions that a program can catch and handle (e.g., IOException,
NullPointerException). They are typically caused by external factors or user input errors.
• Error: Represents serious issues that a program cannot reasonably recover from (e.g.,
OutOfMemoryError, StackOverflowError). Errors indicate problems with the runtime environment
or system resources.

j) What is Panel?
Ans:-
A Panel in Java is a container class used to group related components together within a GUI
application. It can hold multiple UI elements like buttons, text fields, and labels, allowing for
better organization and layout management within a window or frame.

Q2) Attempt any four : [4 × 4 = 16]


a) What is Super Keyword? Explain the use of super keyword with a suitable example.
Ans:-
The super keyword in Java refers to the superclass (parent class) of the current object. It is
used to access superclass methods and constructors.
Example:
class Animal {
void display() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
void display() {
super.display(); // Calls the display method of Animal
System.out.println("I am a dog.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.display();
}
}

Output:
I am an animal.
I am a dog.

b) Describe file handling in brief.


Ans:-
File handling in Java involves reading from and writing to files using various classes provided by
the java.io package.
Key classes include:
• File: Represents file and directory pathnames.
• FileReader/FileWriter: For reading/writing character files.
• BufferedReader/BufferedWriter: For efficient reading/writing of text files using buffers.
• FileInputStream/FileOutputStream: For reading/writing binary files.
Java provides exception handling mechanisms to manage I/O errors effectively.

c) What is datatype? Explain types of datatypes used in Java.


Ans:-
A datatype defines the type of data that can be stored in a variable and determines the
operations that can be performed on that data. In Java, datatypes are categorized into two main
types:

1. Primitive Data Types:


• byte: 8-bit integer
• short: 16-bit integer
• int: 32-bit integer
• long: 64-bit integer
• float: Single-precision 32-bit floating point
• double: Double-precision 64-bit floating point
• char: Single 16-bit Unicode character
• boolean: Represents true or false values

2. Reference Data Types / Non-Primitive Data Types: These include any object or array type
that refers to an instance in memory.

d) What is interface? Why are they used in Java?


Ans:-
An interface in Java is a reference type similar to a class that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces cannot
contain instance fields or constructors. They are used to achieve abstraction and multiple
inheritance in Java, allowing classes to implement multiple interfaces and ensuring that certain
methods are implemented in those classes.

e) Why is the main() method public static? Can we overload it? Can we run a Java class without
the main() method?
Ans:-
The main() method must be declared as public so that it can be accessed by the JVM from
outside the class. It must also be static so that it can be invoked without creating an instance of
the class. Yes, we can overload the main() method by providing different parameter lists;
however, only the standard signature (public static void main(String[] args)) will be called by the
JVM at runtime. A Java class cannot run without a main() method unless it is invoked from
another class that contains a main() method.

Q3) Attempt any four : [4 × 4 = 16]

a) Write a java program which accepts student details (Sid, Sname, Saddr) from user and
display it on next frame. (Use AWT).
Ans:-
import java.awt.*;
import java.awt.event.*;

public class StudentDetails extends Frame implements ActionListener {


TextField sidField, snameField, saddrField;
Button submitButton;

public StudentDetails() {
// Create UI components
Label sidLabel = new Label("Student ID:");
Label snameLabel = new Label("Student Name:");
Label saddrLabel = new Label("Student Address:");

sidField = new TextField(20);


snameField = new TextField(20);
saddrField = new TextField(20);

submitButton = new Button("Submit");


submitButton.addActionListener(this);

// Layout setup
setLayout(new FlowLayout());
add(sidLabel);
add(sidField);
add(snameLabel);
add(snameField);
add(saddrLabel);
add(saddrField);
add(submitButton);

setSize(300, 200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


// Display entered details on new frame
Frame detailsFrame = new Frame("Student Details");
detailsFrame.setLayout(new FlowLayout());

Label detailsLabel = new Label("Details: " +


"ID: " + sidField.getText() + ", " +
"Name: " + snameField.getText() + ", " +
"Address: " + saddrField.getText());

detailsFrame.add(detailsLabel);

detailsFrame.setSize(300, 100);
detailsFrame.setVisible(true);
}

public static void main(String[] args) {


new StudentDetails();
}
}

b) Write a package MCA which has one class student. Accept student details through
parameterized constructor. Write display() method to display details. Create a main class which
will use package and calculate total marks and percentage.
Ans:-
// File: MCA/Student.java
package MCA;
public class Student {
private int sid;
private String name;
private String address;
private int marks1, marks2, marks3;

public Student(int sid, String name, String address, int marks1, int marks2, int marks3) {
this.sid = sid;
this.name = name;
this.address = address;
this.marks1 = marks1;
this.marks2 = marks2;
this.marks3 = marks3;
}

public void display() {


System.out.println("Student ID: " + sid);
System.out.println("Name: " + name);
System.out.println("Address: " + address);
System.out.println("Total Marks: " + totalMarks());
System.out.println("Percentage: " + percentage() + "%");
}

private int totalMarks() {


return marks1 + marks2 + marks3;
}

private double percentage() {


return totalMarks() / 3.0;
}
}

// File: Main.java
import MCA.Student;

public class Main {


public static void main(String[] args) {
Student student = new Student(101, "John Doe", "123 Main St", 85, 90, 78);
student.display();
}
}

c) Write a Java program which accepts a string from user; if its length is less than five, then
throw user-defined exception “Invalid String”; otherwise display string in uppercase.
Ans:-
import java.util.Scanner;

class InvalidStringException extends Exception {


public InvalidStringException(String message) {
super(message);
}
}

public class StringValidation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

try {
validateString(input);
System.out.println("Uppercase String: " + input.toUpperCase());
} catch (InvalidStringException e) {
System.out.println(e.getMessage());
}
}

static void validateString(String str) throws InvalidStringException {


if (str.length() < 5) {
throw new InvalidStringException("Invalid String: Length must be at least 5 characters.");
}
}
}

d) Write a Java Program using Applet to create a login form.


Ans:-
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class LoginForm extends Applet implements ActionListener {


TextField usernameField;
TextField passwordField;
Button loginButton;

public void init() {


Label usernameLabel = new Label("Username:");
usernameField = new TextField(20);

Label passwordLabel = new Label("Password:");


passwordField = new TextField(20);
passwordField.setEchoChar('*');

loginButton = new Button("Login");


loginButton.addActionListener(this);
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(loginButton);
}

public void actionPerformed(ActionEvent e) {


String username = usernameField.getText();
String password = passwordField.getText();

// Simple validation logic for demonstration purposes


if ("admin".equals(username) && "password".equals(password)) {
showStatus("Login Successful");
} else {
showStatus("Login Failed");
}
}
}

e) What is recursion in Java? Write a Java Program to find factorial of a given number using
recursion.
Ans:-
Recursion in Java refers to a technique where a method calls itself to solve smaller instances of
the same problem until reaching a base condition.

import java.util.Scanner;

public class FactorialRecursion {

public static int factorial(int n) {


if (n == 0 || n == 1)
return 1; // Base case
else
return n * factorial(n - 1); // Recursive case
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int number = scanner.nextInt();

int result = factorial(number);

System.out.println("Factorial of " + number + " is: " + result);


}
}
Q4) Attempt any four : [4 × 4 = 16]

a) Explain method overloading and method overriding in detail.


Ans:-
• Method Overloading: This occurs when multiple methods have the same name but different
parameter lists (different types or numbers of parameters). It allows methods to perform similar
functions with different inputs.

Example:
class MathOperations {
int add(int a, int b) { return a + b; } // Method with two int parameters
double add(double a, double b) { return a + b; } // Method with two double parameters
}

• Method Overriding: This occurs when a subclass provides a specific implementation of a


method already defined in its superclass. The overridden method must have the same name
and parameter list as the method in the superclass.

Example:
class Animal {
void sound() { System.out.println("Animal makes sound"); }
}

class Dog extends Animal {


void sound() { System.out.println("Dog barks"); } // Overriding sound method
}

b) Write an applet application in Java for designing a smiley.


Ans:-
import java.applet.Applet;
import java.awt.*;

public class SmileyApplet extends Applet {

public void paint(Graphics g) {


// Draw face
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 200, 200); // Face

// Draw eyes
g.setColor(Color.BLACK);
g.fillOval(100, 100, 30, 30); // Left eye
g.fillOval(170, 100, 30, 30); // Right eye

// Draw mouth
g.drawArc(100, 120, 100, 60, 0, -180); // Mouth
}
}

c) Explain in brief delegation event model for handling events.


Ans:-
The delegation event model in Java separates event handling from event generation by using
event listeners and event sources:
• Event Source: An object that generates events (e.g., buttons).
• Event Listener: An interface that defines methods for responding to events (e.g.,
ActionListener).
• Event Object: Contains information about the event (e.g., which button was clicked).
When an event occurs on an event source, it notifies registered listeners via callback methods
defined in listener interfaces.

d) Write a Java program to copy the data from one file into another file.
Ans:-
import java.io.*;

public class FileCopy {

public static void main(String[] args) {

try (BufferedReader reader = new BufferedReader(new FileReader("source.txt"));


BufferedWriter writer = new BufferedWriter(new FileWriter("destination.txt"))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine(); // Add newline after each line copied
}
System.out.println("File copied successfully.");

} catch (IOException e) {
e.printStackTrace();
}
}
}

e) Write a Java program to accept ‘n’ integers from the user store them in an ArrayList
Collection. Display the elements of ArrayList collection in reverse order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class ReverseArrayList {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of integers: ");


int n = scanner.nextInt();

ArrayList<Integer> numbers = new ArrayList<>();

System.out.println("Enter " + n + " integers:");

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


numbers.add(scanner.nextInt());
}

Collections.reverse(numbers); // Reverse ArrayList

System.out.println("Elements in reverse order: " + numbers);


}
}

Q5) Write short note any two : [2 × 3 = 6]

a) What does repaint method do?


Ans:-
The repaint() method in Java is used to request that a component be redrawn on the screen. It
schedules a call to the component's paint() method at some point in the future based on system
resources and timing. This method is commonly used when changes occur that require updating
the visual representation of components.

b) Write constructors of JTabbedPane.


Ans:-
JTabbedPane provides several constructors for creating tabbed panes:
1. JTabbedPane(): Creates an empty tabbed pane.
2. JTabbedPane(int tabPlacement): Creates an empty tabbed pane with specified tab placement
(top/bottom/left/right).
3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): Creates an empty tabbed pane with
specified tab placement and layout policy (scrollable or fixed).

Example:
JTabbedPane tabbedPane1 = new JTabbedPane(); // Default constructor
JTabbedPane tabbedPane2 = new JTabbedPane(JTabbedPane.TOP); // Tabs at top

c) Abstract Class:
Ans:-
An abstract class in Java is a class that cannot be instantiated on its own and may contain
abstract methods (methods without implementation). Abstract classes are used as base classes
for other classes to extend them and provide specific implementations for abstract methods.

Example:
abstract class Animal {
abstract void sound(); // Abstract method

void sleep() { // Concrete method


System.out.println("Sleeping...");
}
}

class Dog extends Animal {


void sound() { // Implementation of abstract method
System.out.println("Bark");
}
}

Java University Paper 1

*******Paper-1*******
Q1) Attempt any Eight : [8 × 2 = 16]

a) What is JDK? How to build and run a Java program?


Ans:-
JDK stands for Java Development Kit. It is a software development environment used for
developing Java applications and applets.
To build and run a Java program:
1. Write your Java code in a text file with a .java extension.
2. Open the command prompt or terminal.
3. Navigate to the directory where your .java file is located.
4. Compile the Java file using the command:
javac YourProgram.java.
5. Run the compiled program using the command: java YourProgram.

b) Explain Static keyword.


Ans:-
The static keyword in Java is used for memory management primarily. It can be applied to
variables, methods, blocks, and nested classes. When a member (variable or method) is
declared static, it belongs to the class rather than instances of the class. This means that static
members can be accessed without creating an instance of the class.

c) What is the use of classpath?


Ans:-
Classpath is a parameter that tells the Java Virtual Machine (JVM) and Java compiler where to
look for user-defined classes and packages in Java programs. It can include directories, JAR
files, and ZIP files. The classpath is essential for locating classes during compilation and
runtime.

d) What is collection? Explain collection framework in detail.


Ans:-
A collection in Java is an object that can hold multiple values or objects. The Collection
Framework provides a set of classes and interfaces to work with groups of objects.
It includes:
• Interfaces: List, Set, Queue, Map
• Implementations: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap
• Algorithms: Methods for sorting, searching, and manipulating collections.
The framework allows for flexible data manipulation and storage.

e) What is the use of Reader and Writer class?


Ans:-
The Reader and Writer classes are part of Java's I/O package and are used for reading and
writing character streams, respectively. They handle character encoding and decoding, making
them suitable for text data. Reader provides methods to read characters, arrays, and lines,
while Writer provides methods to write characters, arrays, and strings.

f) What is the use of layout manager?


Ans:-
A layout manager in Java is an object that controls the arrangement of components within a
container. It defines how components are sized and positioned on the screen. Common layout
managers include FlowLayout, BorderLayout, GridLayout, and BoxLayout. They help create a
responsive user interface that adapts to different screen sizes.

g) What is the difference between paint() and repaint()?


Ans:-
The paint() method is called by the AWT (Abstract Window Toolkit) to render the components on
the screen. It is called automatically when a component needs to be redrawn. On the other
hand, repaint() is a method that requests a call to paint(), indicating that a component should be
redrawn. Calling repaint() schedules a call to paint() at a later time.

h) Explain Access modifiers used in Java.


Ans:-
Access modifiers in Java define the visibility of classes, methods, and variables.
There are four main types:
• public: Accessible from any other class.
• protected: Accessible within its own package and by subclasses.
• default (no modifier): Accessible only within its own package.
• private: Accessible only within its own class.

i) Define keyword throw.


Ans:-
The throw keyword in Java is used to explicitly throw an exception from a method or block of
code. It can be used to indicate that an error has occurred or to enforce certain conditions in
your program.

j) Define polymorphism.
Ans:-
Polymorphism in Java refers to the ability of a single interface to represent different underlying
forms (data types). It allows methods to do different things based on the object it is acting upon,
typically achieved through method overriding (runtime polymorphism) and method overloading
(compile-time polymorphism).

Q2) Attempt any four : [4 × 4 = 16]

a) Explain features of Java.


Ans:-
Java has several key features:
1. Platform Independence: Java code can run on any device with a JVM.
2. Object-Oriented: Supports concepts like inheritance, encapsulation, polymorphism.
3. Robustness: Strong memory management and exception handling.
4. Security: Provides security features like bytecode verification.
5. Multithreading: Supports concurrent execution of two or more threads.

b) What is the difference between constructor and method? Explain types of constructors.
Ans:-
A constructor is a special method invoked when an object is created, whereas a method is a
block of code that performs a specific task when called.
Types of constructors:
• Default Constructor: No arguments; initializes default values.
• Parameterized Constructor: Takes parameters to initialize object attributes.

c) Differentiate between interface and abstract class.

🛑
Ans:-
Refer another answer for this🛑
d) Explain the concept of exception and exception handling.
Ans:-
An exception is an event that disrupts the normal flow of execution in a program. Exception
handling in Java is done using try-catch blocks:
• try block: Contains code that may throw an exception.
• catch block: Catches and handles exceptions thrown by the try block.
This mechanism allows developers to manage errors gracefully without crashing the program.

e) Explain try and Catch with example.


Ans:-
The try block contains code that might throw an exception, while the catch block handles it:

try {
int result = 10 / 0; // This will throw ArithmeticException
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}

Q3) Attempt any four : [4 × 4 = 16]

a) Write a Java program to display all the perfect numbers between 1 to n.


Ans:-
import java.util.Scanner;

public class PerfectNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter value of n: ");
int n = scanner.nextInt();

System.out.println("Perfect numbers between 1 and " + n + ":");


for (int i = 1; i <= n; i++) {
if (isPerfect(i)) {
System.out.println(i);
}
}
}

static boolean isPerfect(int num) {


int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
}

b) Write a Java program to calculate area of circle, Triangle and Rectangle (Use Method
overloading).
Ans:-
class AreaCalculator {
double area(double radius) { // Area of Circle
return Math.PI * radius * radius;
}

double area(double base, double height) { // Area of Triangle


return 0.5 * base * height;
}

double area(double length, double width) { // Area of Rectangle


return length * width;
}

public static void main(String[] args) {


AreaCalculator calc = new AreaCalculator();
System.out.println("Area of Circle: " + calc.area(5));
System.out.println("Area of Triangle: " + calc.area(5, 10));
System.out.println("Area of Rectangle: " + calc.area(5, 10));
}
}

c) Write a java program to accept n integers from the user and store them in an ArrayList
collection. Display elements in reverse order.
Ans:-
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class ReverseArrayList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();

System.out.print("Enter number of integers: ");


int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
numbers.add(scanner.nextInt());
}

Collections.reverse(numbers);

System.out.println("Numbers in reverse order: " + numbers);


}
}

d) Write a Java program to count number of digits, spaces and characters from a file.
Ans:-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileCharacterCount {


public static void main(String[] args) {
int digits = 0, spaces = 0, characters = 0;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {


int ch;
while ((ch = br.read()) != -1) {
if (Character.isDigit(ch)) digits++;
else if (Character.isWhitespace(ch)) spaces++;
else characters++;
}
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Digits: " + digits);


System.out.println("Spaces: " + spaces);
System.out.println("Characters: " + characters);
}
}

e) Create an applet that displays x and y position of the cursor movement using mouse and
keyboard. (Use appropriate listener)
Ans:-
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class MousePositionApplet extends Applet implements MouseMotionListener {


String msg = "";

public void init() {


addMouseMotionListener(this);
}

public void mouseMoved(MouseEvent me) {


msg = "Mouse moved at: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseDragged(MouseEvent me) {}

public void paint(Graphics g) {


g.drawString(msg, 20, 20);
}
}

Q4) Attempt any four : [4 × 4 = 16]

a) How is a Java program structured? Explain data types.


Ans:-
A Java program typically consists of classes containing methods.
The structure includes:
1. Package Declaration
2. Import Statements
3. Class Definition
4. Main Method

Java has two categories of data types:


• Primitive Data Types: byte, short, int, long, float, double, char, boolean.
• Reference Data Types: Objects created from classes.

b) What is an applet? Explain its types.


Ans:-
An applet is a small application designed to be transmitted over the internet and run in a web
browser or applet viewer. There are two types:
1. Standard Applet: Uses AWT for GUI components.
2. Swing Applet: Uses Swing for enhanced GUI capabilities.

c) Write a java program to count number of Lines, words and characters from a given file.
Ans:-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileWordCount {


public static void main(String[] args) {
int lines = 0, words = 0, characters = 0;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {


String line;
while ((line = br.readLine()) != null) {
lines++;
characters += line.length();
words += line.split("\s+").length;
}
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Lines: " + lines);


System.out.println("Words: " + words);
System.out.println("Characters: " + characters);
}
}

d) Write a Java program to design an email registration form (Use Swing components).
Ans:-
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EmailRegistrationForm {


public static void main(String[] args) {
JFrame frame = new JFrame("Email Registration Form");
JLabel label = new JLabel("Enter your email:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Register");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String email = textField.getText();
JOptionPane.showMessageDialog(frame, "Registered Email: " + email);
}
});

JPanel panel = new JPanel();


panel.add(label);
panel.add(textField);
panel.add(button);

frame.add(panel);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

e) Create a class Teacher (Tid, Tname, Designation, Salary, Subject). Write a java program to
accept 'n' teachers and display who teach Java subject (Use Array of object).

import java.util.Scanner;

class Teacher {
int tid;
String tname;
String designation;
double salary;
String subject;

Teacher(int tid, String tname, String designation, double salary, String subject) {
this.tid = tid;
this.tname = tname;
this.designation = designation;
this.salary = salary;
this.subject = subject;
}
}

public class TeacherDetails {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of teachers: ");


int n = scanner.nextInt();
Teacher[] teachers = new Teacher[n];

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


System.out.print("Enter ID: ");
int id = scanner.nextInt();
scanner.nextLine(); // Consume newline

System.out.print("Enter Name: ");


String name = scanner.nextLine();

System.out.print("Enter Designation: ");


String designation = scanner.nextLine();

System.out.print("Enter Salary: ");


double salary = scanner.nextDouble();

scanner.nextLine(); // Consume newline

System.out.print("Enter Subject: ");


String subject = scanner.nextLine();

teachers[i] = new Teacher(id, name, designation, salary, subject);


}

System.out.println("Teachers who teach Java:");


for (Teacher teacher : teachers) {
if ("Java".equalsIgnoreCase(teacher.subject)) {
System.out.println(teacher.tname);
}
}
}
}

Q5) Write short notes on any two : [2 × 3 = 6]

a) Define object.
Ans:-
An object in Java is an instance of a class that contains state (attributes/fields) and behavior
(methods/functions). Objects are fundamental building blocks in object-oriented programming.

Syntax to create an object:


ClassName objectName = new ClassName();

Example:
class Car {
// Properties (instance variables)
String model;
int year;
// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}

// Method
void displayInfo() {
System.out.println("Car Model: " + model);
System.out.println("Car Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota", 2020);

// Calling the method using the object


myCar.displayInfo();
}
}

b) Define term finally block.


Ans:-
The finally block in Java is used to execute code after try-catch blocks regardless of whether an
exception was thrown or caught. It is typically used for cleanup activities such as closing files or
releasing resources.

try {
// Code that may throw an exception
} catch (Exception e) {
// Handle exception
} finally {
// Cleanup code that always executes
}

c) What is package? Write down all the steps for package creation.
Ans:-
A package in Java is a namespace that organizes related classes and interfaces together. It
helps avoid naming conflicts and controls access.

Steps for creating a package:


1. Declare the package at the top of your Java file using package packageName;.
2. Compile your Java file with the command: javac -d . YourClass.java.
3. Use classes from your package by importing them in other classes using import
packageName.ClassName;.

You might also like