Docsity

Java questions and answers, Summaries of Java Programming

Toggle sidebar
bg1
EXHAUSTIVE JAVA PROGRAMMING HANDBOOK
Complete Curated Guide: Long Descriptive Answers, 80+ Short Questions/Viva Bank & 36 Practical Lab
Implementations
Target: BCA & B.Sc (Computer Science & IT) 19 Long Theory Answers 80+ Viva/Short Questions 36 Solved Lab Programs
PART I: EXHAUSTIVE UNIVERSITY LONG THEORETICAL ESSAYS (19 MODULES)
Q1. Explain the architecture of the Java Virtual Machine (JVM) in detail. Discuss how the JVM enables Java
programs to be platform-independent.
JVM Architecture: The JVM is an abstract computing machine that provides a runtime environment in which Java bytecode
can be executed. It consists of three primary subsystems:
1. ClassLoader Subsystem: Loads, links, and initializes .class files. Uses Delegation Hierarchy (Bootstrap → Extension/
Platform → Application/System ClassLoader). Verifies bytecode security.
2. Runtime Data Areas (Memory Hierarchy):
Method Area: Shared among all threads. Stores per-class structures, runtime constant pools, field/method metadata, and
static variables.
Heap Area: Shared memory holding all object instances and their non-static variables. Managed by the Garbage
Collector.
JVM Stack: Per-thread memory storing stack frames containing local variables, operand stacks, and method return data.
Program Counter (PC) Registers: Tracks the memory address of the current executing JVM instruction per thread.
Native Method Stack: Manages native C/C++ method invocations via JNI (Java Native Interface).
3. Execution Engine: Contains the Interpreter (executes bytecode line by line), Just-In-Time (JIT) Compiler (compiles
frequently repeated hot code into native machine code), and Garbage Collector.
Platform Independence: Source code is compiled by javac into platform-neutral Bytecode ( .class ). Disparate host
operating systems execute distinct platform-native JVMs which translate this identical bytecode into host-specific native
machine instructions.
Q2. Differentiate between JDK, JRE, and JVM. Explain their roles and interaction during program execution.
Specification JVM (Java Virtual Machine) JRE (Java Runtime Environment) JDK (Java Development Kit)
Core Nature Abstract specification &
runtime engine.
Software deployment package. Full development software suite.
Contents Execution engine, JIT,
ClassLoader, GC.
JVM + Core Libraries ( rt.jar ) +
Runtime files.
JRE + Development tools ( javac ,
jar , jdb ).
Target
Audience
Internal runtime layer. End-users executing compiled Java
apps.
Software developers building Java
apps.
Formula Engine JVM + Libraries JRE + Compiler & Tools
Interaction: A programmer writes Test.java and uses JDK's javac to produce Test.class . The end-user launches the
application using JRE, which loads standard libraries and spins up the JVM to execute bytecode instructions.
Q3. Discuss the key features of Java (Platform Independence, OOP, Security, Portability, Robustness,
Multithreading).
Platform Independent & Portable: "Write Once, Run Anywhere" (WORA) via intermediate bytecode and standard JVM
environments.
•
•
ā—¦
ā—¦
ā—¦
ā—¦
ā—¦
•
•
Java Programming Master Handbook • BCA / B.Sc (Computer Science & IT) Page 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15

Partial preview of the text

Download Java questions and answers and more Summaries Java Programming in PDF only on Docsity!

EXHAUSTIVE JAVA PROGRAMMING HANDBOOK

Complete Curated Guide: Long Descriptive Answers, 80+ Short Questions/Viva Bank & 36 Practical Lab

Implementations

Target: BCA & B.Sc (Computer Science & IT) 19 Long Theory Answers 80+ Viva/Short Questions 36 Solved Lab Programs

PART I: EXHAUSTIVE UNIVERSITY LONG THEORETICAL ESSAYS (19 MODULES)

Q1. Explain the architecture of the Java Virtual Machine (JVM) in detail. Discuss how the JVM enables Java

programs to be platform-independent.

JVM Architecture: The JVM is an abstract computing machine that provides a runtime environment in which Java bytecode

can be executed. It consists of three primary subsystems:

1. ClassLoader Subsystem: Loads, links, and initializes .class files. Uses Delegation Hierarchy (Bootstrap → Extension/

Platform → Application/System ClassLoader). Verifies bytecode security.

