Java Important Questions with Solutions (For
Complete Beginners)
Question 1: Using proper examples, give the difference between interfaces
and abstract classes in Java.
📚 BEGINNER NOTE: What You Need to Know First
What is a Class?
A class is like a blueprint or template to create objects.
Example: A "Car" class is a blueprint; an actual car you create from it is an object.
What is a Method?
A method is an action that an object can do.
Example: A dog can bark() or eat() - these are methods.
What is Abstract?
Abstract means "incomplete" or "not fully defined".
You declare what something should do, but don't write how to do it yet.
What is an Interface?
An interface is like a contract or promise.
It lists what methods a class MUST have, but doesn't provide the code.
The % Symbol (Modulo):
num % 2 gives the remainder when dividing by 2.
If remainder is 0, the number is even.
Example: 10 % 2 = 0 (even), 7 % 2 = 1 (odd)
✍️ ANSWER:
Abstract Class
An abstract class is like a half-built house - some rooms are complete, some are just plans.
It can have complete methods (with code inside) and incomplete methods (just names).
It can have variables to store data.
It can have a constructor (special method that runs when creating objects).
A class can extend only ONE abstract class.
Use the word extends to inherit from it.
Super Simple Example:
java
// Abstract class - cannot create objects directly from this
abstract class Animal {
String name;
// Complete method - has code
void eat() {
[Link](name + " is eating");
}
// Incomplete method - just name, no code
abstract void sound();
}
// Dog completes the Animal class
class Dog extends Animal {
// Now we write code for sound method
void sound() {
[Link]("Woof Woof!");
}
}
// Main class to run
class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link] = "Tommy";
[Link](); // Output: Tommy is eating
[Link](); // Output: Woof Woof !
}
}
Interface
An interface is like a to-do list - it tells you what you must do, but not how to do it.
ALL methods are incomplete by default (just names, no code).
Cannot have variables, only constants (values that never change).
Cannot have constructors.
A class can implement MANY interfaces at once.
Use the word implements to adopt an interface.
Super Simple Example:
java
// Interface 1
interface CanFly {
void fly(); // Just name, no code
}
// Interface 2
interface CanSwim {
void swim(); // Just name, no code
}
// Duck implements both interfaces
class Duck implements CanFly, CanSwim {
// Must write code for all methods
public void fly() {
[Link]("Duck is flying");
}
public void swim() {
[Link]("Duck is swimming");
}
}
// Main class to run
class Test {
public static void main(String[] args) {
Duck d = new Duck();
[Link](); // Output: Duck is flying
[Link](); // Output: Duck is swimming
}
}
Simple Summary:
Feature Abstract Class Interface
Complete methods ✅ Yes ❌ No
Incomplete methods ✅ Yes ✅ Yes
Variables ✅ Yes ❌ Only constants
Constructor ✅ Yes ❌ No
How many? Only 1 Many
Keyword extends implements
Question 2: Distinguish between checked and unchecked exceptions.
📚 BEGINNER NOTE: What You Need to Know First
What is an Exception?
An exception is an error that happens while your program is running.
Example: Dividing by zero, file not found, wrong input type.
What is Try-Catch?
try = "Try to do something that might fail"
catch = "If it fails, catch the error and do this
instead"
Think of it like a safety net when doing something risky.
What is Compile-Time vs Runtime?
Compile-time = Before program runs (when you press "Run")
Runtime = While program is running (after it starts)
parseInt() Method:
Converts text to a number.
Example: "123" (text) becomes 123 (number)
Throws exception if text is not a valid number.
✍️ ANSWER:
Checked Exceptions
Checked exceptions are errors that Java checks BEFORE running your program (at compile-time).
Java forces you to handle these with try-catch or throws.
If you don't handle them, your program won't compile.
These are problems outside your control (like file missing, network down).
Examples: IOException, SQLException, FileNotFoundException.
Super Simple Example:
java
import [Link].*;
class CheckedExample {
public static void main(String[] args) {
// Must use try-catch or program won't compile
try {
// Trying to open a file
FileReader file = new FileReader("[Link]");
[Link]("File opened!");
}
catch (FileNotFoundException e) {
// If file doesn't exist, this runs
[Link]("File not found!");
}
}
}
Unchecked Exceptions
Unchecked exceptions are errors that happen WHILE your program is running (at runtime).
Java doesn't force you to handle these.
Your program compiles fine but may crash when running.
These are usually programming mistakes (divide by zero, null object).
Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.
Super Simple Example:
java
class UncheckedExample {
public static void main(String[] args) {
// Example 1: Divide by zero
try {
int result = 10 / 0; // Error!
}
catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
// Example 2: Wrong array index
try {
int[] numbers = {1, 2, 3};
[Link](numbers[10]); // Only 3 items!
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("That position doesn't exist!");
}
// Example 3: Null object
try {
String name = null;
[Link]([Link]()); // name is empty!
}
catch (NullPointerException e) {
[Link]("String is null!");
}
}
}
Simple Summary:
Feature Checked Unchecked
Checked when? Before running (compile-time) While running (runtime)
Must handle? ✅ Yes, required ❌ No, optional
Caused by? External problems Programming mistakes
Examples File errors, Network errors Divide by zero, Null errors
Question 3: List any three event sources and their corresponding event
types and listeners used.
📚 BEGINNER NOTE: What You Need to Know First
What is an Event?
An event is something that happens (like clicking a button).
Events are user actions: click, type, move mouse, etc.
What is an Event Source?
The thing that creates the event.
Example: A button is the source when you click it.
What is a Listener?
Code that "listens" for events and responds.
Like a security guard watching for something to happen.
What is ActionListener?
A special listener for button clicks.
When button is clicked, actionPerformed() method runs automatically.
Why "implements ActionListener"?
This tells Java: "My class can handle button clicks"
You MUST write the actionPerformed() method.
✍️ ANSWER:
Three Common Events:
1. Button → ActionEvent → ActionListener
When you click a button, ActionEvent happens.
ActionListener catches it and responds.
2. TextField → KeyEvent → KeyListener
When you type in a text box, KeyEvent happens.
KeyListener catches it and responds.
3. Mouse → MouseEvent → MouseListener
When you click or move mouse, MouseEvent happens.
MouseListener catches it and responds.
Super Simple Example (Button Click):
java
import [Link].*;
import [Link].*;
// "implements ActionListener" means this class can handle button clicks
class SimpleEvent extends Frame implements ActionListener {
Button btn;
Label msg;
SimpleEvent() {
// Create button
btn = new Button("Click Me");
msg = new Label("Press the button");
// Tell button to notify THIS class when clicked
[Link](this);
// Add to window
setLayout(new FlowLayout());
add(btn);
add(msg);
// Show window
setSize(300, 150);
setVisible(true);
}
// This method runs automatically when button is clicked
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
public static void main(String[] args) {
new SimpleEvent();
}
}
How it works:
1. You click the button
2. Java calls actionPerformed() automatically
3. The message changes
Question 4: Compare Swing API and AWT API.
📚 BEGINNER NOTE: What You Need to Know First
What is AWT?
AWT = Abstract Window Toolkit
The OLD way to make windows and buttons in Java.
Uses your computer's built-in buttons and windows.
What is Swing?
The NEW and BETTER way to make windows and buttons.
Draws its own buttons and windows (doesn't use computer's).
Component names start with 'J' (JButton, JFrame, JLabel).
What is a Frame?
A Frame is a window (like the window of a house).
Everything goes inside the frame.
What is FlowLayout?
Arranges components left to right, like reading a book.
When one row is full, starts a new row.
setVisible(true) - Very Important!
Makes the window appear on screen.
Without this, your window is invisible!
✍️ ANSWER:
AWT (Old Way)
Uses your operating system's buttons and windows.
Looks different on Windows, Mac, and Linux.
Component names: Button, Frame, TextField, Label (no 'J').
Heavyweight - uses more computer resources.
Need complicated code to close window.
Super Simple AWT Example:
java
import [Link].*;
import [Link].*;
class AWTExample extends Frame implements ActionListener {
Button btn;
TextField box;
Label lbl;
AWTExample() {
// Create components
btn = new Button("Click");
box = new TextField(15);
lbl = new Label("Type above");
// Tell button to listen
[Link](this);
// Add to window
setLayout(new FlowLayout());
add(lbl);
add(box);
add(btn);
// Window settings
setSize(300, 150);
setTitle("AWT Program");
setVisible(true);
// Close window code (complicated!)
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// When button clicked
public void actionPerformed(ActionEvent e) {
String text = [Link]();
[Link]("You typed: " + text);
}
public static void main(String[] args) {
new AWTExample();
}
}
Swing (New Way - Better!)
Draws its own buttons and windows.
Looks the same on all computers.
Component names start with 'J': JButton, JFrame, JTextField, JLabel.
Lightweight - uses less computer resources.
Easy to close window with one line!
Super Simple Swing Example:
java
import [Link].*;
import [Link].*;
import [Link].*;
class SwingExample extends JFrame implements ActionListener {
JButton btn;
JTextField box;
JLabel lbl;
SwingExample() {
// Create components
btn = new JButton("Click");
box = new JTextField(15);
lbl = new JLabel("Type above");
// Tell button to listen
[Link](this);
// Add to window
setLayout(new FlowLayout());
add(lbl);
add(box);
add(btn);
// Window settings
setSize(300, 150);
setTitle("Swing Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Easy close!
setVisible(true);
}
// When button clicked
public void actionPerformed(ActionEvent e) {
String text = [Link]();
[Link]("You typed: " + text);
}
public static void main(String[] args) {
new SwingExample();
}
}
Simple Comparison:
Feature AWT Swing
Names Button, Frame JButton, JFrame
Looks same everywhere? ❌ No ✅ Yes
Easy to close window? ❌ No ✅ Yes
More features? ❌ Basic ✅Many
Which to use? Old (don't use) New (use this!)
Question 5: Inheritance and its types with examples.
📚 BEGINNER NOTE: What You Need to Know First
What is Inheritance?
Inheritance means getting something from parents.
In Java, a child class gets features from parent class.
Saves time - don't write same code again!
What is "extends"?
The word "extends" means "inherits from".
Example: class Dog extends Animal means Dog inherits from Animal.
Parent Class vs Child Class:
Parent (Superclass) = The class being inherited from
Child (Subclass) = The class that inherits
What is "super"?
super refers to the parent class.
super() calls the parent's constructor.
✍️ ANSWER:
Types of Inheritance:
1. Single Inheritance (One Parent, One Child)
The simplest type - one child inherits from one parent.
Super Simple Example:
java
// Parent class
class Animal {
void eat() {
[Link]("Eating food");
}
}
// Child class - gets eat() automatically!
class Dog extends Animal {
void bark() {
[Link]("Woof!");
}
}
// Run it
class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // From Animal parent
[Link](); // Dog's own method
}
}
Output:
Eating food
Woof!
2. Multilevel Inheritance (Grandparent → Parent → Child)
A chain of inheritance - like a family tree.
Super Simple Example:
java
// Grandparent
class LivingThing {
void breathe() {
[Link]("Breathing");
}
}
// Parent
class Animal extends LivingThing {
void eat() {
[Link]("Eating");
}
}
// Child - gets EVERYTHING from above!
class Dog extends Animal {
void bark() {
[Link]("Woof!");
}
}
// Run it
class Test {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // From grandparent
[Link](); // From parent
[Link](); // Own method
}
}
Output:
Breathing
Eating
Woof!
3. Hierarchical Inheritance (One Parent, Many Children)
One parent has multiple children.
Super Simple Example:
java
// Parent
class Shape {
void draw() {
[Link]("Drawing shape");
}
}
// Child 1
class Circle extends Shape {
void drawCircle() {
[Link]("Drawing circle");
}
}
// Child 2
class Square extends Shape {
void drawSquare() {
[Link]("Drawing square");
}
}
// Run it
class Test {
public static void main(String[] args) {
Circle c = new Circle();
[Link](); // From parent
[Link](); // Own method
Square s = new Square();
[Link](); // From parent
[Link](); // Own method
}
}
4. Multiple Inheritance (Using Interfaces)
One class gets features from multiple sources (only possible with interfaces).
Super Simple Example:
java
// Interface 1
interface CanFly {
void fly();
}
// Interface 2
interface CanSwim {
void swim();
}
// Duck can do both!
class Duck implements CanFly, CanSwim {
public void fly() {
[Link]("Flying");
}
public void swim() {
[Link]("Swimming");
}
}
// Run it
class Test {
public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}
Question 6 & 7: Create a package named Evenpackage with a class that
has a static method to check whether a number is even or odd. Import this
package in another class and use it.
📚 BEGINNER NOTE: What You Need to Know First
What is a Package?
A package is like a folder to organize your Java files.
Example: All math-related classes in one folder.
What is Static?
Static means you can use it WITHOUT creating an object.
Example: [Link](25) - you don't create a Math object first!
What is Import?
Import brings code from other packages into your program.
Like borrowing a tool from another toolbox.
The % (Modulo) Operator:
num % 2 gives remainder when dividing by 2.
If remainder is 0 → Even number
If remainder is 1 → Odd number
Compilation Steps:
javac -d . creates package folders automatically
The dot (.) means "current directory"
✍️ ANSWER:
Step 1: Create the Package File
File name: [Link]
java
// Package name - MUST be first line!
package Evenpackage;
public class EvenOddChecker {
// Static method - can use without creating object
public static void checkNumber(int num) {
if (num % 2 == 0) {
[Link](num + " is Even");
} else {
[Link](num + " is Odd");
}
}
}
Step 2: Compile the Package
Open terminal and type:
bash
javac -d . [Link]
This creates a folder "Evenpackage" with the class inside.
Step 3: Use the Package
File name: [Link]
java
// Import our package
import [Link];
class TestPackage {
public static void main(String[] args) {
// Use the static method - no object needed!
[Link](10);
[Link](7);
[Link](25);
[Link](100);
}
}
Step 4: Run It
bash
javac [Link]
java TestPackage
Output:
10 is Even
7 is Odd
25 is Odd
100 is Even
Question 8: How would you implement and use the Singleton and
Adapter design patterns in a real-world software project? Explain their
purposes and benefits in practical scenarios.
📚 BEGINNER NOTE: What You Need to Know First
What is a Design Pattern?
A design pattern is a smart solution to a common problem.
Like a recipe that many programmers use.
What is "private"?
Private means only this class can access it.
Others cannot see or use private things.
What is "static"?
Static means belongs to the class, not to objects.
Only one copy exists for everyone.
What is "getInstance()"?
A method name commonly used to get the single instance.
It's a convention (standard practice).
✍️ ANSWER:
Singleton Pattern
Purpose: Make sure only ONE object of a class exists in the entire program.
Real Example: A school has one principal. Everyone goes to the same principal, not different principals.
Super Simple Code:
java
class School {
// Store the one and only principal
private static School principal = null;
// Private constructor - nobody else can create principals!
private School() {
[Link]("Principal hired!");
}
// Everyone gets the same principal
public static School getPrincipal() {
if (principal == null) {
principal = new School();
}
return principal;
}
public void teach() {
[Link]("Principal is teaching");
}
}
// Using Singleton
class Test {
public static void main(String[] args) {
// Teacher 1 meets principal
School p1 = [Link]();
[Link]();
// Teacher 2 meets the SAME principal
School p2 = [Link]();
[Link]();
// Check if same
if (p1 == p2) {
[Link]("Same principal!");
}
}
}
Output:
Principal hired!
Principal is teaching
Principal is teaching
Same principal!
Adapter Pattern
Purpose: Make two incompatible things work together.
Real Example: You have a round peg, but the hole is square. An adapter makes it fit!
Super Simple Code:
java
// Old charger (Indian plug)
class IndianCharger {
public void chargeWithIndianPlug() {
[Link]("Charging with Indian plug");
}
}
// New standard (USB plug)
interface USBCharger {
void chargeWithUSB();
}
// Adapter - makes Indian plug work with USB
class ChargerAdapter implements USBCharger {
IndianCharger oldCharger;
ChargerAdapter(IndianCharger old) {
[Link] = old;
}
public void chargeWithUSB() {
[Link]("Adapter converting...");
[Link]();
}
}
// Using Adapter
class Test {
public static void main(String[] args) {
// Have old Indian charger
IndianCharger old = new IndianCharger();
// Use adapter to make it work with USB
USBCharger adapted = new ChargerAdapter(old);
[Link]();
}
}
Output:
Adapter converting...
Charging with Indian plug
Question 9: Create a user-defined exception 'InvalidAgeException'. Write
a Java program that takes age as a Command Line Argument. Raise the
Exception 'InvalidAgeException' if age is less than 18.
📚 BEGINNER NOTE: What You Need to Know First
What is a Custom Exception?
An exception YOU create for YOUR specific needs.
Built-in exceptions don't cover every situation.
What is "extends Exception"?
Makes your class an exception type.
Now you can throw it like other exceptions.
What are Command Line Arguments?
Values you provide when running the program.
Example: java Program 20 → 20 is the argument
In code, use args[0] to get first argument
What is "throw"?
Throw means "create an error on purpose".
Used when something goes wrong in your logic.
parseInt():
Converts text to number.
"20" (text) becomes 20 (number)
✍️ ANSWER:
java
// Step 1: Create custom exception
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
// Step 2: Main program
class AgeChecker {
public static void main(String[] args) {
// Check if user gave us age
if ([Link] == 0) {
[Link]("Please provide age!");
[Link]("Example: java AgeChecker 20");
return;
}
try {
// Get age from command line
int age = [Link](args[0]);
// Check if age is less than 18
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or more!");
}
// If we reach here, age is valid
[Link]("Valid age: " + age);
[Link]("Access granted!");
}
catch (InvalidAgeException e) {
[Link]("Error: " + [Link]());
}
catch (NumberFormatException e) {
[Link]("Please enter a number!");
}
}
}
How to Run:
Compile:
bash
javac [Link]
Run with age 15:
bash
java AgeChecker 15
Output: Error: Age must be 18 or more!
Run with age 20:
bash
java AgeChecker 20
Output:
Valid age: 20
Access granted!
Question 10: Create a user-defined exception named
NegativeNumberException. Write a Java program that takes a number as
a Command Line Argument. Raise the exception
NegativeNumberException if the entered number is less than zero.
📚 BEGINNER NOTE: What You Need to Know First
Negative Numbers:
Negative means less than zero.
Example: -5, -10, -100 are negative
0 is NOT negative
5, 10, 100 are positive
Command Line Arguments (Review):
Run: java Program 50
In code: args[0] gives you "50"
Must convert to number using parseInt()
✍️ ANSWER:
java
// Step 1: Create custom exception
class NegativeNumberException extends Exception {
NegativeNumberException(String message) {
super(message);
}
}
// Step 2: Main program
class NumberChecker {
public static void main(String[] args) {
// Check if user gave us a number
if ([Link] == 0) {
[Link]("Please provide a number!");
[Link]("Example: java NumberChecker 25");
return;
}
try {
// Get number from command line
int number = [Link](args[0]);
// Check if negative
if (number < 0) {
throw new NegativeNumberException("Number cannot be negative!");
}
// If we reach here, number is valid
[Link]("Valid number: " + number);
[Link]("Number is positive or zero");
}
catch (NegativeNumberException e) {
[Link]("Error: " + [Link]());
}
catch (NumberFormatException e) {
[Link]("Please enter a valid number!");
}
}
}
How to Run:
Compile:
bash
javac [Link]
Run with -5:
bash
java NumberChecker -5
Output: Error: Number cannot be negative!
Run with 10:
bash
java NumberChecker 10
Output:
Valid number: 10
Number is positive or zero
Question 11: Write a Java AWT program that takes two numbers as input
and displays "Monday" if their sum is odd and "Sunday" if their sum is
even.
📚 BEGINNER NOTE: What You Need to Know First
AWT Basics:
Frame = The window
TextField = Box where user types
Button = Clickable button
Label = Text that shows on screen
Layout Manager:
FlowLayout arranges things left to right
Like reading a book - one item after another
getText():
Gets text from TextField
Returns a String (text), not a number!
Must convert using parseInt()
setText():
Changes the text in a Label
Shows new message to user
Why try-catch here?
If user types "abc" instead of number, parseInt() fails
try-catch prevents crash
✍️ ANSWER:
java
import [Link].*;
import [Link].*;
class OddEvenDay extends Frame implements ActionListener {
TextField box1, box2;
Button btn;
Label result;
OddEvenDay() {
// Create components
Label lbl1 = new Label("Number 1:");
box1 = new TextField(10);
Label lbl2 = new Label("Number 2:");
box2 = new TextField(10);
btn = new Button("Check");
result = new Label("Result shows here");
// Tell button to listen
[Link](this);
// Add everything to window
setLayout(new FlowLayout());
add(lbl1);
add(box1);
add(lbl2);
add(box2);
add(btn);
add(result);
// Window settings
setSize(250, 250);
setTitle("Day Checker");
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// When button is clicked, this runs
public void actionPerformed(ActionEvent e) {
try {
// Get numbers from text boxes
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
// Add them
int sum = n1 + n2;
// Check if even or odd
if (sum % 2 == 0) {
[Link]("Sum = " + sum + " (Even) → Sunday");
} else {
[Link]("Sum = " + sum + " (Odd) → Monday");
}
}
catch (NumberFormatException ex) {
[Link]("Enter valid numbers!");
}
}
public static void main(String[] args) {
new OddEvenDay();
}
}
Example:
Type 5 and 3 → Sum = 8 (Even) → "Sunday"
Type 4 and 3 → Sum = 7 (Odd) → "Monday"
Question 12: Write a Java AWT program to take two numbers as input
and display "Positive Sum" if their sum is greater than zero, otherwise
display "Negative or Zero Sum".
📚 BEGINNER NOTE: What You Need to Know First
Positive vs Negative Numbers:
Positive = Greater than 0 (1, 2, 3, 100)
Negative = Less than 0 (-1, -2, -3, -100)
Zero = Exactly 0 (not positive, not negative)
Greater Than (>):
sum > 0 means "sum is greater than zero"
If true, sum is positive
If false, sum is zero or negative
✍️ ANSWER:
java
import [Link].*;
import [Link].*;
class SumChecker extends Frame implements ActionListener {
TextField box1, box2;
Button btn;
Label result;
SumChecker() {
// Create components
Label lbl1 = new Label("Number 1:");
box1 = new TextField(10);
Label lbl2 = new Label("Number 2:");
box2 = new TextField(10);
btn = new Button("Calculate");
result = new Label("Result shows here");
// Tell button to listen
[Link](this);
// Add everything to window
setLayout(new FlowLayout());
add(lbl1);
add(box1);
add(lbl2);
add(box2);
add(btn);
add(result);
// Window settings
setSize(250, 250);
setTitle("Sum Calculator");
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// When button is clicked, this runs
public void actionPerformed(ActionEvent e) {
try {
// Get numbers
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
// Add them
int sum = n1 + n2;
// Check if positive or not
if (sum > 0) {
[Link]("Sum = " + sum + " → Positive Sum");
} else {
[Link]("Sum = " + sum + " → Negative or Zero Sum");
}
}
catch (NumberFormatException ex) {
[Link]("Enter valid numbers!");
}
}
public static void main(String[] args) {
new SumChecker();
}
}
Examples:
Type 5 and 3 → Sum = 8 → "Positive Sum"
Type -5 and 3 → Sum = -2 → "Negative or Zero Sum"
Type 5 and -5 → Sum = 0 → "Negative or Zero Sum"
Question 13: Write a Java program that uses two Textfields and a button.
The first Textfield accepts temperature in Celsius. When the 'Convert'
button is clicked, the second textfield displays the temperature in
Fahrenheit.
📚 BEGINNER NOTE: What You Need to Know First
Celsius vs Fahrenheit:
Celsius (°C) = Used in most countries, including India
Fahrenheit (°F) = Used in USA
Formula: F = (C × 9/5) + 32
Why 9.0 instead of 9?
9.0 makes it a decimal number (double)
Gives accurate decimal results
Example: 37°C = 98.60°F (not 98)
setEditable(false):
Makes TextField read-only
User cannot type in it
Only program can change it
[Link]("%.2f", number):
Formats number to 2 decimal places
Example: 98.6 stays 98.60
Makes output look neat
✍️ ANSWER:
java
import [Link].*;
import [Link].*;
class TempConverter extends Frame implements ActionListener {
TextField celsiusBox, fahrenheitBox;
Button btn;
TempConverter() {
// Create components
Label lbl1 = new Label("Celsius:");
celsiusBox = new TextField(10);
btn = new Button("Convert");
Label lbl2 = new Label("Fahrenheit:");
fahrenheitBox = new TextField(10);
[Link](false); // User can't type here
// Tell button to listen
[Link](this);
// Add everything
setLayout(new FlowLayout());
add(lbl1);
add(celsiusBox);
add(btn);
add(lbl2);
add(fahrenheitBox);
// Window settings
setSize(280, 200);
setTitle("Temperature Converter");
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// When Convert button is clicked
public void actionPerformed(ActionEvent e) {
try {
// Get Celsius temperature
double celsius = [Link]([Link]());
// Convert to Fahrenheit using formula
double fahrenheit = (celsius * 9.0 / 5.0) + 32;
// Show result with 2 decimal places
[Link]([Link]("%.2f", fahrenheit));
}
catch (NumberFormatException ex) {
[Link]("Invalid!");
}
}
public static void main(String[] args) {
new TempConverter();
}
}
Examples:
Type 0 → Result: 32.00°F (freezing point of water)
Type 100 → Result: 212.00°F (boiling point of water)
Type 37 → Result: 98.60°F (normal body temperature)
Type -40 → Result: -40.00°F (same in both scales!)
Question 14: Write a Java AWT program that uses two TextFields and a
Button. The first TextField accepts a number. When the 'Square' button is
clicked, the second TextField should display the square of the entered
number.
📚 BEGINNER NOTE: What You Need to Know First
What is Square?
Square means multiply a number by itself
Symbol: n²
Example: 5² = 5 × 5 = 25
Why [Link]()?
Double allows decimal numbers
[Link]() only allows whole numbers
Double is more flexible (can handle 5 and 5.5)
Why number * number?
Simplest way to square
Could also use [Link](number, 2)
But multiplication is easier!
[Link]():
Converts number back to text
TextField can only show text, not numbers
So we convert: 25 (number) → "25" (text)
✍️ ANSWER:
java
import [Link].*;
import [Link].*;
class SquareCalculator extends Frame implements ActionListener {
TextField numberBox, squareBox;
Button btn;
SquareCalculator() {
// Create components
Label lbl1 = new Label("Enter Number:");
numberBox = new TextField(10);
btn = new Button("Square");
Label lbl2 = new Label("Square:");
squareBox = new TextField(10);
[Link](false); // User can't type here
// Tell button to listen
[Link](this);
// Add everything
setLayout(new FlowLayout());
add(lbl1);
add(numberBox);
add(btn);
add(lbl2);
add(squareBox);
// Window settings
setSize(280, 200);
setTitle("Square Calculator");
setVisible(true);
// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// When Square button is clicked
public void actionPerformed(ActionEvent e) {
try {
// Get the number
double number = [Link]([Link]());
// Calculate square (multiply by itself)
double square = number * number;
// Show result
[Link]([Link](square));
}
catch (NumberFormatException ex) {
[Link]("Invalid!");
}
}
public static void main(String[] args) {
new SquareCalculator();
}
}
Examples:
Type 5 → Result: 25.0 (because 5 × 5 = 25)
Type 10 → Result: 100.0 (because 10 × 10 = 100)
Type 3 → Result: 9.0 (because 3 × 3 = 9)
Type 2.5 → Result: 6.25 (because 2.5 × 2.5 = 6.25)
Type -4 → Result: 16.0 (because -4 × -4 = 16, negative × negative = positive!)
📝 EXAM SUCCESS GUIDE
Must Remember Before Exam:
Import Statements:
java
import [Link].*; // For AWT programs
import [Link].*; // For event handling
import [Link].*; // For Swing programs
import [Link].*; // For file operations
Basic Structure of AWT Program:
java
import [Link].*;
import [Link].*;
class MyProgram extends Frame implements ActionListener {
// Step 1: Declare components
Button btn;
TextField tf;
MyProgram() {
// Step 2: Create components
btn = new Button("Click");
tf = new TextField(10);
// Step 3: Add listener
[Link](this);
// Step 4: Add to window
setLayout(new FlowLayout());
add(btn);
add(tf);
// Step 5: Window settings
setSize(300, 200);
setVisible(true);
// Step 6: Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
// Step 7: Handle button click
public void actionPerformed(ActionEvent e) {
// Your code here
}
public static void main(String[] args) {
new MyProgram();
}
}
Common Formulas:
java
// Check Even/Odd
if (num % 2 == 0) {
// Even
} else {
// Odd
}
// Celsius to Fahrenheit
fahrenheit = (celsius * 9.0 / 5.0) + 32;
// Square of number
square = number * number;
// Check if positive
if (sum > 0) {
// Positive
} else {
// Negative or zero
}
Common Mistakes to Avoid:
1. Forgetting to import packages → Program won't compile
2. Not calling addActionListener(this) → Button won't work
3. Forgetting setVisible(true) → Window won't show
4. Not using try-catch with parseInt() → Program crashes on bad input
5. Forgetting WindowAdapter → Can't close AWT window
Quick Compilation Guide:
Regular Program:
bash
javac [Link]
java MyProgram
With Package:
bash
javac -d . [Link]
javac [Link]
java UsePackage
With Command Line Arguments:
bash
javac [Link]
java Program 20
Last Minute Tips:
✅ Practice typing code 3 times before exam
✅ Remember the order: import → class → constructor → methods
✅ Always use try-catch for parseInt()
✅ Don't forget setVisible(true)!
✅ For custom exceptions, extend Exception
✅ Static methods don't need objects
Good Luck! You've got this! 💪🎯