0% found this document useful (0 votes)
8 views26 pages

Perfect Numbers and Multiplication Table

The document contains a series of Java programming exercises that cover various concepts such as perfect numbers, Harshad numbers, object-oriented programming (OOP) principles, string compression, data structures, and interfaces. Each exercise includes code examples, line-by-line explanations, and discussions on key programming concepts and best practices. The exercises aim to enhance understanding of Java programming through practical implementation and theoretical insights.

Uploaded by

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

Perfect Numbers and Multiplication Table

The document contains a series of Java programming exercises that cover various concepts such as perfect numbers, Harshad numbers, object-oriented programming (OOP) principles, string compression, data structures, and interfaces. Each exercise includes code examples, line-by-line explanations, and discussions on key programming concepts and best practices. The exercises aim to enhance understanding of Java programming through practical implementation and theoretical insights.

Uploaded by

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

Q1 — Perfect Number + Multiplication Table

import [Link].*;

public class Q1 {

static boolean isPerfect(int n){

if(n<=1) return false;

int sum = 1;

for(int i=2; i*i<=n; i++){

if(n % i == 0){

sum += i;

if(i != n/i) sum += n / i;

return sum == n;

public static void main(String[] args){

Scanner s = new Scanner([Link]);

[Link]("Enter number: ");

int n = [Link]();

[Link](n + (isPerfect(n) ? " is a Perfect Number." : " is not a Perfect Number."));

[Link]("Multiplication table of " + n + ":");

for(int i=1;i<=10;i++) [Link](n + " x " + i + " = " + (n*i));

[Link]();

Line-by-line:

• import [Link].*; — brings in utility classes (here Scanner).

• public class Q1 { — defines the public class named Q1 — filename must be [Link].
• static boolean isPerfect(int n){ — method that checks whether n is perfect; static so
we can call it without creating an object.

• if(n<=1) return false; — by definition, 1 and below are not perfect.

• int sum = 1; — start sum of proper divisors at 1 (1 is a divisor for all n>1).

• for(int i=2; i*i<=n; i++){ — loop i from 2 to sqrt(n) for efficiency.

• if(n % i == 0){ — if i divides n exactly, then:

• sum += i; — add divisor i.

• if(i != n/i) sum += n / i; — add the paired divisor n/i unless both are same (perfect
square case).

• return sum == n; — return true if sum of proper divisors equals n.

• public static void main(String[] args){ — program entry point.

• Scanner s = new Scanner([Link]); — create input reader.

• [Link]("Enter number: "); — prompt user.

• int n = [Link](); — read user integer.

• [Link](... isPerfect(n) ? ... ); — prints if the number is perfect (ternary


operator).

• for(int i=1;i<=10;i++) [Link](...); — prints multiplication table 1–10.

• [Link](); — closes the scanner to free input resource.

Viva focus: What is a perfect number? Why loop to sqrt(n)? Why start sum at 1?

Q2 — Harshad (Niven) Number + Table

import [Link].*;

public class Q2 {

static boolean isHarshad(int n){

int t = [Link](n), sum = 0;

while(t>0){ sum += t%10; t/=10; }

return sum!=0 && n % sum == 0;

public static void main(String[] args){


Scanner s = new Scanner([Link]);

[Link]("Enter number: ");

int n = [Link]();

[Link](n + (isHarshad(n) ? " is a Harshad (Niven) number." : " is not a Harshad


number."));

for(int i=1;i<=10;i++) [Link](n+ " x " + i + " = " + (n*i));

[Link]();

Line-by-line:

• [Link](n) — takes absolute to sum digits when number might be negative.

• while(t>0){ sum += t%10; t/=10; } — repeatedly take last digit (t%10) and remove it
(t/=10) to compute digit sum.

• return sum!=0 && n % sum == 0; — true if digit-sum isn’t zero and n divisible by sum.

• Other lines as in Q1: reading input, printing results and table.

Viva focus: Explain digit extraction via % and /. What about n=0? (digit sum 0 — guard
prevents divide by zero)

Q3 — Car class (properties + behaviors)

public class Q3 {

static class Car {

String brand, color;

int speed;

Car(String b, String c){ brand=b; color=c; speed=0; }

void accelerate(int v){ speed += v; [Link]("Accelerating... Speed: "+speed); }

void brake(int v){ speed = [Link](0, speed - v); [Link]("Braking... Speed:


"+speed); }

void honk(){ [Link](brand + " says Beep Beep!"); }

}
public static void main(String[] args){

Car c = new Car("Toyota","Red");

[Link](30);

[Link]();

[Link](10);

Line-by-line:

• static class Car — nested class for demo; fields brand, color, speed.

• Car(String b, String c){ brand=b; ... } — constructor initialises fields.

• void accelerate(int v){ speed += v; ... } — increases speed by v.

• void brake(int v){ speed = [Link](0, speed - v); ... } — decreases but not below 0.

• void honk() — prints honk with brand.

• Car c = new Car("Toyota","Red"); — creates new object.

• [Link](30); — call method on object.

Viva focus: OOP basics: fields vs methods vs constructor. Why use [Link]?

Q4 — String Compression

public class Q4 {

public static String compress(String s){

if(s==null || [Link]()==0) return "";

StringBuilder sb = new StringBuilder();

int n = [Link]();

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

char ch = [Link](i);

int j = i;

while(j<n && [Link](j)==ch) j++;

[Link](ch).append(j-i);
i = j;

return [Link]();

public static void main(String[] args){

[Link](compress("aaabbcccc")); // a3b2c4

Line-by-line:

• if(s==null || [Link]()==0) return ""; — handle empty or null input.

• StringBuilder sb = new StringBuilder(); — efficient mutable string builder.

• for(int i=0;i<n;){ — note no i++ because i jumps by group size.

• char ch = [Link](i); — current character.

• while(j<n && [Link](j)==ch) j++; — find the end of the run of same chars.

• [Link](ch).append(j-i); — append character and its count.

• i = j; — move to next new character.

Viva focus: Complexity O(n). Why not use String concatenation every time?

Q5 — Student Attendance using Vector

import [Link].*;

public class Q5 {

public static void main(String[] args){

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

[Link]("Alice"); [Link]("Bob"); [Link](1, "Charlie"); // insert at index 1

[Link]("Bob"); // remove by value

[Link]("Contains Alice? " + [Link]("Alice"));

[Link]("Count: " + [Link]());

[Link](v);
}

Line-by-line:

• Vector<String> v = new Vector<>(); — create synchronized list of Strings.

• [Link](1, "Charlie"); — insert at index 1 shifting others.

• [Link]("Bob"); — removes first occurrence by value.

• [Link]("Alice") — check membership.

• [Link]() — number of elements.

Viva focus: Difference between Vector and ArrayList (synchronization). How to iterate?

Q6 — Car mileage array (5 cars)

import [Link].*;

public class Q6 {

public static void main(String[] args){

Scanner s = new Scanner([Link]);

double[] m = new double[5];

double total = 0;

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

[Link]("Mileage for car " + (i+1) + ": ");

m[i] = [Link]();

total += m[i];

[Link]([Link](m));

double max = m[0], min = m[0];

for(double x: m){ if(x>max) max=x; if(x<min) min=x; }

[Link]("Max: " + max + " Min: " + min + " Total: " + total + " Avg: " + (total/5));

[Link]();

}
}

Line-by-line:

• double[] m = new double[5]; — array for 5 mileage values.

• input loop reads each and accumulates total.

• [Link](m) — prints array nicely.

• loop to find max and min.

• average = total/5.

Viva focus: Why double? How to handle unknown number of cars (use ArrayList)?

Q7 — Student registration (constructors)

public class Q7 {

static class Student {

String name; int age;

Student(){ name = "Unknown"; age = 0; }

Student(String n, int a){ name = n; age = a; }

Student(Student other){ [Link] = [Link]; [Link] = [Link]; }

void display(){ [Link]("Name: " + name + ", Age: " + age); }

public static void main(String[] args){

Student s1 = new Student();

Student s2 = new Student("Riya", 19);

Student s3 = new Student(s2);

[Link](); [Link](); [Link]();

Line-by-line:

• Three constructors: default (no args), parameterized, and copy constructor.

• Student(Student other) — copies fields from another Student.


• display() prints fields.

Viva focus: Shallow vs deep copy (this is shallow, strings are immutable so safe).

Q8 — BankAccount (constructor overloading & chaining)

public class Q8 {

static class BankAccount {

String type, holder; double balance;

BankAccount(){ this("Savings", 0.0, "Unknown"); }

BankAccount(String type){ this(type, 0.0, "Unknown"); }

BankAccount(String type, double balance){ this(type, balance, "Unknown"); }

BankAccount(String type, double balance, String holder){

[Link] = type; [Link] = balance; [Link] = holder;

void display(){ [Link](holder + " | " + type + " | ₹" + balance); }

public static void main(String[] args){

BankAccount a1 = new BankAccount();

BankAccount a2 = new BankAccount("Current");

BankAccount a3 = new BankAccount("Savings", 5000);

BankAccount a4 = new BankAccount("Fixed", 10000, "Amit");

[Link](); [Link](); [Link](); [Link]();

Line-by-line:

• this(...) — constructor chaining: one constructor calls another to avoid duplication.

• display() prints account summary.

Viva focus: Constructor chaining rules: must be first line inside constructor.
Q9 — Vehicle inventory (inheritance + super())

public class Q9 {

static class Vehicle {

String brand, model;

Vehicle(String b, String m){ brand=b; model=m; }

static class Car extends Vehicle {

String fuelType;

Car(String b, String m, String f){ super(b,m); fuelType = f; }

void display(){ [Link](brand + " " + model + " | Fuel: " + fuelType); }

public static void main(String[] args){

Car c = new Car("Honda","City","Petrol"); [Link]();

Line-by-line:

• extends Vehicle — Car inherits fields and behavior from Vehicle.

• super(b,m); — call parent constructor to initialize brand and model.

Viva focus: Access levels (private vs protected vs public) and inheritance.

Q10 — HotelRoom (defaults, mapping, copy)

public class Q10 {

static class HotelRoom {

String type; int price;

HotelRoom(){ this("Standard"); }

HotelRoom(String type){

[Link] = type;

switch([Link]()){
case "deluxe": price = 3500; break;

case "suite": price = 5000; break;

default: price = 2000;

HotelRoom(HotelRoom other){ [Link] = [Link]; [Link] = [Link]; }

void display(){ [Link](type + " Room | ₹" + price); }

public static void main(String[] args){

HotelRoom r1 = new HotelRoom();

HotelRoom r2 = new HotelRoom("Suite");

HotelRoom r3 = new HotelRoom(r2);

[Link](); [Link](); [Link]();

Line-by-line:

• switch([Link]()) — handles case-insensitive input.

• default price of 2000.

Viva focus: Copy constructor purpose; switch vs if-else.

Q11 — Device interface + SmartFeature

public class Q11 {

interface Device{ void turnOn(); void turnOff(); }

interface SmartFeature{ void voiceControl(); }

static class Light implements Device, SmartFeature {

public void turnOn(){ [Link]("Light turned ON"); }

public void turnOff(){ [Link]("Light turned OFF"); }

public void voiceControl(){ [Link]("Light responding to voice command"); }


}

static class Fan implements Device, SmartFeature {

public void turnOn(){ [Link]("Fan turned ON"); }

public void turnOff(){ [Link]("Fan turned OFF"); }

public void voiceControl(){ [Link]("Fan responding to voice command"); }

public static void main(String[] args){

Light l = new Light(); Fan f = new Fan();

[Link](); [Link]();

[Link](); [Link](); [Link]();

Line-by-line:

• interface Device — declares method signatures only.

• Classes Light and Fan implement interfaces, must provide method bodies.

• implements Device, SmartFeature — allows multiple interface implementation.

Viva focus: Difference between class and interface. Since Java 8, interfaces can have default
methods.

Q12 — Car rental (abstract Vehicle)

public class Q12 {

static abstract class Vehicle {

String id;

Vehicle(String id){ [Link] = id; }

abstract double calculateRent(int days);

static class Car extends Vehicle {

double perDay = 1000;


Car(String id){ super(id); }

double calculateRent(int days){ return days * perDay; }

static class Bike extends Vehicle {

double perDay = 500;

Bike(String id){ super(id); }

double calculateRent(int days){ return days * perDay; }

public static void main(String[] args){

Vehicle v1 = new Car("C1"); Vehicle v2 = new Bike("B1");

[Link]("Car rent for 3 days: ₹" + [Link](3));

[Link]("Bike rent for 4 days: ₹" + [Link](4));

Line-by-line:

• abstract class Vehicle cannot be instantiated and can contain abstract methods.

• Car and Bike must implement calculateRent.

Viva focus: When to use abstract class vs interface.

Q13 — Smartphone with interfaces

public class Q13 {

static class Phone { void makeCall(String number){ [Link]("Calling " + number +


"..."); } }

interface MusicPlayer{ void playMusic(); }

interface Camera{ void takePhoto(); }

static class SmartPhone extends Phone implements MusicPlayer, Camera {

public void playMusic(){ [Link]("Playing music..."); }

public void takePhoto(){ [Link]("Taking photo..."); }


void videoCall(String number){ [Link]("Video calling " + number + "..."); }

public static void main(String[] args){

SmartPhone sp = new SmartPhone();

[Link]("9876543210"); [Link](); [Link](); [Link]("9876543210");

Line-by-line:

• SmartPhone extends Phone — reuses makeCall.

• implements MusicPlayer, Camera — enforces that playMusic and takePhoto are


defined.

Viva focus: Can SmartPhone inherit from two classes? (No — only one class, multiple
interfaces allowed.)

Q14 — Payroll system (abstract Employee)

public class Q14 {

static abstract class Employee {

String name;

Employee(String n){ name = n; }

abstract double calculatePay();

static class FullTimeEmployee extends Employee {

double salary;

FullTimeEmployee(String n, double s){ super(n); salary = s; }

double calculatePay(){ return salary; }

static class PartTimeEmployee extends Employee {

int hours; double rate;

PartTimeEmployee(String n, int h, double r){ super(n); hours=h; rate=r; }


double calculatePay(){ return hours * rate; }

public static void main(String[] args){

Employee e1 = new FullTimeEmployee("Ravi", 25000);

Employee e2 = new PartTimeEmployee("Kiran", 40, 200);

[Link]([Link] + " earns ₹" + [Link]());

[Link]([Link] + " earns ₹" + [Link]());

Line-by-line:

• abstract double calculatePay() — must be implemented by subclasses to compute


salary.

• FullTimeEmployee returns fixed salary; PartTimeEmployee multiplies hours by rate.

Viva focus: Polymorphism: Employee e = new FullTimeEmployee(...) — you can call


calculatePay() without knowing exact subclass.

Q15 — Multiple inheritance via interfaces

public class Q15 {

interface A{ void showA(); }

interface B{ void showB(); }

static class C implements A, B {

public void showA(){ [Link]("Feature from A"); }

public void showB(){ [Link]("Feature from B"); }

public static void main(String[] args){

C obj = new C();

[Link](); [Link]();

}
Line-by-line:

• implements A, B — class C implements both interfaces, providing both methods. This


simulates multiple inheritance.

Viva focus: Why Java avoids multiple class inheritance (diamond problem).

Q16 — Area calculator (method overloading)

public class Q16 {

static int area(int side){ return side * side; }

static int area(int length, int breadth){ return length * breadth; }

static double area(double radius){ return [Link] * radius * radius; }

public static void main(String[] args){

[Link]("Square(5): " + area(5));

[Link]("Rectangle(4x6): " + area(4,6));

[Link]("Circle(r=3.5): " + area(3.5));

Line-by-line:

• Three area methods with different parameter lists — example of overloading.

• [Link] constant for circle area.

Viva focus: Overload resolution rules (compile-time).

Q17 — Phone call overloading & override

public class Q17 {

static class Phone {

void call(String number){ [Link]("Calling " + number); }

void call(String number, int duration){ [Link]("Calling " + number + " for " +
duration + " mins"); }

static class SmartPhone extends Phone {


@Override

void call(String number){ [Link]("Video calling " + number); }

void call(String number, boolean video){ [Link]("Call " + number + " video? " +
video); }

public static void main(String[] args){

Phone p = new Phone(); SmartPhone s = new SmartPhone();

[Link]("9999999999"); [Link]("9999999999", 5);

[Link]("8888888888"); [Link]("8888888888", true);

Line-by-line:

• Phone has two overloaded call methods (different params).

• SmartPhone overrides the single-argument call(String) to change behavior.

• @Override — optional but recommended to ensure you really override a parent


method.

Viva focus: Difference between overloading and overriding.

Q18 — Employee salary overloading & Manager override

public class Q18 {

static class Employee {

double calculateSalary(double basic){ return basic; }

double calculateSalary(double basic, double bonus){ return basic + bonus; }

static class Manager extends Employee {

@Override

double calculateSalary(double basic){ return [Link](basic) + 0.2 * basic; }

public static void main(String[] args){


Employee e = new Employee(); Manager m = new Manager();

[Link]("Employee: ₹" + [Link](30000));

[Link]("Employee with bonus: ₹" + [Link](30000, 5000));

[Link]("Manager: ₹" + [Link](40000));

Line-by-line:

• [Link](basic) — call parent method to reuse logic.

• 0.2 * basic — manager allowance added.

Viva focus: Use of super and why override.

Q19 — University student (average & pass/fail)

import [Link].*;

public class Q19 {

static class Student {

int rollNo; String name; int[] marks;

public Student(int r, String n, int[] m){ rollNo=r; name=n; marks=m; }

public double calculateAverage(){

int sum=0; for(int x: marks) sum += x; return sum / (double) [Link];

public void displayResult(){

double avg = calculateAverage();

[Link](name + " (" + rollNo + ") Avg: " + avg);

[Link]("Result: " + (avg >= 28 ? "PASS" : "FAIL"));

public static void main(String[] args){

int[] marks = {30,25,35};


Student s1 = new Student(101, "Ravi", marks);

[Link]();

Line-by-line:

• for(int x: marks) — enhanced for loop to sum marks.

• sum / (double) [Link] — cast to double for fractional average.

• avg >= 28 ? "PASS" : "FAIL" — ternary to show pass/fail.

Viva focus: Why cast to double; what if marks array empty (divide by zero).

Q20 — Library Book management

public class Q20 {

static class Book {

int bookId; String title, author; boolean isAvailable = true;

public Book(int id, String t, String a){ bookId=id; title=t; author=a; }

public boolean issueBook(){

if(isAvailable){ isAvailable = false; [Link](title + " issued."); return true; }

[Link](title + " is not available."); return false;

public void returnBook(){ isAvailable = true; [Link](title + " returned."); }

public void displayDetails(){ [Link](bookId + " | " + title + " | " + author + " |
Available: " + isAvailable); }

public static void main(String[] args){

Book b1 = new Book(1, "Java Basics", "James Gosling"); [Link]();


[Link](); [Link]();

Line-by-line:
• isAvailable tracks status.

• issueBook() returns boolean indicating success/failure.

• returnBook() sets available again.

Viva focus: How to store who issued it? (add issuedTo field) How to persist across runs?
(files/db)

Q21 — Calculator with exception handling

import [Link].*;

public class Q21 {

public static void main(String[] args){

Scanner s = new Scanner([Link]);

try{

[Link]("Num: "); double a = [Link]();

[Link]("Den: "); double b = [Link]();

if(b == 0) throw new ArithmeticException("Denominator zero");

[Link]("Result: " + (a / b));

} catch(InputMismatchException ime){

[Link]("Invalid input: enter numbers only.");

} catch(ArithmeticException ae){

[Link]("Error: " + [Link]());

} finally {

[Link]("Calculation attempt finished."); [Link]();

Line-by-line:

• try { ... } catch(...) { ... } finally { ... } — handles exceptions and guarantees finally runs.

• InputMismatchException — thrown if user types non-number when nextDouble()


expected.
• if(b == 0) throw new ArithmeticException(...) — explicitly throw arithmetic error for
division by zero.

Viva focus: Difference between checked and unchecked exceptions (both caught here are
unchecked). finally will run even after return or exception.

Q22 — Result calculation with user-defined exception

import [Link].*;

class MarksOutOfBoundsException extends Exception { MarksOutOfBoundsException(String


msg){ super(msg); } }

public class Q22 {

static void checkMarks(int m) throws MarksOutOfBoundsException {

if(m < 0 || m > 100) throw new MarksOutOfBoundsException("Marks out of range: " + m);

public static void main(String[] args){

Scanner s = new Scanner([Link]);

[Link]("Enter marks (0-100): "); int m = [Link]();

try{ checkMarks(m); [Link]("Marks accepted: " + m); }

catch(MarksOutOfBoundsException e){ [Link]("Exception: " +


[Link]()); }

[Link]();

Line-by-line:

• class MarksOutOfBoundsException extends Exception — custom checked exception


type.

• throws MarksOutOfBoundsException — declares the method may throw this


exception; caller must handle it.

• throw new MarksOutOfBoundsException(...) — create and throw the exception when


marks invalid.
Viva focus: Checked vs unchecked exceptions. How to make it unchecked? (extend
RuntimeException)

Q23 — Bank minimum balance custom exception

import [Link].*;

class MinimumBalanceException extends Exception { MinimumBalanceException(String


msg){ super(msg); } }

public class Q23 {

static class Bank {

double balance = 2000;

void withdraw(double amt) throws MinimumBalanceException {

if(balance - amt < 1000) throw new MinimumBalanceException("Withdrawal denied!


Minimum balance ₹1000 required.");

balance -= amt; [Link]("Withdrawal successful. New balance: ₹" + balance);

public static void main(String[] args){

Scanner s = new Scanner([Link]);

Bank b = new Bank();

[Link]("Enter amount to withdraw: "); double amt = [Link]();

try{ [Link](amt); } catch(MinimumBalanceException e){


[Link]([Link]()); }

[Link]();

Line-by-line:

• MinimumBalanceException — custom checked exception for domain rule.

• withdraw(...) throws MinimumBalanceException — declaration to force caller to


handle.
• If withdrawal would make balance < ₹1000, throw exception; otherwise update
balance.

Viva focus: Why use custom exception? How to handle transactions more robustly?

Q24 — Threads using Runnable

// [Link]

class Weather implements Runnable {

String type;

Weather(String t){ type=t; }

public void run(){

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

[Link](type+" reading "+i+" : "+([Link]()*100));

try{ [Link](500); }catch(Exception e){}

public class Q24 {

public static void main(String[] a){

Thread t1=new Thread(new Weather("Temperature"));

Thread t2=new Thread(new Weather("Humidity"));

Thread t3=new Thread(new Weather("Weather Report"));

[Link](); [Link](); [Link]();

Explanation

• Weather implements Runnable → defines a run() method executed by a thread.

• 3 threads created → each prints random readings.

• [Link](500) pauses half a second between readings.

• All 3 run concurrently.


Viva Qs

1. Why use Runnable? → So class can extend another if needed; separates logic from
thread object.

2. Difference between start() and run()? → start() begins new thread; run() runs in same
thread.

3. How to make threads run sequentially? → Use join().

Q25 — Buffered File Read/Write

// [Link]

import [Link].*;

class Q25 {

public static void main(String[] a)throws Exception{

String s="Name: Rahul\nClass: 12-A\nRoll: 24";

FileOutputStream f=new FileOutputStream("[Link]");

BufferedOutputStream b=new BufferedOutputStream(f);

[Link]([Link]()); [Link]();

[Link]("File written.");

FileInputStream fi=new FileInputStream("[Link]");

BufferedInputStream bi=new BufferedInputStream(fi);

int i; while((i=[Link]())!=-1) [Link]((char)i);

[Link]();

Explanation

• BufferedOutputStream → writes efficiently using memory buffer.

• write() → sends bytes of your string to file.

• Then read with BufferedInputStream and print char by char.


Viva Qs

1. Why use buffered streams? → Faster I/O by reducing disk access.

2. What is getBytes()? → Converts string to byte array for writing.

3. Which exception must be handled? → IOException.

Q26 — Swing Online Shopping Page

// [Link]

import [Link].*;

import [Link].*;

class Q26 {

public static void main(String[] a){

JFrame f=new JFrame("Shopping");

String items[]={"Laptop","Phone","Bag","Watch"};

JList<String> list=new JList<>(items);

JTextArea area=new JTextArea();

JButton add=new JButton("Add"), check=new JButton("Checkout");

[Link](e->{ [Link]([Link]()+"\n"); });

[Link](e->{
[Link](f,"Items:\n"+[Link]()); });

[Link](list); [Link](add); [Link](area); [Link](check);

[Link](new [Link]());

[Link](300,300); [Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

Explanation
• JList shows item list; JTextArea displays cart.

• Add → appends selected item to cart.

• Checkout → shows dialog with all selected items.

• Uses simple FlowLayout for compact design.

Viva Qs

1. Which package has Swing classes? → [Link].

2. What does addActionListener do? → Handles button click event.

3. Difference between AWT and Swing? → Swing is lightweight and platform-


independent.

Q27 — AWT Simple Calculator

// [Link]

import [Link].*;

import [Link].*;

class Q27 extends Frame implements ActionListener{

TextField t1=new TextField(5), t2=new TextField(5);

Label res=new Label("Result:");

Button a=new Button("+"), s=new Button("-"), m=new Button("*"), d=new Button("/");

Q27(){

add(t1); add(t2); add(a); add(s); add(m); add(d); add(res);

setLayout(new FlowLayout()); setSize(250,150); setVisible(true);

[Link](this); [Link](this); [Link](this);


[Link](this);

addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent


e){dispose();}});

public void actionPerformed(ActionEvent e){

double x=[Link]([Link]()), y=[Link]([Link]()), r=0;


String op=[Link]();

if([Link]("+"))r=x+y; else if([Link]("-"))r=x-y;

else if([Link]("*"))r=x*y; else if([Link]("/"))r=y==0?0:x/y;

[Link]("Result: "+r);

public static void main(String[] a){ new Q27(); }

Explanation

• Extends Frame → main AWT window.

• Two TextFields for input; four Buttons for operations.

• actionPerformed does calculation and updates label.

• windowClosing closes the app safely.

Viva Qs

1. What does implements ActionListener mean? → Class handles button click events.

2. What happens if user types non-number? → NumberFormatException.

3. Why dispose() in windowClosing? → Closes the window properly.

Common questions

Powered by AI

Java uses interfaces such as 'Device' and 'SmartFeature' to define method signatures without implementing them, thus promoting a separation of capabilities from implementation. This allows classes to provide their own versions of methods such as 'turnOn' and 'voiceControl', which can greatly vary in implementation. Interfaces enable multiple inheritance of types, unlike abstract classes, which may have shared fields or methods and can add more complexity and overhead if multiple inheritance of functionality is needed. This makes interfaces lightweight and flexible for implementing targeted functionalities across disparate hierarchies. Meanwhile, abstract classes serve well when there is common base-level implementation across all subclasses .

Inheritance allows the 'Car' class to inherit fields and behavior from the 'Vehicle' class. This means that the 'Car' class has access to the 'brand' and 'model' attributes defined in the 'Vehicle' class. The 'super()' keyword is used to call the constructor of the parent class, initializing these inherited fields .

In the 'Phone' and 'SmartPhone' class examples, method overloading occurs when multiple methods within the same class have the same name but differ in the type or number of parameters, such as 'call(String)' and 'call(String, int)' in 'Phone'. This allows different logic depending on method signature. Overriding, as seen in 'SmartPhone', happens when a subclass provides a specific implementation of a method already defined in its superclass, even with the same parameter list, such as overriding 'call(String)' to implement video calling, changing the inherited behavior to suit subclass-specific needs .

An abstract class like 'Vehicle' is preferable when there is a shared base behavior or state that needs to be initialized and used across all subclasses, such as the 'id' field and 'calculateRent' method in the Car Rental example. It allows for more inherent functionality like maintaining common data fields or partially implementing shared methods, which interfaces cannot do. For scenarios where different subclass models (like 'Car' and 'Bike') must share common functionality or helper methods, abstract classes provide a structured way to enforce and maintain this shared structure and logic .

In the Bank withdrawal example, exceptions play a critical role in ensuring business rule compliance by preventing operations that would breach defined constraints, such as maintaining a minimum balance. The 'MinimumBalanceException' is used as a custom checked exception that enforces withdrawal limits by rejecting transactions that would result in a balance falling below ₹1000. This practice encapsulates business logic into exception handling, offering robust error management and ensuring that illegal transactions are prevented, which enhances system reliability and guides user action through clear, exceptional messages .

Method overloading in the Area calculator example demonstrates how multiple methods can share the same name but differ in their parameter lists, enabling the calculation of areas for squares, rectangles, and circles using different inputs such as 'int' and 'double'. This provides flexibility, as it allows the same logical operation—computing an area—to be applied to different sets of data inputs while maintaining semantic consistency across method names. This approach streamlines code readability and organization by associating a singular concept ('area') with the same method name across different contexts .

Interfaces in Java, such as 'MusicPlayer' and 'Camera', allow a class like 'SmartPhone' to implement multiple sets of behaviors or functionalities by defining essential method signatures. Unlike classes, interfaces cannot hold state (instance variables), ensuring that any class implementing them provides concrete behavior. While both interfaces and instance's parent classes guide the structure of a class, interfaces allow for a type of multiple inheritance that classes do not, as Java classes can only extend one parent class due to the diamond problem .

Polymorphism is highlighted in the Payroll system through the ability to treat different types of 'Employee' objects (FullTimeEmployee and PartTimeEmployee) as their superclass type. The 'calculatePay()' method can be called on an 'Employee' reference without knowing the exact subclass at compile time, because the actual method executed depends on the runtime type of the employee. This abstraction allows the system to process both types of employees in a uniform manner while varying the calculation logic internally for each employee subtype, thus simplifying the codebase and improving flexibility .

The copy constructor in the 'HotelRoom' class is used to create a new instance of 'HotelRoom' with the same attributes as an existing instance by copying its 'type' and 'price'. In contrast, the constructor that uses default values initializes a 'HotelRoom' with a standard or specified type, assigning a price based on the type provided ('Standard' room price is set at 2000 by default). The copy constructor avoids re-executing logic for determining the 'price', thereby directly copying the state of the 'type' and 'price' from another object .

Java avoids multiple inheritance of classes due to the complexity and ambiguity it introduces, commonly known as the diamond problem, where a class cannot unambiguously inherit fields and methods from multiple parent classes. Interfaces provide a solution by allowing class C to implement multiple interfaces, like A and B, thus inheriting method signatures without carrying state or behavior from more than one class hierarchy. This resolves potential conflicts in method inheritance as interfaces only define forms, ensuring that implementing classes provide the necessary method implementations .

You might also like