2. Runtime Data Areas (Memory Hierarchy):

Method Area: Shared among all threads. Stores per-class structures, runtime constant pools, field/method metadata, and

static variables.

Heap Area: Shared memory holding all object instances and their non-static variables. Managed by the Garbage

Collector.

JVM Stack: Per-thread memory storing stack frames containing local variables, operand stacks, and method return data.

Program Counter (PC) Registers: Tracks the memory address of the current executing JVM instruction per thread.

Native Method Stack: Manages native C/C++ method invocations via JNI (Java Native Interface).

3. Execution Engine: Contains the Interpreter (executes bytecode line by line), Just-In-Time (JIT) Compiler (compiles

frequently repeated hot code into native machine code), and Garbage Collector.

Platform Independence: Source code is compiled by javac into platform-neutral Bytecode ( .class ). Disparate host

operating systems execute distinct platform-native JVMs which translate this identical bytecode into host-specific native

machine instructions.

Q2. Differentiate between JDK, JRE, and JVM. Explain their roles and interaction during program execution.

Specification JVM (Java Virtual Machine) JRE (Java Runtime Environment) JDK (Java Development Kit)

Core Nature Abstract specification & runtime engine.

Software deployment package. Full development software suite.

Contents Execution engine, JIT, ClassLoader, GC.

JVM + Core Libraries ( rt.jar ) + Runtime files.

JRE + Development tools ( javac , jar , jdb ).

Target Audience

Internal runtime layer. End-users executing compiled Java apps.

Software developers building Java apps.

Formula (^) Engine JVM + Libraries JRE + Compiler & Tools

Interaction: A programmer writes Test.java and uses JDK's javac to produce Test.class. The end-user launches the

application using JRE, which loads standard libraries and spins up the JVM to execute bytecode instructions.

Q3. Discuss the key features of Java (Platform Independence, OOP, Security, Portability, Robustness,

Multithreading).

Platform Independent & Portable: "Write Once, Run Anywhere" (WORA) via intermediate bytecode and standard JVM

environments.

  • • ā—¦ ā—¦ ā—¦ ā—¦ ā—¦ • •

Object-Oriented: Pure OOP model organized around classes, objects, encapsulation, inheritance, polymorphism, and

abstraction.

Robust & Safe: Strong type checking, explicit exception handling, automatic garbage collection, and complete elimination of

explicit pointers prevent memory corruption.

Secure: Execution inside a sandboxed JVM environment, Bytecode Verifier, and Security Manager prevent unauthorized

file/network access.

Built-in Multithreading: Rich concurrent processing primitives built into language core via Thread class, Runnable , and

monitor-based synchronization.

Q4. Discuss the fundamental concepts of Java OOP Principles (Encapsulation, Inheritance, Polymorphism,

Abstraction) with comprehensive code examples.

Q5. What are constructors in Java? Explain types of constructors, constructor chaining, and object

initialization roles.

A Constructor is a special member block invoked when an object is instantiated using new. It has no return type and shares

the class name.

Default Constructor: Zero-arg constructor created automatically by compiler if none provided.

Parameterized Constructor: Takes arguments to initialize custom object states.

Copy Constructor: Manually created constructor taking another instance of the same class to clone state.

Constructor Chaining: Invoking one constructor from another using this() (same class) or super() (superclass). Must

be the first statement in the body.

Q6. Elaborate on OOP Principles in Java and discuss how they enhance software reusability and

maintainability.

Maintainability & Reusability Advantages:

Encapsulation restricts unauthorized modification of internal state, ensuring modular code where bugs are isolated to

specific class scopes.

// 1. Abstraction (Hiding internal implementation) abstract class Shape { abstract double calculateArea(); }

// 2. Inheritance (Reusing superclass state & behavior) class Circle extends Shape { // 3. Encapsulation (Private fields with public accessors) private double radius; public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double r) { if (r > 0) this.radius = r; }

// 4. Polymorphism (Runtime Method Overriding) @Override double calculateArea() { return Math.PI * radius * radius; } }

