2MARKS QUESTION
1. Define constructor with its syntax and enlist its types.
2. List and explain different access specifier.
3. Write short note on type casting.
4. Explain Conditional operator in java with example.
5. Explain any four features of Java.
6. What is the difference between String and String Buffer classes
in Java?
7. What are wrapper classes in Java? Explain with examples.
4MARKS QUESTION
1. Explain the concept of garbage collection in Java.
2. Explain shift operator in java with example
3. Write a program to accept 2 numbers from user and perform
arithmetic operations
4. Define a class Rectangle with length and breadth. Create a
default constructor and parameterized constructor to calculate
area of rectangle.
5. Explain any 4 String functions and 4 StringBuffer functions with
its syntax.
6. Write a program to insert 4 elements in vector of Integer type
and 4 elements of String type. Remove element at 6th index and
display vector.
7. Explain while loop and do while loop with example.
8. Explain logical and assignment operator with example
9. Explain bitwise operator in java with example
give answer of this according their marks [2,4]
2 MARKS QUESTIONS
1. Define constructor with its syntax and enlist its types.
Constructor: A special member method used to initialize objects of a class. It has
the same name as the class and no return type.
Syntax:
java
class ClassName {
ClassName() { // constructor
// initialization code
}
}
Types:
1. Default constructor (no parameters)
2. Parameterized constructor (with parameters)
3. Copy constructor (copies another object's values)
2. List and explain different access specifiers.
Access specifiers control visibility of class members:
1. private - Accessible only within the class
2. default (no specifier) - Accessible within same package
3. protected - Accessible within same package and subclasses
4. public - Accessible from anywhere
3. Write short note on type casting.
Type casting is converting one data type to another.
Two types:
1. Implicit (Widening) - Automatically by compiler (smaller to larger type)
int x = 10; double y = x;
2. Explicit (Narrowing) - Manual casting (larger to smaller type)
double x = 10.5; int y = (int)x;
4. Explain Conditional operator in java with example.
Conditional (Ternary) operator: ? :
Syntax: condition ? expression1 : expression2
Example:
java
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
5. Explain any four features of Java.
1. Platform Independent - Write once, run anywhere (WORA) using bytecode
2. Object-Oriented - Supports OOP concepts (inheritance, polymorphism, etc.)
3. Secure - No explicit pointers, bytecode verification, sandbox environment
4. Multithreading - Built-in support for concurrent programming
6. What is the difference between String and String Buffer
classes?
String StringBuffer
Immutable (cannot change) Mutable (can change)
Stored in constant pool Stored in heap memory
Slower for concatenation Faster for modifications
StringBuffer sb = new
String s = "Hello";
StringBuffer("Hello");
7. What are wrapper classes in Java? Explain with examples.
Wrapper classes convert primitive data types into objects.
Examples:
int → Integer
char → Character
double → Double
boolean → Boolean
Example:
java
int num = 10;
Integer obj = [Link](num); // boxing
int n = [Link](); // unboxing
4 MARKS QUESTIONS
1. Explain the concept of garbage collection in Java.
Garbage Collection: Automatic memory management process that removes unused
objects to free memory.
How it works: JVM's garbage collector identifies objects no longer referenced
Advantages: Prevents memory leaks, no manual memory management needed
Methods: [Link]() suggests garbage collection (not guaranteed)
Example:
java
Object obj = new Object();
obj = null; // Object becomes eligible for GC
2. Explain shift operator in java with example
Shift operators move bits left/right:
1. Left Shift ( << ) - Shifts bits left, fills 0 at right
int x = 8; // 1000
x << 2; // 100000 = 32
2. Right Shift ( >> ) - Shifts bits right, preserves sign
int y = -8; // 111...1000
y >> 2; // 111...1110 = -2
3. Unsigned Right Shift ( >>> ) - Shifts bits right, fills 0 at left
int z = -8;
z >>> 2; // 001...1110 = large positive
3. Write a program to accept 2 numbers and perform arithmetic
operations
java
import [Link];
public class Arithmetic {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Modulus: " + (a % b));
[Link]();
}
}
4. Define a class Rectangle with constructors to calculate area
java
class Rectangle {
double length, breadth;
// Default constructor
Rectangle() {
length = 1.0;
breadth = 1.0;
}
// Parameterized constructor
Rectangle(double l, double b) {
length = l;
breadth = b;
}
double calculateArea() {
return length * breadth;
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // uses default
[Link]("Default area: " + [Link]());
Rectangle r2 = new Rectangle(5.0, 3.0);
[Link]("Parameterized area: " + [Link]());
}
}
5. Explain any 4 String functions and 4 StringBuffer functions
String functions:
1. length() - Returns string length
2. charAt(int index) - Returns character at index
3. substring(int begin) - Returns substring from begin index
4. equals(String str) - Compares strings content
StringBuffer functions:
1. append(String str) - Appends string
2. insert(int offset, String str) - Inserts at position
3. delete(int start, int end) - Deletes subsequence
4. reverse() - Reverses the sequence
6. Program with Vector to insert elements and remove at index
java
import [Link];
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
// Add Integer elements
for(int i = 1; i <= 4; i++) {
[Link](i * 10); // Integer
}
// Add String elements
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Date");
[Link]("Original Vector: " + v);
// Remove element at 6th index (0-based)
[Link](6);
[Link]("After removing 6th index: " + v);
}
}
7. Explain while loop and do while loop with example
while loop: Entry-controlled, checks condition first
java
int i = 1;
while(i <= 5) {
[Link](i + " ");
i++;
} // Output: 1 2 3 4 5
do-while loop: Exit-controlled, executes at least once
java
int j = 1;
do {
[Link](j + " ");
j++;
} while(j <= 5); // Output: 1 2 3 4 5
Difference: do-while executes body before checking condition.
8. Explain logical and assignment operator with example
Logical operators: Combine boolean expressions
&& (AND): true && true = true
|| (OR): false || true = true
! (NOT): !true = false
Assignment operators: Assign values with operation
= : Simple assignment
+= : a += 5 (a = a + 5)
-= : a -= 3 (a = a - 3)
*= : a *= 2 (a = a * 2)
Example:
java
int a = 10;
a += 5; // a = 15
boolean x = true, y = false;
boolean z = x && y; // z = false
9. Explain bitwise operator in java with example
Bitwise operators work on bits:
1. & (AND) - 5 & 3 = 1 (0101 & 0011 = 0001)
2. | (OR) - 5 | 3 = 7 (0101 | 0011 = 0111)
3. ^ (XOR) - 5 ^ 3 = 6 (0101 ^ 0011 = 0110)
4. ~ (Complement) - ~5 = -6 (~0101 = 1010)
Example:
java
int a = 5, b = 3;
[Link]("AND: " + (a & b)); // 1
[Link]("OR: " + (a | b)); // 7
[Link]("XOR: " + (a ^ b)); // 6
[Link]("Complement of a: " + (~a)); // -6
Screenshot 2026-01-22… Screenshot 2026-01-22…
PNG 25.21KB PNG 59.99KB
Screenshot 2026-01-22…
PNG 26.15KB
2MARKS QUESTION
1. Define inheritance and enlist the types of inheritance, which is
supported by java.
2. Define the interface with its syntax in java.
3. Explain method overriding with example.
4. Explain super keyword with example and uses.
5. Define static import with example in java.
6. Explain abstract class with methods.
4 MARKS QUESTION
1. Explain hierarchical inheritance with the diagram and example.
2. Explain Multilevel inheritance with the diagram and example.
3. Write short note on final keyword with example
4. Develop a program to create a class “Book” having data
members “author”, “title” and “price”. Derive a class “BookInfo”
having data member “stockposition” and “method to initialize and
display the information for three objects.
5. Explain concept of package with example.
6. Explain user defined packages with example.
7. Write java code for following fig(and give code name)
give answer of this according their marks [2,4]
2 MARKS QUESTIONS
1. Define inheritance and enlist the types of inheritance
supported by Java.
Inheritance: A mechanism where a child class acquires properties and behaviors of
a parent class. It promotes code reusability and establishes IS-A relationship.
Types of inheritance supported by Java:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
Note: Java does NOT support:
Multiple inheritance (through classes)
Hybrid inheritance
2. Define interface with its syntax in Java.
Interface: A blueprint of a class that contains only abstract methods (until Java 7)
and constants. From Java 8 onwards, it can have default and static methods too.
Syntax:
java
interface InterfaceName {
// constant fields (implicitly public static final)
int CONSTANT = 10;
// abstract methods (implicitly public abstract)
void methodName();
// default method (Java 8+)
default void defaultMethod() {
// implementation
}
// static method (Java 8+)
static void staticMethod() {
// implementation
}
}
3. Explain method overriding with example.
Method overriding: When a subclass provides a specific implementation of a
method already defined in its parent class.
Rules:
Method name and parameters must be same
Return type should be same or covariant
Cannot reduce visibility (private < default < protected < public)
Example:
java
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
4. Explain super keyword with example and uses.
super keyword: Refers to immediate parent class object.
Uses:
1. To call parent class constructor
2. To call parent class methods
3. To access parent class variables
Example:
java
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
[Link](x); // 20 (child's x)
[Link](super.x); // 10 (parent's x)
}
}
5. Define static import with example in Java.
Static import: Allows accessing static members of a class without class name
qualification.
Example:
java
// Without static import
import [Link];
double result = [Link](25);
// With static import
import static [Link].*;
double result = sqrt(25); // No need for [Link]()
6. Explain abstract class with methods.
Abstract class: A class declared with abstract keyword that cannot be instantiated.
It may contain abstract methods (without body) and concrete methods (with body).
Example:
java
abstract class Shape {
// Abstract method (no implementation)
abstract void draw();
// Concrete method (with implementation)
void display() {
[Link]("Displaying shape");
}
}
class Circle extends Shape {
@Override
void draw() {
[Link]("Drawing circle");
}
}
4 MARKS QUESTIONS
1. Explain hierarchical inheritance with diagram and example.
Hierarchical inheritance: Multiple child classes inherit from a single parent class.
Diagram:
text
Class A (Parent)
/ | \
/ | \
Class B Class C Class D (Children)
Example:
java
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Cat extends Animal {
void meow() {
[Link]("Meowing...");
}
}
class Lion extends Animal {
void roar() {
[Link]("Roaring...");
}
}
2. Explain multilevel inheritance with diagram and example.
Multilevel inheritance: A class inherits from another class which itself inherits from
another class.
Diagram:
text
Class A (Grandparent)
↓
Class B (Parent)
↓
Class C (Child)
Example:
java
class Grandfather {
void property() {
[Link]("Land property");
}
}
class Father extends Grandfather {
void car() {
[Link]("Car");
}
}
class Son extends Father {
void bike() {
[Link]("Bike");
}
}
// Son has access to property(), car(), and bike()
3. Write short note on final keyword with example.
final keyword: Used to restrict the user.
Three uses:
1. final variable - Cannot be changed (constant)
java
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // Error: cannot assign new value
2. final method - Cannot be overridden
java
class Parent {
final void display() {
[Link]("Cannot override");
}
}
3. final class - Cannot be inherited
java
final class FinalClass {
// This class cannot be extended
}
// class Child extends FinalClass {} // Error
4. Program for Book and BookInfo classes
java
class Book {
String author, title;
double price;
// Constructor
Book(String author, String title, double price) {
[Link] = author;
[Link] = title;
[Link] = price;
}
void display() {
[Link]("Author: " + author);
[Link]("Title: " + title);
[Link]("Price: " + price);
}
}
class BookInfo extends Book {
int stockPosition;
// Constructor
BookInfo(String author, String title, double price, int stockPosition) {
super(author, title, price);
[Link] = stockPosition;
}
@Override
void display() {
[Link]();
[Link]("Stock Position: " + stockPosition);
[Link]("------------------------");
}
}
public class Main {
public static void main(String[] args) {
// Create three BookInfo objects
BookInfo[] books = new BookInfo[3];
books[0] = new BookInfo("J.K. Rowling", "Harry Potter", 599.99, 50);
books[1] = new BookInfo("George Orwell", "1984", 399.99, 30);
books[2] = new BookInfo("Paulo Coelho", "The Alchemist", 299.99, 75);
// Display all books
for(BookInfo book : books) {
[Link]();
}
}
}
5. Explain concept of package with example.
Package: A grouping of related classes/interfaces. It helps in:
Organizing code
Preventing naming conflicts
Controlling access
Types:
1. Built-in packages ([Link], [Link], etc.)
2. User-defined packages
Example:
java
// Save as [Link]
package mypackage; // Package declaration
public class Test {
public void display() {
[Link]("Hello from mypackage");
}
}
// Using the package
import [Link];
public class Main {
public static void main(String[] args) {
Test obj = new Test();
[Link]();
}
}
6. Explain user-defined packages with example.
User-defined package: Created by programmers to organize their own classes.
Steps to create:
1. Declare package at top of file
2. Create directory structure matching package name
3. Compile with -d option
4. Import and use
Example:
text
Step 1: Create file [Link]
package [Link];
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Step 2: Create directory structure
math/operations/
Step 3: Compile
javac -d . [Link]
Step 4: Use in another class
import [Link];
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](10, 20));
}
}
7. Write Java code for the given figures
For Screenshot 1 (Gross Interface):
java
// Gross Interface
interface Gross {
double TA = 5000; // Travel Allowance
double DA = 8000; // Dearness Allowance
double gross_sal(); // Abstract method
}
// Employee Class
class Employee {
String name;
double basic_sal;
Employee(String name, double basic_sal) {
[Link] = name;
this.basic_sal = basic_sal;
}
}
// Salary Class extending Employee and implementing Gross
class Salary extends Employee implements Gross {
double HRA; // House Rent Allowance
Salary(String name, double basic_sal, double HRA) {
super(name, basic_sal);
[Link] = HRA;
}
@Override
public double gross_sal() {
return basic_sal + HRA + TA + DA;
}
void disp_sal() {
[Link]("Employee Name: " + name);
[Link]("Basic Salary: " + basic_sal);
[Link]("HRA: " + HRA);
[Link]("TA: " + TA);
[Link]("DA: " + DA);
[Link]("Gross Salary: " + gross_sal());
}
}
For Screenshot 2 (Exam Interface):
java
// Exam Interface
interface Exam {
int SportsMark = 20; // Constant
}
// Student Class
class Student {
int rollNo;
String sName;
int m1, m2, m3;
Student(int rollNo, String sName, int m1, int m2, int m3) {
[Link] = rollNo;
[Link] = sName;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
}
// Result Class extending Student and implementing Exam
class Result extends Student implements Exam {
Result(int rollNo, String sName, int m1, int m2, int m3) {
super(rollNo, sName, m1, m2, m3);
}
void display() {
int total = m1 + m2 + m3 + SportsMark;
[Link]("Roll No: " + rollNo);
[Link]("Student Name: " + sName);
[Link]("Marks - Subject1: " + m1);
[Link]("Marks - Subject2: " + m2);
[Link]("Marks - Subject3: " + m3);
[Link]("Sports Marks: " + SportsMark);
[Link]("Total Marks: " + total);
}
}
For Screenshot 3 (Multilevel Inheritance):
java
// Square Class
class Square {
double length;
Square(double length) {
[Link] = length;
}
double area() {
return length * length;
}
}
// Rectangle Class extending Square
class Rectangle extends Square {
double breadth;
Rectangle(double length, double breadth) {
super(length);
[Link] = breadth;
}
double rectarea() {
return length * breadth;
}
}
// Box Class extending Rectangle
class Box extends Rectangle {
double height;
Box(double length, double breadth, double height) {
super(length, breadth);
[Link] = height;
}
double volume() {
return length * breadth * height;
}
void displayAll() {
[Link]("Square Area: " + area());
[Link]("Rectangle Area: " + rectarea());
[Link]("Box Volume: " + volume());
}
}
1. Explain Error and Exceptions. Explain Types of error.
2. Explain try catch finally Block With Synatx And Example.
3. Write a Program to accept password from user and throw
‘Authentication failure’ exception if password is incorrect.
give answer of this according their marks [4]
4 MARKS QUESTIONS
1. Explain Error and Exceptions. Explain Types of error.
Error vs Exception:
Error Exception
Represents serious problems that Represents conditions that applications
applications should not try to catch might want to catch
Occurs due to lack of system resources Occurs due to program logic issues
Generally cannot be recovered from Can be recovered from using try-catch
Examples: OutOfMemoryError , Examples: IOException , SQLException ,
StackOverflowError NullPointerException
Error Exception
Belongs to [Link] class Belongs to [Link] class
Types of Errors:
1. Compile-time Errors (Syntax Errors)
Occur during compilation
Due to syntax violations
Example: Missing semicolon, wrong spelling
java
int x = 10 // Error: missing semicolon
[Link](x)
2. Runtime Errors (Exceptions)
Occur during program execution
Program compiles successfully
Example: Division by zero, array index out of bounds
java
int x = 10/0; // ArithmeticException
int[] arr = new int[5];
arr[10] = 50; // ArrayIndexOutOfBoundsException
3. Logical Errors
Program runs without crashing but produces wrong output
Due to incorrect algorithm/logic
Most difficult to detect
java
// Logical error: wrong formula for area of circle
double area = 2 * 3.14 * radius; // Should be 3.14 * radius * radius
2. Explain try-catch-finally Block with Syntax and Example.
Exception Handling Mechanism: Used to handle runtime errors gracefully.
Syntax:
java
try {
// Code that may throw exception
// Risky code
}
catch(ExceptionType1 e1) {
// Handle ExceptionType1
// Recovery code
}
catch(ExceptionType2 e2) {
// Handle ExceptionType2
// Recovery code
}
finally {
// Cleanup code
// Always executes (except [Link]())
}
Explanation:
1. try block: Contains code that might throw an exception
2. catch block: Catches and handles specific exceptions
3. finally block: Always executes (for cleanup operations)
Example:
java
public class ExceptionDemo {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
int result = 0;
try {
[Link]("Try block started");
result = numbers[5] / 0; // This will throw ArrayIndexOutOfBoundsExcepti
on
[Link]("This line won't execute");
}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Caught ArrayIndexOutOfBoundsException: " + [Link]
ge());
result = numbers[0]; // Recovery: use first element
}
catch(ArithmeticException e) {
[Link]("Caught ArithmeticException: " + [Link]());
}
catch(Exception e) {
[Link]("Caught general Exception: " + [Link]());
}
finally {
[Link]("Finally block always executes");
[Link]("Cleaning up resources...");
}
[Link]("Result: " + result);
[Link]("Program continues normally...");
}
}
Output:
text
Try block started
Caught ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
Finally block always executes
Cleaning up resources...
Result: 1
Program continues normally...
Key Points:
Multiple catch blocks can handle different exceptions
Order of catch blocks matters (specific to general)
finally block executes even if exception occurs or not
finally doesn't execute if [Link](0) is called
3. Write a Program to accept password from user and throw
'Authentication failure' exception if password is incorrect.
java
import [Link];
// Custom Exception class
class AuthenticationFailureException extends Exception {
public AuthenticationFailureException(String message) {
super(message);
}
}
public class PasswordAuthentication {
// Method to validate password
public static void validatePassword(String inputPassword)
throws AuthenticationFailureException {
// Correct password (in real scenario, this would be hashed and stored in DB)
String correctPassword = "Secure@123";
if () {
throw new AuthenticationFailureException(
"Incorrect password! Authentication failed.");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("=== PASSWORD AUTHENTICATION SYSTEM ===");
[Link]("Enter your password: ");
String userPassword = [Link]();
try {
// Validate the password
validatePassword(userPassword);
[Link]("Authentication successful! Welcome.");
} catch (AuthenticationFailureException e) {
// Handle authentication failure
[Link]("ERROR: " + [Link]());
[Link]("Please try again with correct credentials.");
} finally {
// Cleanup
[Link]();
[Link]("Session terminated.");
}
}
}
Alternative version with multiple attempts:
java
import [Link];
class AuthenticationFailureException extends Exception {
public AuthenticationFailureException(String message) {
super(message);
}
}
public class EnhancedPasswordAuth {
private static final String CORRECT_PASSWORD = "Java@2024";
private static final int MAX_ATTEMPTS = 3;
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int attempts = 0;
boolean authenticated = false;
[Link]("=== ENHANCED AUTHENTICATION SYSTEM ===");
while (attempts < MAX_ATTEMPTS && !authenticated) {
attempts++;
[Link]("\nAttempt %d of %d\n", attempts, MAX_ATTEMPTS);
[Link]("Enter password: ");
String password = [Link]();
try {
authenticate(password);
authenticated = true;
[Link]("\n✅ Authentication successful!");
[Link]("Access granted to the system.");
} catch (AuthenticationFailureException e) {
[Link]("❌ " + [Link]());
if (attempts < MAX_ATTEMPTS) {
[Link]("Please try again.");
} else {
[Link]("\n🚨 Maximum attempts reached!");
[Link]("Account locked. Contact administrator.");
}
}
}
[Link]();
if (authenticated) {
[Link]("\nWelcome to the system!");
}
}
public static void authenticate(String password)
throws AuthenticationFailureException {
// Check if password is empty
if (password == null || [Link]().isEmpty()) {
throw new AuthenticationFailureException("Password cannot be empty!");
}
// Check if password matches
if () {
throw new AuthenticationFailureException("Incorrect password!");
}
}
}
Sample Output 1 (Successful authentication):
text
=== PASSWORD AUTHENTICATION SYSTEM ===
Enter your password: Secure@123
Authentication successful! Welcome.
Session terminated.
Sample Output 2 (Failed authentication):
text
=== PASSWORD AUTHENTICATION SYSTEM ===
Enter your password: wrongpass
ERROR: Incorrect password! Authentication failed.
Please try again with correct credentials.
Session terminated.
Sample Output 3 (Enhanced version - multiple attempts):
text
=== ENHANCED AUTHENTICATION SYSTEM ===
Attempt 1 of 3
Enter password: test123
❌ Incorrect password!
Please try again.
Attempt 2 of 3
Enter password:
❌ Password cannot be empty!
Please try again.
Attempt 3 of 3
Enter password: Java@2024
✅ Authentication successful!
Access granted to the system.
W l t th t !