Module 1
Here are the answers to your Java-related questions:
1. Explain different lexical issues in JAVA
Lexical issues refer to the basic building blocks of a Java program and how they are
interpreted by the compiler. Key lexical issues include:
• Identifiers: Names used for variables, methods, classes, etc. Must begin with a letter,
_, or $.
• Keywords: Reserved words like class, public, static, if, etc.
• Literals: Constants like 10, 'A', "Hello", true.
• Operators: Symbols used for operations like +, -, *, ==, etc.
• Separators: Characters like (), {}, ;, , used to separate statements and blocks.
• Comments: Used to document code. // for single-line and /*...*/ for multi-line.
• White spaces: Used to separate tokens; ignored by the compiler but useful for
readability.
2. Define Array. Write a Java program to implement the addition of two matrices.
Definition: An array is a data structure that stores elements of the same data type in
contiguous memory locations.
Program for Addition of Two Matrices:
public class MatrixAddition {
public static void main(String[] args) {
int[][] a = {
{1, 2, 3},
{4, 5, 6}
};
int[][] b = {
{7, 8, 9},
{1, 2, 3}
};
int[][] sum = new int[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = a[i][j] + b[i][j];
[Link](sum[i][j] + " ");
[Link]();
3. Explain the following operations with examples
(i) << — Left Shift Operator
Shifts bits to the left, filling with 0s. Equivalent to multiplying by 2ⁿ.
Example:
int a = 5; // binary: 00000101
int result = a << 1; // binary: 00001010 => 10
(ii) >> — Signed Right Shift Operator
Shifts bits to the right, preserving the sign (sign extension).
Example:
int a = -8; // binary: 11111000
int result = a >> 2; // binary: 11111110 => -2
(iii) >>> — Unsigned Right Shift Operator
Shifts bits to the right, filling with 0s.
Example:
int a = -8;
int result = a >>> 2; // Will result in a large positive number
4. Explain object-oriented principles
The four main object-oriented principles are:
• Encapsulation: Wrapping data and methods into a single unit (class). Example: using
private variables and public methods.
• Inheritance: Acquiring properties of one class in another. Example: class B extends A.
• Polymorphism: One interface, many implementations. Example: method
overloading/overriding.
• Abstraction: Hiding internal details and showing only functionality. Example: using
interfaces or abstract classes.
5. Write a Java program to sort the elements using a for loop.
public class SortArray {
public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 3};
// Bubble sort using for loop
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
// Print sorted array
for (int num : arr) {
[Link](num + " ");
6. Explain different types of if statements in JAVA
a) Simple if
if (a > b) {
[Link]("a is greater");
b) if-else
if (a > b) {
[Link]("a is greater");
} else {
[Link]("b is greater or equal");
c) if-else-if ladder
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 80) {
[Link]("Grade B");
} else {
[Link]("Grade C or below");
d) Nested if
if (a > 0) {
if (a % 2 == 0) {
[Link]("Positive even number");
Let me know if you’d like these as a PDF or formatted notes!
Module 2
Here's a simple explanation for each of your Java questions:
1. What are constructors? Explain two types with an example program.
A constructor is a special method in Java used to initialize objects. It has the same name as
the class and doesn't have a return type.
Types of Constructors:
1. Default Constructor – No parameters.
2. Parameterized Constructor – Takes parameters to initialize values.
Example:
class Student {
String name;
int age;
// Default Constructor
Student() {
name = "Unknown";
age = 0;
// Parameterized Constructor
Student(String n, int a) {
name = n;
age = a;
void display() {
[Link](name + " is " + age + " years old");
public static void main(String[] args) {
Student s1 = new Student(); // Default
Student s2 = new Student("John", 20); // Parameterized
[Link]();
[Link]();
2. Define recursion. Write a recursive program to find nth Fibonacci number.
Recursion is when a method calls itself to solve smaller parts of a problem.
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8...
class Fibonacci {
static int fib(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fib(n - 1) + fib(n - 2);
public static void main(String[] args) {
int n = 7;
[Link]("Fibonacci number at position " + n + " is " + fib(n));
3. Explain the various access specifiers in Java.
Access specifiers control who can access a class, variable, or method.
Specifier Where it can be accessed from
public Anywhere
private Only within the same class
protected Same class, same package, and child classes
(default) Only within the same package
Example:
public class Example {
public int a = 10; // Public: accessible everywhere
private int b = 20; // Private: accessible only in this class
protected int c = 30; // Protected: accessible in subclass or same package
int d = 40; // Default: same package
4. Explain call by value and call by reference with an example.
In Java, call by value means copying the value of the variable. Java does not support true
call by reference, but objects can be modified via references.
Example:
class Test {
int num = 10;
void changeValue(int x) {
x = 50; // Does not change original
void changeObject(Test obj) {
[Link] = 100; // Changes the original object's value
}
public static void main(String[] args) {
Test t = new Test();
int a = 20;
[Link](a); // Call by value
[Link]("a = " + a); // Still 20
[Link](t); // Object reference
[Link]("num = " + [Link]); // Changed to 100
5. Write a program to perform Stack operations using class and methods.
class Stack {
int[] arr = new int[5];
int top = -1;
void push(int item) {
if (top < [Link] - 1) {
arr[++top] = item;
} else {
[Link]("Stack Overflow");
void pop() {
if (top >= 0) {
[Link]("Popped: " + arr[top--]);
} else {
[Link]("Stack Underflow");
void display() {
[Link]("Stack elements:");
for (int i = 0; i <= top; i++) {
[Link](arr[i]);
public static void main(String[] args) {
Stack s = new Stack();
[Link](10);
[Link](20);
[Link]();
[Link]();
[Link]();
6. Explain the use of this in Java with an example.
The this keyword is used to refer to the current object. It's helpful when variable names are
the same as parameters.
Example:
class Person {
String name;
Person(String name) {
[Link] = name; // '[Link]' refers to the instance variable
void display() {
[Link]("Name is " + [Link]);
public static void main(String[] args) {
Person p = new Person("Alice");
[Link]();
Let me know if you’d like these compiled into a PDF or explained with diagrams!
Module 3
Sure! Here's a simple and clear explanation of each question with example Java programs
where needed:
1. Java Program for Multilevel Inheritance (3 levels)
Multilevel inheritance means a class inherits from another class, which in turn inherits from
a third class.
class Animal {
void eat() {
[Link]("Animal eats food");
class Dog extends Animal {
void bark() {
[Link]("Dog barks");
class Puppy extends Dog {
void weep() {
[Link]("Puppy weeps");
public class MultilevelInheritance {
public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
2. Interface for Achieving Multiple Inheritance in Java
Java does not support multiple inheritance with classes (to avoid ambiguity), but it
supports multiple inheritance through interfaces.
interface A {
void displayA();
interface B {
void displayB();
class C implements A, B {
public void displayA() {
[Link]("Display from Interface A");
public void displayB() {
[Link]("Display from Interface B");
public class MultipleInheritanceDemo {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
Explanation in simple words:
Interfaces act like blueprints. A class can take multiple blueprints and build on them.
3. Method Overriding in Java
Method overriding happens when a subclass provides its own version of a method already
defined in its superclass.
class Animal {
void sound() {
[Link]("Animal makes a sound");
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
public class MethodOverridingExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Calls overridden method
}
4. Single-Level Inheritance
Single-level inheritance is when one class inherits directly from another class.
class Vehicle {
void start() {
[Link]("Vehicle starts");
class Car extends Vehicle {
void drive() {
[Link]("Car is driving");
public class SingleLevelInheritance {
public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link]();
5. Importance of super Keyword in Inheritance
super is used to:
• Access the parent class constructor
• Call the parent class method
• Access parent class variables
class Parent {
void display() {
[Link]("Parent class method");
class Child extends Parent {
void display() {
[Link](); // Call parent class method
[Link]("Child class method");
public class SuperKeywordExample {
public static void main(String[] args) {
Child c = new Child();
[Link]();
6. Abstract Class and Abstract Method
• Abstract class: A class that cannot be instantiated (can't create objects).
• Abstract method: A method without a body; it must be implemented in a subclass.
abstract class Shape {
abstract void draw(); // Abstract method
}
class Circle extends Shape {
void draw() {
[Link]("Drawing Circle");
public class AbstractExample {
public static void main(String[] args) {
Shape s = new Circle(); // Upcasting
[Link]();
Simple Explanation:
Abstract class is like a partial design. The complete details must be given by the subclass.
Would you like a PDF or summary of these answers too?
Module 4
Here are simple explanations and example programs for your Java questions related to
packages and exception handling:
1. Define package. Steps to create a user-defined package with an example
Definition:
A package is a group of related classes and interfaces in Java. It helps organize your code and
avoid name conflicts.
Steps to create a user-defined package:
1. Create a package using the package keyword.
2. Save the class file in a folder with the same name as the package.
3. Compile the file using javac -d . [Link] to create a proper directory
structure.
4. Use the package by importing it in another class using import.
Example:
File: MyPackage/[Link]
package MyPackage; // Step 1
public class Hello {
public void greet() {
[Link]("Hello from MyPackage!");
File: [Link]
import [Link]; // Step 4
public class TestPackage {
public static void main(String[] args) {
Hello obj = new Hello();
[Link]();
Compile commands:
javac -d . [Link] // Inside MyPackage folder
javac [Link] // From the root folder
2. Program to throw and handle IllegalAccessException
public class IllegalAccessDemo {
public static void throwException() throws IllegalAccessException {
throw new IllegalAccessException("Access not allowed!");
public static void main(String[] args) {
try {
throwException();
} catch (IllegalAccessException e) {
[Link]("Caught Exception: " + e);
3. Define exception and key terms in exception handling
Exception:
An exception is an error that occurs at runtime, which disrupts the normal flow of the
program.
Key Terms:
• try: Block where risky code is written.
• catch: Handles the exception.
• throw: Used to manually throw an exception.
• throws: Declares exceptions that a method might throw.
• finally: Executes code whether an exception occurs or not.
4. Importing packages in Java with example
Concept:
To use classes from another package, we use the import statement.
Example:
File: tools/[Link]
package tools;
public class MathUtil {
public static int square(int x) {
return x * x;
File: [Link]
import [Link];
public class UseImport {
public static void main(String[] args) {
[Link]("Square of 5: " + [Link](5));
5. Creating a custom exception class
Explanation:
You can create your own exception by extending Exception or RuntimeException.
Example:
class MyException extends Exception {
public MyException(String message) {
super(message);
public class CustomExceptionDemo {
public static void main(String[] args) {
try {
throw new MyException("This is a user-defined exception");
} catch (MyException e) {
[Link]("Caught: " + [Link]());
6. Nested try block example
Explanation:
You can put a try block inside another try block — helpful when handling multiple levels of
risky code.
Example:
public class NestedTryDemo {
public static void main(String[] args) {
try {
[Link]("Outer try block");
try {
int a = 5 / 0; // Will cause ArithmeticException
} catch (ArithmeticException e) {
[Link]("Inner catch: " + e);
int[] arr = new int[2];
arr[3] = 10; // Will cause ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch: " + e);
Let me know if you want this content in a document or formatted in a table for easy revision.
Module 5
Here’s a simple explanation of each concept along with examples:
1. What is a Thread? How to Create Threads in Java
Thread:
A thread is a lightweight subprocess, the smallest unit of processing. Java allows us to run
multiple threads in a program to perform multiple tasks at once (concurrently).
Ways to Create Threads:
(i) Extending the Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread running using Thread class");
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
(ii) Implementing the Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread running using Runnable interface");
}
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
2. Why Synchronization? How it's implemented in Java
Need for Synchronization:
When multiple threads access shared resources (like variables or methods), data
inconsistency may happen. Synchronization ensures only one thread accesses a resource at
a time.
Example:
class Counter {
int count = 0;
synchronized void increment() {
count++;
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) [Link]();
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) [Link]();
});
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Final count: " + [Link]);
3. values() and valueOf() Methods in Enums
Enum: A special class to define a group of constants.
• values(): returns all constants in the enum.
• valueOf(String name): returns the constant with the specified name.
Example:
enum Color {
RED, GREEN, BLUE;
public class Main {
public static void main(String[] args) {
// values()
for (Color c : [Link]()) {
[Link](c);
}
// valueOf()
Color myColor = [Link]("RED");
[Link]("Selected: " + myColor);
4. What is Multithreading? Java Program for Multiple Threads
Multithreading:
Running two or more threads concurrently (at the same time).
Example Program:
class MyThread extends Thread {
public void run() {
[Link]([Link]().getName() + " is running");
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link]();
[Link]();
5. Inter-thread Communication in Java (wait, notify, notifyAll)
Used when one thread needs to wait for another to complete some task.
Example:
class Shared {
boolean flag = false;
synchronized void produce() throws InterruptedException {
while (flag) wait();
[Link]("Produced");
flag = true;
notify();
synchronized void consume() throws InterruptedException {
while (!flag) wait();
[Link]("Consumed");
flag = false;
notify();
public class Main {
public static void main(String[] args) {
Shared s = new Shared();
Thread producer = new Thread(() -> {
try {
[Link]();
} catch (Exception e) {}
});
Thread consumer = new Thread(() -> {
try {
[Link]();
} catch (Exception e) {}
});
[Link]();
[Link]();
6. Auto-boxing and Unboxing in Expressions
Auto-boxing: Automatic conversion of primitive type to object (e.g., int to Integer).
Unboxing: Conversion from object to primitive (e.g., Integer to int).
Example:
public class Main {
public static void main(String[] args) {
int a = 10;
Integer obj = a; // auto-boxing
int b = obj; // unboxing
Integer sum = a + obj; // auto-boxing and unboxing in expression
[Link]("Sum: " + sum);
}
Let me know if you'd like the same in even simpler terms or local language explanation!