class Vehicle { String type; Vehicle(String t) { this.type = t; } } class Car extends Vehicle { String model; Car() { this("Sedan", "Standard"); } // Calls parameterized constructor Car(String t, String m) { super(t); this.model = m; } // Calls superclass constructor }

Map: Key-value store ( HashMap : fast hashed lookup; TreeMap : key-sorted map).

Q11. What are Wrapper Classes? Discuss Autoboxing, Unboxing, and their role in Collections.

Wrapper classes ( Integer , Double , Boolean , Character , etc.) wrap primitive values inside object containers, enabling

them to be used in generic collections (like ArrayList ) which cannot store raw primitives.

Autoboxing: Automatic conversion from primitive to wrapper object: Integer val = 100;

Unboxing: Automatic extraction of primitive value from wrapper object: int num = val;

Utility Methods: Parsing strings to primitives ( Integer.parseInt("123") ), constant limits ( Integer.MAX_VALUE ).

Q12. Discuss the String class in Java, Immutability, and compare with StringBuffer and StringBuilder.

String Immutability: Once created, a String object's internal character sequence cannot be changed. Any concatenation or

replacement produces a new object in the String Constant Pool (SCP). This guarantees thread safety, security in network/DB

connections, and hashcode caching.

String : Immutable, stored in SCP/Heap, slower on heavy concatenation.

StringBuffer : Mutable, thread-safe (methods synchronized), medium speed.

StringBuilder : Mutable, non-synchronized (not thread-safe), fastest performance for single-threaded string

manipulations.

Q13. Explain the static keyword in Java: Variables, Methods, Blocks, and Context comparison.

The static modifier denotes members that belong to the class itself rather than individual object instances.

Static Variables: Loaded once in the Method Area, shared across all instances of the class (ideal for global counters and

constants).

Static Methods: Invoked via ClassName.methodName() without instantiating an object. Cannot access instance fields or

use this / super directly.

Static Blocks: Initializer blocks executed once when the class is loaded by the ClassLoader before constructor calls.

Q14. What are Packages in Java? Explain naming conventions, creation, import mechanisms, and access

modifiers.

A Package is a namespace container grouping related classes and interfaces, preventing naming collisions and providing

access protection boundaries.

Creation & Import: Declared via package com.university.geometry;. Imported via import

com.university.geometry.Circle; or wildcards.

Access Modifiers Matrix:

Modifier Same Class Same Package Subclass (Diff Pkg) World

private Yes No No No

default (package-private) Yes^ Yes^ No^ No

protected Yes^ Yes^ Yes (via inheritance)^ No

public Yes Yes Yes Yes

Q15. Describe the Life Cycle of a Java Applet and differentiate Applets from Standalone Applications.

Applet Lifecycle Methods:

init() : Initializes variables, GUI controls, and resources (executed once on load).

start() : Starts execution when applet becomes active or browser window is revisited.

paint(Graphics g) : Invoked automatically after start() to render GUI components and graphics.

stop() : Suspends execution when user navigates away from the hosting page.

  • • • • • • • • • • • •

destroy() : Releases allocated system resources before applet destruction (executed once).

Applets vs Standalone Applications: Applications run independently in a standalone JVM with a main() entry point and full

OS access. Applets execute embedded in web browsers or applet viewers under restrictive security sandboxes without a

main() method.

Q16. Explain the Skeleton of a Java Applet with the essential lifecycle methods.

Q17. Explain Multithreading in Java: Thread Creation, Life Cycle, Synchronization, and Deadlock.

Thread Creation: 1) Extending Thread class and overriding run() ; 2) Implementing Runnable interface (preferred for

loose coupling and multiple inheritance compliance).

Synchronization: Ensures only one thread executes a critical section on a given object monitor lock at a time via

synchronized methods or blocks, preventing race conditions and shared data corruption.

Deadlock: Two or more threads permanently waiting on resource locks held by each other. Avoided by: lock ordering, acquiring

locks with timeouts ( ReentrantLock.tryLock() ), and minimizing locked block scopes.

Q18. Explain the Vector class in Java: Features, Synchronization, Dynamic Resizing, and comparison with

ArrayList.

Specification Vector ArrayList

Synchronization Synchronized (Thread-safe by default). Non-synchronized (Not thread-safe).

Performance Slower due to internal lock acquisition overhead. Faster; preferred for single-threaded applications.

Growth Strategy Doubles capacity (100% growth) by default. Increases capacity by 50% ($1.5 imes$).

Legacy Status Legacy class (Java 1.0) retrofitted to implement List. Modern core Collection class (Java 1.2).

Q19. Discuss the Java Database Connectivity (JDBC) API: Architecture, Drivers, and 5-Step Pipeline with

Example.

5-Step JDBC Execution Pipeline:

import java.applet.Applet; import java.awt.Graphics;

/* / public class AppletSkeleton extends Applet { @Override public void init() { / Allocate resources & parameters / } @Override public void start() { / Start worker threads / } @Override public void paint(Graphics g) { g.drawString("Applet Running", 20, 20); } @Override public void stop() { / Suspend threads / } @Override public void destroy() { / Final cleanup */ } }

import java.sql.*;

public class JdbcDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/college_db"; String user = "root", pass = "password"; // 1 & 2. Load Driver & Establish Connection try (Connection con = DriverManager.getConnection(url, user, pass); // 3. Create PreparedStatement PreparedStatement pst = con.prepareStatement("SELECT name, gpa FROM students WHERE id = ?")) { pst.setInt(1, 101); // 4. Execute Query

S11. How do you compile and run a Java program from the command line?

Compile: javac FileName.java | Run: java FileName

S12. What is the significance of System.out.println()?

Outputs data to standard output (console) followed by an automatic newline character.

Section B: Constructors & Object Lifecycle

S13. What is a constructor in Java?

A special member method invoked during object instantiation to initialize the instance variables of an object.

S14. How is a constructor different from a method?

Constructors have no return type (not even void ) and match the class name; methods have explicit return types and perform

operations.

S15. What are the types of constructors in Java?

Default constructor (no-arg) and parameterized constructor.

S16. Explain the concept of a default constructor.

An implicit zero-argument constructor provided by the Java compiler when no explicit constructors are defined.

S17. Can a constructor be overloaded? Provide an example.

Yes, by creating multiple constructors with distinct parameter lists (e.g., Student() and Student(String name) ).

S18. What is the purpose of the this() call in a constructor?

Used for constructor chaining to invoke another constructor within the same class (must be the first statement).

S19. Can constructors be inherited? Explain.

No, constructors cannot be inherited, but subclasses invoke superclass constructors using super().

S20. What is the use of the super() call in a constructor?

Invokes the constructor of the immediate superclass to initialize inherited state.

Section C: OOP, Inheritance, Polymorphism & Interfaces

S21. Define classes and objects in Java.

A class is a blueprint defining structure and behavior; an object is an instantiated physical entity of that class.

S22. What is inheritance in Java?

The OOP mechanism where a subclass inherits fields and methods from a parent class using extends.

S23. Explain polymorphism in Java.

The ability of an entity to take multiple forms, manifesting as method overloading (static) or method overriding (dynamic).

S24. What is method overloading?

Defining multiple methods in the same class with identical names but differing parameter types, counts, or order.

S25. What is method overriding?

Redefining a superclass method in a subclass with an identical name, return type, and parameter signature.

S26. Explain encapsulation with an example.

Binding data and logic together while hiding internal details via private variables with public getters/setters.

S27. What is an abstract class?

A class declared with abstract that cannot be instantiated directly and can contain both abstract and concrete methods.

S28. What is an interface in Java?

A pure reference type defining abstract behavior contracts, constants, and (post-Java 8) default/static methods.

S29. How do you implement multiple inheritance in Java?

Through multiple interface implementation: class C implements A, B { ... }.

S30. What is the default access level of methods in an interface?

Methods are implicitly public abstract (or public default / public static ).

S31. What is the use of the default keyword in an interface?

Allows adding new concrete method implementations to interfaces without breaking existing implementing classes.

S32. Explain functional interfaces with an example.

An interface having exactly one abstract method (SAM), e.g., @FunctionalInterface interface Calc { int op(int

x); }.

Section D: Exception Handling & Collections Framework

S33. What is an exception in Java?

An abnormal event during execution that interrupts the normal flow of program instructions.

S34. What are the 5 keywords used in exception handling?

try , catch , finally , throw , and throws.

S35. What is the purpose of the finally block?

Executes critical cleanup code (closing streams, files, DB connections) regardless of whether an exception occurred.

S36. How can you create a custom exception?

By creating a class that extends java.lang.Exception (checked) or java.lang.RuntimeException (unchecked).

Section F: Multithreading, Applets, JDBC & Advanced Topics

S51. What is multithreading in Java?

Concurrent execution of two or more lightweight threads within a single process to maximize CPU utilization.

S52. Difference between Runnable interface and Thread class?

Implementing Runnable allows extending other classes; extending Thread restricts the class from extending other bases.

S53. What is thread synchronization?

Controlling thread access to shared mutable resources to prevent race conditions and ensure data consistency.

S54. Difference between wait() and sleep()?

wait() releases the lock until notified; sleep() pauses the thread without releasing any locks held.

S55. What is a deadlock?

A deadlock is a situation where two or more threads are permanently blocked, each waiting for a lock held by the other.

S56. What is an Applet in Java?

A small Java GUI program designed to run embedded inside a web browser or applet viewer.

S57. What are the lifecycle methods of an Applet?

init() , start() , paint() , stop() , and destroy().

S58. What is JDBC and what is it used for?

Java Database Connectivity: an API enabling Java applications to connect to relational databases and execute SQL statements.

S59. What is the purpose of PreparedStatement in JDBC?

Precompiles SQL queries for high performance and automatically escapes parameters to prevent SQL Injection attacks.

S60. What are JavaBeans?

Reusable software component classes following conventions: no-arg constructor, private fields with getters/setters, serializable.

S61. What is the Java 8 Stream API?

A declarative pipeline for processing sequences of elements using functional operations ( filter , map , reduce ).

S62. What is a Lambda Expression in Java?

An anonymous function (parameters + arrow token -> + body) providing a concise way to instantiate functional interfaces.

S63. What is the purpose of the Optional class in Java 8?

A container object that may or may not contain a non-null value, designed to cleanly eliminate NullPointerException.

S64. Difference between Comparable and Comparator?

Comparable provides natural sorting via compareTo() ; Comparator defines custom external sorting strategies via

compare().

S65. What is the Java Reflection API?

An API to inspect and dynamically manipulate classes, methods, fields, and constructors at runtime.

S66. What is Garbage Collection in Java?

The automatic memory management process in the JVM that reclaims heap space occupied by unreferenced objects.

S67. What are Annotations in Java?

Metadata tags (e.g., @Override , @Deprecated ) providing instructional context to the compiler and runtime.

S68. Difference between Serializable and Externalizable?

Serializable is a marker interface for default binary serialization; Externalizable requires manual custom serialization

logic.

S69. What is a Singleton class and how is it implemented?

A design pattern ensuring a class has only one instance, implemented using a private constructor and a static factory method.

S70. What is the purpose of the transient keyword?

Marks a field so that its value is skipped and not written during object serialization.

PART III: 36 UNIVERSITY PRACTICAL LABORATORY PROGRAMS & SOLUTIONS

Section 1: Java Basics & Mathematical Logic (Q1 – Q4)

Lab 1. Program to find the sum of two integers entered by the user.

Lab 2. Program to calculate the factorial of a given number using recursion.

import java.util.Scanner; public class SumTwoNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first integer: "); int a = sc.nextInt(); System.out.print("Enter second integer: "); int b = sc.nextInt(); System.out.println("Sum of " + a + " + " + b + " = " + (a + b)); sc.close(); } }

public class RecursiveFactorial { public static long factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }

Lab 6. Rectangle class with length, width, area, and perimeter methods.

Section 3: Constructors & Interfaces (Q7 – Q8)

Lab 7. Employee class implementing Bonus interface with parameterized constructor.

Lab 8. Constructor Chaining demonstration across Vehicle, Car, and Bike.

public class Rectangle { private double length, width; public Rectangle(double length, double width) { this.length = length; this.width = width; } public double calculateArea() { return length * width; } public double calculatePerimeter() { return 2 * (length + width); } public static void main(String[] args) { Rectangle r = new Rectangle(5.0, 3.0); System.out.println("Area: " + r.calculateArea() + " | Perimeter: " + r.calculatePerimeter()); } }

interface Bonus { double calculateBonus(); } public class Employee implements Bonus { private String name; private int empId; private double salary; public Employee(String name, int empId, double salary) { this.name = name; this.empId = empId; this.salary = salary; } @Override public double calculateBonus() { return salary * 0.10; } public void display() { System.out.println("ID: " + empId + " | Name: " + name + " | Bonus: " + calculateBonus()); } public static void main(String[] args) { new Employee("John", 1001, 60000).display(); } }

class Vehicle { Vehicle(String type) { System.out.println("Vehicle Initialized: " + type); } } class Car extends Vehicle { Car(String model) { super("Four-Wheeler"); System.out.println("Car Model: " + model); } } class Bike extends Vehicle { Bike(String brand) { super("Two-Wheeler");

Section 4: Polymorphism & Inheritance (Q9 – Q10)

Lab 9. Abstract Shape class with Circle, Rectangle, and Triangle area calculations.

Lab 10. Animal superclass with Dog and Cat method overriding.

Section 5: String & StringBuffer Processing (Q11 – Q12)

Lab 11. Reverse a given string using StringBuffer.

System.out.println("Bike Brand: " + brand); } } public class ConstructorChainDemo { public static void main(String[] args) { new Car("SUV"); new Bike("Yamaha"); } }

abstract class Shape { abstract double calculateArea(); } class ShapeCircle extends Shape { double r; ShapeCircle(double r) { this.r = r; } @Override double calculateArea() { return Math.PI * r * r; } } class ShapeRect extends Shape { double l, w; ShapeRect(double l, double w) { this.l = l; this.w = w; } @Override double calculateArea() { return l * w; } } class ShapeTri extends Shape { double b, h; ShapeTri(double b, double h) { this.b = b; this.h = h; } @Override double calculateArea() { return 0.5 * b * h; } } public class ShapesPolyTest { public static void main(String[] args) { Shape[] s = { new ShapeCircle(3), new ShapeRect(4, 5), new ShapeTri(4, 6) }; for (Shape item : s) System.out.printf("Area: %.2f%n", item.calculateArea()); } }

class Animal { void sound() { System.out.println("Generic animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class AnimalOverriding { public static void main(String[] args) { Animal a1 = new Dog(); Animal a2 = new Cat(); a1.sound(); a2.sound(); } }

public class ReverseStringBuffer { public static void main(String[] args) { String str = "Java Programming"; String rev = new StringBuffer(str).reverse().toString(); System.out.println("Original: " + str + " | Reversed: " + rev);

Lab 16. Find the second largest element in an array.

Section 8: Multithreading & Exception Handling (Q17 – Q18)

Lab 17. Multithreading: Two threads printing even and odd numbers up to limit.

Lab 18. Safe division method handling ArithmeticException.

Section 9: Wrapper Classes & Autoboxing (Q19 – Q20)

Lab 19. Autoboxing: Convert primitive int to Integer object.

public class ArraySecondLargest { public static void main(String[] args) { int[] arr = { 45, 12, 89, 23, 89, 67, 90, 34 }; int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for (int x : arr) { if (x > first) { second = first; first = x; } else if (x > second && x != first) { second = x; } } System.out.println("Second Largest: " + second); } }

public class EvenOddConcurrency { public static void main(String[] args) { int limit = 10; Thread even = new Thread(() -> { for (int i = 2; i <= limit; i += 2) System.out.println("Even: " + i); }); Thread odd = new Thread(() -> { for (int i = 1; i <= limit; i += 2) System.out.println("Odd: " + i); }); odd.start(); even.start(); } }

public class ExceptionHandlingDivision { public static void divide(int a, int b) { try { int res = a / b; System.out.println("Quotient: " + res); } catch (ArithmeticException e) { System.out.println("Exception Caught: Division by zero is prohibited."); } } public static void main(String[] args) { divide(10, 2); divide(10, 0); } }

Lab 20. Operations on Integer, Double, and Character wrapper classes.

Section 10: Applet Programming (Q21 – Q22)

Lab 21. Applet drawing circle with user-defined radius and color.

Lab 22. Applet displaying horizontally scrolling text banner.

public class AutoboxingDemo { public static void main(String[] args) { int primitiveInt = 42; Integer boxedInt = primitiveInt; // Autoboxing int unboxedInt = boxedInt; // Unboxing System.out.println("Boxed: " + boxedInt + " | Unboxed: " + unboxedInt); } }

public class WrapperOperations { public static void main(String[] args) { Integer i = Integer.valueOf(50); Double d = Double.valueOf(25.5); Character c = Character.valueOf('A'); System.out.println("Sum: " + (i + d) + " | Uppercase char: " + Character.isUpperCase(c)); } }

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class CircleApplet extends Applet { public void paint(Graphics g) { g.setColor(Color.BLUE); g.fillOval(50, 50, 100, 100); } }

import java.applet.Applet; import java.awt.Graphics; public class ScrollBannerApplet extends Applet implements Runnable { String msg = "University Computer Science Java Lab "; Thread t; public void init() { t = new Thread(this); t.start(); } public void run() { while (true) { try { repaint(); Thread.sleep(250); msg = msg.substring(1) + msg.charAt(0); } catch (Exception e) {} } } public void paint(Graphics g) { g.drawString(msg, 20, 50); } }

Section 13: String Verification & Deduping (Q27 – Q28)

Lab 27. Check if a given string is a palindrome.

Lab 28. Remove all duplicate characters from a string.

Section 14: String Conversions & Exceptions (Q29 – Q30)

Lab 29. Convert String to Integer handling NumberFormatException.

Lab 30. Convert String to Double using autoboxing.

set.add("Java"); set.add("Python"); set.add("C++"); set.remove("Python"); for (String lang : set) System.out.println("Language: " + lang); } }

public class PalindromeCheck { public static boolean isPalindrome(String s) { String clean = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); return clean.equals(new StringBuilder(clean).reverse().toString()); } public static void main(String[] args) { String test = "racecar"; System.out.println(test + " is Palindrome? " + isPalindrome(test)); } }

import java.util.LinkedHashSet; public class RemoveDuplicateChars { public static void main(String[] args) { String s = "programming"; LinkedHashSet set = new LinkedHashSet<>(); for (char c : s.toCharArray()) set.add(c); StringBuilder sb = new StringBuilder(); for (char c : set) sb.append(c); System.out.println("Deduplicated: " + sb.toString()); } }

public class StringToIntSafe { public static void main(String[] args) { String raw = "123a"; try { int val = Integer.parseInt(raw); System.out.println("Parsed Value: " + val); } catch (NumberFormatException e) { System.out.println("Invalid numeric string: " + raw); } } }

public class StringToDoubleAuto { public static void main(String[] args) {

Section 15: GUI Graphics & Dynamic Displays (Q31 – Q32)

Lab 31. Applet drawing a bar graph representing student marks.

Lab 32. Simple GUI Calculator with arithmetic action buttons.

Section 16: Advanced File Processing (Q33 – Q34)

Lab 33. Read CSV file and display in formatted tabular format.

String str = "98.75"; Double d = Double.valueOf(str); // Autoboxed System.out.println("Double object: " + d); } }

import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class MarksBarGraphApplet extends Applet { int[] marks = { 75, 90, 60, 85 }; public void paint(Graphics g) { for (int i = 0; i < marks.length; i++) { g.setColor(Color.BLUE); g.fillRect(50 + (i * 60), 200 - marks[i], 40, marks[i]); g.drawString("S" + (i + 1) + ": " + marks[i], 50 + (i * 60), 220); } } }

import java.applet.Applet; import java.awt.; import java.awt.event.; public class SimpleCalcApplet extends Applet implements ActionListener { TextField t1, t2, t3; Button bAdd, bSub; public void init() { t1 = new TextField(5); t2 = new TextField(5); t3 = new TextField(5); bAdd = new Button("+"); bSub = new Button("-"); add(t1); add(t2); add(bAdd); add(bSub); add(t3); bAdd.addActionListener(this); bSub.addActionListener(this); } public void actionPerformed(ActionEvent e) { int v1 = Integer.parseInt(t1.getText()), v2 = Integer.parseInt(t2.getText()); if (e.getSource() == bAdd) t3.setText(String.valueOf(v1 + v2)); else if (e.getSource() == bSub) t3.setText(String.valueOf(v1 - v2)); } }

import java.io.*; import java.util.Scanner; public class CsvTableReader { public static void main(String[] args) { String csvData = "ID,Name,GPA 101,Alice,3. 102,Bob,3.7"; Scanner sc = new Scanner(csvData); while (sc.hasNextLine()) {