0% found this document useful (0 votes)
34 views70 pages

Java Interview Questions and Concepts

The document provides an overview of Java, including its features, versions, and differences from other programming languages. It covers the Java programming environment, basic syntax, control structures, and various programming tasks. Additionally, it includes links to resources for Java interview questions and coding exercises.

Uploaded by

naveenadhi014
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)
34 views70 pages

Java Interview Questions and Concepts

The document provides an overview of Java, including its features, versions, and differences from other programming languages. It covers the Java programming environment, basic syntax, control structures, and various programming tasks. Additionally, it includes links to resources for Java interview questions and coding exercises.

Uploaded by

naveenadhi014
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

Java Interview theory questions

[Link]

[Link]

Java interview coding questions


[Link]

Module 1: Introduction to Java

1. Java: Why? What? How? When? Where?

Why Java?

●​ Platform independence: Write Once, Run Anywhere (WORA).


●​ Robust and secure: Built-in security features and strong memory management.
●​ Versatile: Supports applications like web, mobile, desktop, and enterprise solutions.
●​ Large community and extensive libraries: Faster development and problem-solving.

What is Java?

●​ Java is a high-level, object-oriented programming language developed by Sun


Microsystems (now owned by Oracle).
●​ It is designed to be portable, secure, and efficient.

How Java Works?

1.​ Write: Source code written in .java files.


2.​ Compile: The Java Compiler (javac) converts code into bytecode (.class files).
3.​ Run: The Java Virtual Machine (JVM) executes bytecode, making it
platform-independent.

When to Use Java?

●​ Building enterprise-grade applications (e.g., banking systems).


●​ Developing cross-platform software.
●​ Creating Android apps (Java is the foundation of Android development).

Where is Java Used?

●​ Web Development: Back-end systems using frameworks like Spring.


●​ Mobile Applications: Android apps.
●​ Big Data: Tools like Hadoop use Java.
●​ Gaming: High-performance games and simulations.
●​ Embedded Systems: Devices like smart TVs, routers, etc.

2. Different Java Versions

Timeline of Java Versions

●​ JDK 1.0 (1996): Initial release with basic features like applets and AWT.
●​ JDK 1.2 (1998): Introduction of Swing, Collections Framework.
●​ JDK 5.0 (2004): Added generics, enhanced for loop, and annotations.
●​ Java SE 8 (2014): Lambda expressions, Stream API, and new date/time API.
●​ Java SE 11 (2018): Long-Term Support (LTS) version with modularization
(introduced in Java 9).
●​ Java SE 17 (2021): Latest LTS version with features like sealed classes and pattern
matching.

Key Features in Modern Versions

●​ Java 8: Functional programming, streams for data processing.


●​ Java 9: Module system (Project Jigsaw) for scalable application design.
●​ Java 11: HTTP client API, local variable syntax for Lambda parameters.
●​ Java 17: Sealed classes, pattern matching for switch.

3. How Java is Different from Other Technologies

Comparison with Other Programming Languages

Feature Java C++ Python C#

Platform Platform-indepe Platform-depend Platform-indepen Windows-focused


ndent (via JVM) ent (compiled) dent (now cross-platform
(intperpreted) with .NET Core)
Memory Automatic Manual Automatic Automatic (Garbage
Management (Garbage Collection)
Collection)

Syntax Strict and Complex and Simple and Similar to Java with
verbose less strict concise .NET integration

Usage General-purpose System-level Rapid Enterprise apps with


, enterprise apps programming development, .NET ecosystem
scripting

Java Advantages Over Other Technologies

●​ Compared to C++:
○​ No explicit memory management.
○​ Supports multithreading natively.
○​ Fully object-oriented (no pointers).
●​ Compared to Python:
○​ Better performance (Java is compiled into bytecode, whereas Python is
interpreted).
○​ Stronger typing system ensures fewer runtime errors.
●​ Compared to C#:
○​ Cross-platform support from the beginning.
○​ Broader application areas, including Android development.

Why Developers Prefer Java?

●​ Mature ecosystem with extensive tools like IntelliJ IDEA and Eclipse.
●​ Strong support for enterprise-level frameworks (e.g., Spring, Hibernate).
●​ Proven track record of reliability and scalability.

Reading materials
[Link]

[Link]

[Link]
Module 2: Introduction to Java programming environment

Install jdk

[Link]
html

Download Spring tool suite IDE

[Link]
Verify Installation:

●​ Run the following commands in the terminal or command prompt:

java -version
javac -version

2. Main Class and Main Method

Main Class

●​ Every Java application starts execution from a main class.


●​ The main class is typically named after the file and follows proper naming
conventions.

Main Method

●​ The entry point of every Java application is the main method.

Syntax:

java
public static void main(String[] args) {
​ // Code to execute
}

Explanation of Components:

●​ public: The method is accessible from anywhere.


●​ static: Allows the JVM to call the method without creating an object.
●​ void: Does not return any value.
●​ String[] args: Accepts command-line arguments as an array of strings.

3. [Link]

●​ Definition: [Link] is used to print output to the console.


●​ Syntax:

[Link]("Your message here");

Variations:

1.​ Print without a newline:

[Link]("This will not add a new line.");


4. A Simple Java Program

Here’s an example program:

Code:

public class HelloWorld {


​ public static void main(String[] args) {
​ [Link]("Hello, World!");
​ [Link]("This is my first Java program.");
​ }
}

5. Naming Conventions

Java follows specific naming conventions for readability and maintainability:

Classes

●​ Use PascalCase (each word starts with a capital letter).


●​ Example: HelloWorld, StudentDetails.

Methods

●​ Use camelCase (first word lowercase, subsequent words capitalized).


●​ Example: calculateSum, printDetails.

Variables

●​ Use camelCase.
●​ Example: studentName, totalMarks.

Constants

●​ Use uppercase letters with underscores (_) separating words.


●​ Example: PI, MAX_LIMIT.

Packages

●​ Use all lowercase, typically representing the domain name in reverse.


●​ Example: [Link].

6. Features of Java

Java offers several key features that make it powerful and versatile:
1. Platform Independence

●​ Code written in Java can run on any platform with a JVM.

2. Object-Oriented

●​ Everything in Java revolves around objects and classes (except for primitive data
types).

3. Simple

●​ Java is easy to learn and understand with a clear syntax.

4. Secure

●​ Features like bytecode verification and no use of pointers ensure security.

5. Multithreaded

●​ Java supports concurrent execution of code using threads.

6. Robust

●​ Strong error handling and garbage collection prevent crashes and memory leaks.

7. High Performance

●​ Bytecode execution and Just-In-Time (JIT) compiler make Java efficient.

8. Distributed

●​ Java provides tools like RMI and CORBA for distributed computing.

Daily Task

1. ​ Installation Task:

○​ Install Java on their system, set up the PATH, and verify using java
-version.

2. ​ Coding Task 1:

○​ Write and run a simple Java program that prints their name, favorite color, and
a fun fact about Java.
3. ​ Coding Task 2:

○​ Write a Java program using [Link] and [Link] to


demonstrate the difference between them.

Module 3: Fundamentals of java programming

Comments

●​ Definition: Comments are non-executable statements that enhance code readability


and help developers understand the code.
●​ Types:
1.​ Single-line Comment: Starts with //

2. // This is a single-line comment

3.​ Multi-line Comment: Enclosed between /* and */

4. /*
5. This is a multi-line comment
6. spanning multiple lines
7. */

8.​ Documentation Comment: Starts with /** and is used to generate


documentation using Javadoc.

9. /**
10. * This is a documentation comment
11. */

Statements

●​ Definition: A statement is a single line of code that performs an action.


●​ Types:
1.​ Declaration Statement: Declares a variable.

int a;

2.​ Expression Statement: Evaluates an expression.


a = 5;

3.​ Control Flow Statement: Controls the flow of execution.

if (a > 0) {
​ [Link]("Positive number");
}

Identifiers

●​ Definition: Names given to variables, methods, classes, or other program elements.


●​ Rules:
1.​ Must begin with a letter, $, or _.
2.​ Cannot use Java keywords.
3.​ Case-sensitive.
4.​ No special characters except $ and _.
●​ Example:

· ​ int age;
· ​ String $name;
· ​ double _salary;

Keywords

●​ Definition: Reserved words with predefined meanings in Java.


●​ Examples:
○​ Data Type Keywords: int, float, boolean
○​ Control Keywords: if, else, switch
○​ Looping Keywords: for, while, do
○​ Others: class, interface, void, return

Literals

●​ Definition: Constant values directly used in the program.


●​ Types:
1.​ Integer Literals: 10, 0b1010, 0xA
2.​ Floating-point Literals: 3.14, 2.7e10
3.​ Character Literals: 'A', '\n'
4.​ String Literals: "Hello"
5.​ Boolean Literals: true, false
Primitive Data Types and Their Range

Data Type Size Range

byte 1 byte -128 to 127

short 2 bytes -32,768 to 32,767

int 4 bytes -2,147,483,648 to 2,147,483,647

long 8 bytes -9,223,372,036,854,775,808 to ...

float 4 bytes ~±3.4e−38 to ±3.4e38

double 8 bytes ~±1.7e−308 to ±1.7e308

char 2 bytes 0 to 65,535 (Unicode characters)

boolean 1 bit true or false

Reference (User-defined) Data Type


●​ Definition: Data types created by the user to represent objects or classes.
●​ Examples:
○​ Classes: class Employee {}
○​ Interfaces: interface Printable {}
○​ Arrays: int[] arr = new int[10];

Variables

●​ Definition: Containers for storing data values.


●​ Types:
1.​ Primitive Variables: Stores primitive data types.

2. int age = 25;

3.​ Reference Variables: Stores addresses of objects.

4. String name = "John";

Type Casting and Default Values

●​ Type Casting:
1.​ Implicit Casting: Smaller type to larger type (automatic).

2. int num = 10;


3. double d = num; // Implicit casting

4.​ Explicit Casting: Larger type to smaller type (manual).

5. double d = 10.5;
6. int num = (int) d; // Explicit casting

●​ Default Values:
○​ For primitive types: int = 0, boolean = false, char = \u0000.
○​ For reference types: null.

Operators

●​ Definition: Symbols that perform operations on operands.


●​ Types:
1.​ Arithmetic Operators: +, -, *, /, %
2.​ Relational Operators: >, <, ==, !=, >=, <=
3.​ Logical Operators: &&, ||, !
Program/Interview Questions

1. Write a program to check if a number is even or odd.

public class EvenOdd {


public static void main(String[] args) {
​ int num = 10;
​ if (num % 2 == 0) {
​ [Link]("Even number");
​ } else {
​ [Link]("Odd number");
​}
​ }
}

2. ​ What is the default value of char in Java?

o The default value is \u0000 (null character).

3. ​ Difference between == and .equals()?

o == compares reference equality for objects.

o .equals() compares the actual content of the objects.


Write a program to swap two numbers without using a third variable.

public class SwapNumbers {


​ public static void main(String[] args) {
​ int a = 5, b = 10;
​ a = a + b; // a = 15
​ b = a - b; // b = 5
​ a = a - b; // a = 10
​ [Link]("a = " + a + ", b = " + b);
​ }
}

Module 4: Control Structures

1. Working with Control Structures

●​ Definition: Control structures are used to alter the flow of program execution based
on conditions or loops.
●​ Purpose: To enable decision-making (conditional execution) and repetition (loops),
allowing the program to handle various scenarios efficiently.

2. Types of Control Structures

Control structures in Java are categorized into:

●​ Decision Control Structures (used for making decisions based on conditions).


●​ Repetition Control Structures (used for looping or repeating a block of code).
●​ Jump Control Structures (like break, continue, return).

3. Decision Control Structures

· Definition: Decision control structures enable the program to choose between


different paths of execution based on certain conditions.

1. ​ if Statement

■​ Syntax:

java

if (condition) {
​ // Code to execute if condition is true
}

■​ Explanation: Executes a block of code only if the specified condition is


true.
■​ Example:

java
int x = 10;
if (x > 5) {
​ [Link]("x is greater than 5");
}

2. ​ if-else Statement

■​ Syntax:

java

if (condition) {
​ // Code to execute if condition is true
} else {
​ // Code to execute if condition is false
}

■​ Explanation: Executes one block of code if the condition is true, and


another block if it is false.
■​ Example:

java

int x = 4;
if (x > 5) {
​ [Link]("x is greater than 5");
} else {
​ [Link]("x is less than or equal to 5");
}

3. ​ if-else if-else Statement

■​ Syntax:

java

if (condition1) {
​ // Code to execute if condition1 is true
} else if (condition2) {
​ // Code to execute if condition2 is true
} else {
​ // Code to execute if no conditions are true
}

■​ Explanation: Allows you to test multiple conditions and execute the first
block where the condition is true.
■​ Example:
java

int x = 10;
if (x > 20) {
​ [Link]("x is greater than 20");
} else if (x == 10) {
​ [Link]("x is equal to 10");
} else {
​ [Link]("x is less than 10");
}

4. ​ switch-case Statement

■​ Syntax:

java

switch (variable) {
​ case value1:
​ // Code to execute if variable == value1
​ break;
​ case value2:
​ // Code to execute if variable == value2
​ break;
​ default:
​ // Code to execute if no case matches
​ break;
}

■​ Explanation: Used to check a variable against multiple possible values.


If a match is found, the corresponding block of code is executed.
■​ Example:

java

int day = 3;
switch (day) {
​ case 1:
​ [Link]("Monday");
​ break;
​ case 2:
​ [Link]("Tuesday");
​ break;
​ case 3:
​ [Link]("Wednesday");
​ break;
​ default:
​ [Link]("Invalid day");
​ break;
}

4. Repetition Control Structures

· Definition: Repetition control structures are used to repeat a block of code


multiple times based on a condition or until a certain condition is met.

1. ​ for Loop

■​ Syntax:

java

for (initialization; condition; increment/decrement) {


​ // Code to execute repeatedly
}

■​ Explanation: Executes a block of code a specific number of times


based on the initialization, condition, and increment/decrement.
■​ Example:

java

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


​ [Link]("i is: " + i);
}

2. ​ while Loop

■​ Syntax:

java

while (condition) {
​ // Code to execute as long as condition is true
}

■​ Explanation: Executes a block of code repeatedly as long as the


specified condition is true.
■​ Example:

java

int i = 0;
while (i < 5) {
​ [Link]("i is: " + i);
​ i++;
}
3. ​ do-while Loop

■​ Syntax:

java

do {
​ // Code to execute
} while (condition);

■​ Explanation: Executes the code block at least once and then checks
the condition. The loop continues as long as the condition is true.
■​ Example:

java

int i = 0;
do {
​ [Link]("i is: " + i);
​ i++;
} while (i < 5);

5. Program/Interview Questions

●​ Sample Interview Questions:


1.​ Explain the difference between if-else and switch-case.
■​ if-else is used when the condition involves ranges or complex
expressions. switch-case is more efficient when there are multiple
possible values of a single variable to check.
2.​ When would you use a while loop vs. a do-while loop?
■​ Use a while loop when you want to check the condition before
executing the loop body. Use a do-while loop when you want the
body to execute at least once before checking the condition.
3.​ What is the purpose of the break and continue statements in loops?
■​ break exits the loop immediately, while continue skips the current
iteration and moves to the next iteration of the loop.
4.​ What will happen if you forget the break statement in a switch-case?
■​ If you forget break, the code will "fall through" to the next case,
executing the code in that case even if the condition does not match.
5.​ How do for, while, and do-while loops differ in terms of condition evaluation?
■​ In a for loop, the condition is checked before each iteration, in a
while loop, the condition is also checked before each iteration, but in
a do-while loop, the condition is checked after the first iteration.
Daily task

Task: Temperature Category Program

Objective: Write a Java program that takes an integer temperature as input and classifies it
into one of the following categories based on the value:

1.​ Cold: Temperature below 0°C.


2.​ Cool: Temperature from 0°C to 15°C.
3.​ Warm: Temperature from 16°C to 30°C.
4.​ Hot: Temperature above 30°C.

Task: Multiplication Table Generator

Objective: Write a Java program that generates and prints the multiplication table of a
number entered by the user.

Requirements:

1.​ Prompt the user to enter an integer number for which they want to generate the
multiplication table.
2.​ Use a for loop to print the multiplication table from 1 to 10.
3.​ Format the output such that each line shows the result of multiplying the number by a
value from 1 to 10.
4.​ (Bonus) Allow the user to enter a new number for generating a different multiplication
table without restarting the program.

Example Output:

Input:​
Enter a number: 5

Output:

css

Multiplication Table for 5:

5 x 1 = 5

5 x 2 = 10
5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

Module 5: Input Fundamentals and Datatypes in Java

1. Java Program Inputs from Keyboard

●​ Definition: Java provides ways to take input from the user via the keyboard.
●​ Purpose: User input is essential for dynamic programs that require data at runtime.

2. Methods of Keyboard Inputs

Java provides different classes for capturing input from the user:

●​ Scanner Class: A simple, commonly used method for reading input.


●​ BufferedReader Class: A more advanced class for reading input, often used when
reading large chunks of data.

3. Scanner Class

· Overview: Scanner is a built-in class in Java used to get user input. It provides
methods for reading different data types, such as nextInt(), nextLine(),
nextDouble(), etc.

· Example:

java
import [Link];

public class Example {


​ public static void main(String[] args) {
​ Scanner sc = new Scanner([Link]);
​ [Link]("Enter an integer: ");
​ int num = [Link]();
​ [Link]("You entered: " + num);
​ }
}

· Common Methods:

○​ nextInt(): Reads an integer.


○​ nextLine(): Reads a string.
○​ nextDouble(): Reads a double.
○​ nextBoolean(): Reads a boolean.

4. BufferedReader Class

· Overview: BufferedReader reads text from a character-based input stream. It is


more efficient for large inputs or when you need to read multiple lines of text.

· Example:

java

import [Link].*;

public class Example {


​ public static void main(String[] args) throws IOException {
​ BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
​ [Link]("Enter your name: ");
​ String name = [Link]();
​ [Link]("Hello, " + name);
​ }
}

· Key Methods:

○​ readLine(): Reads a line of text.

5. Problem Solving
●​ Focus: Practice solving problems using user input in Java. Problems can range from
simple arithmetic to complex algorithms requiring data from the user.
●​ Important Concept: Always validate inputs (e.g., ensure the input is of the correct
type) to avoid errors during execution.

6. Java Array

●​ What is an Array?
○​ An Array is a data structure in Java that stores a fixed-size sequence of
elements of the same type.
○​ Purpose: To store multiple values in a single variable instead of declaring
individual variables for each value.

7. Array Declaration in Java vs C and C++

· Java:

○​ Syntax for array declaration:

java

int[] arr = new int[5]; // Array of integers with 5 elements

○​ Alternatively:

java

int arr[] = new int[5];

· C/C++:

○​ Syntax for array declaration:

int arr[5]; // Array of integers with 5 elements

· Key Differences:

○​ Java: Arrays are objects, so they must be created using the new keyword or
initialized directly with values.
○​ C/C++: Arrays are not objects, and memory is allocated statically (or
dynamically with pointers).
8. Instantiation of an Array

· Definition: Instantiating an array means creating an instance of an array


(allocating memory for the array elements).

· Example:

java

int[] arr = new int[10]; // Creates an array of 10 integers.

○​ Alternatively, you can initialize an array with values directly:

java

int[] arr = {1, 2, 3, 4, 5}; // Instantiates and initializes the array.

9. String vs Character Array

· String:

○​ A String is a sequence of characters (immutable in Java).


○​ Example:

java

String str = "Hello, World!";

· Character Array:

○​ A character array is an array of characters (char[]), which can be modified.


○​ Example:

java

char[] arr = {'H', 'e', 'l', 'l', 'o'};

· Differences:

○​ Immutability: Strings are immutable, while character arrays are mutable.


○​ Usage: Strings are more commonly used for textual data, while character
arrays are often used for more performance-critical or low-level operations.

10. Accessing Array Elements

●​ Accessing Elements by Index:


○​ Array elements are accessed using indices. Indices in Java arrays start at 0.
○​ Example:

java

int[] arr = {1, 2, 3, 4, 5};


[Link](arr[2]); // Output: 3 (the third element)

11. Elements, Default Value, For-each Loop (Enhanced For Loop),


Varargs

· Default Values in Arrays:

○​ For numeric types (int, double, etc.), the default value is 0.


○​ For boolean arrays, the default value is false.
○​ For object arrays, the default value is null.

· For-each Loop (Enhanced For Loop):

○​ Used to iterate over arrays easily.


○​ Example:

java

int[] arr = {1, 2, 3, 4, 5};


for (int num : arr) {
​ [Link](num); // Output: 1 2 3 4 5
}

· Varargs (Variable Arguments):

○​ Allows a method to accept a variable number of arguments.


○​ Example:

java

public void printNumbers(int... numbers) {


​ for (int num : numbers) {
​ [Link](num);
​ }
}

12. Length of an Array & Array Index Out of Bounds Exception

· Length of an Array:

○​ The length of an array can be accessed using the .length attribute.


○​ Example:

java

int[] arr = {1, 2, 3, 4, 5};


[Link]([Link]); // Output: 5

· Array Index Out of Bounds Exception:

○​ Occurs when you try to access an array index that is outside the valid range
(0 to length-1).
○​ Example:

java

int[] arr = {1, 2, 3};


[Link](arr[5]); // ArrayIndexOutOfBoundsException

13. Increasing, Decreasing the Size, and of an Array

· Increasing or Decreasing the Size:

○​ Arrays in Java have a fixed size. You cannot directly increase or decrease the
size of an array after it’s created.
○​ Workaround:
■​ Use an ArrayList if you need dynamic resizing.
■​ If you need to resize an array, create a new array with the desired size
and elements.
■​ Example:

java

int[] arr = {1, 2, 3};


arr = [Link](arr, 5); // Increases the size to 5

· ing an Array:

○​ Use [Link](), [Link](), or a manual loop to an array.


○​ Example:

java

int[] arr1 = {1, 2, 3};


int[] arr2 = [Link](arr1, [Link]);

14. Multi-Dimensional Arrays


· Definition: An array of arrays, where each element is itself an array.

· Declaration and Initialization:

○​ Syntax:

java

int[][] arr = new int[3][4]; // A 2D array (3 rows, 4 columns)

○​ Example:

java

int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};


[Link](arr[1][2]); // Output: 6

· Iterating Through Multi-Dimensional Arrays:

○​ Example:

java

for (int i = 0; i < [Link]; i++) {


​ for (int j = 0; j < arr[i].length; j++) {
​ [Link](arr[i][j] + " ");
​ }
​ [Link]();
}

Daily task

Task Instructions

1.​ Create a program that does the following:


○​ Takes 5 numbers as input from the user and stores them in an array.
○​ Prints the array elements.
○​ Finds and displays the largest number in the array.
○​ Finds and displays the smallest number in the array.
○​ Calculates and displays the sum of all numbers in the array.
2.​ Requirements:
○​ Use a single-dimensional integer array.
○​ Perform all calculations manually (no built-in functions for min, max,
or sum).
Module 6: Object-Oriented Programming (OOPs Concepts in Deep)

1. Class

●​ Definition: A class in Java is a blueprint or template for creating objects. It defines


properties (fields/variables) and behaviors (methods) that the objects created from
the class will have.
●​ Syntax:

java

class ClassName {
​ // Fields/Properties
​ int age;
​ String name;

​ // Methods/Behaviors
​ void greet() {
​ [Link]("Hello, " + name);
​ }
}

●​ Example:

java

class Person {
​ String name;
​ int age;

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

public class Main {


​ public static void main(String[] args) {
​ Person person1 = new Person();
​ [Link] = "John";
​ [Link] = 25;
​ [Link](); // Output: Name: John, Age: 25
​ }
}

2. Objects

●​ Definition: An object is an instance of a class. It represents a real-world entity and


has its own state (attributes) and behavior (methods).
●​ Creating Objects:
○​ An object is created using the new keyword.
○​ Example:

java

Person person1 = new Person(); // Creating an object of class Person

●​ Objects in Memory: When an object is created, memory is allocated for its instance
variables (attributes) and methods.

3. Inheritance

· Definition: Inheritance is a mechanism in Java by which one class


(child/subclass) can inherit fields and methods from another class
(parent/superclass). It helps in reusability and the creation of hierarchical
relationships.

· Key Concepts:

○​ extends keyword: Used to inherit from a class.


○​ Method Overriding: The subclass can provide its own implementation of a
method from the superclass.

· Syntax:

java

class Parent {
​ void greet() {
​ [Link]("Hello from Parent!");
​ }
}

class Child extends Parent {


​ void greet() {
​ [Link]("Hello from Child!");
​ }
}
public class Main {
​ public static void main(String[] args) {
​ Child child = new Child();
​ [Link](); // Output: Hello from Child!
​ }
}

· Advantages of Inheritance:

○​ Code Reusability.
○​ Hierarchical classification of classes.
○​ Enables polymorphism.

4. Abstraction

· Definition: Abstraction is the concept of hiding the implementation details and


showing only the essential features of an object. This helps in reducing
complexity and focusing on relevant aspects.

· Abstract Class:

○​ An abstract class cannot be instantiated directly and can have both abstract
(without implementation) and non-abstract (with implementation) methods.
○​ Syntax:

java

abstract class Animal {


​ abstract void sound(); // Abstract method

​ void eat() { // Non-abstract method


​ [Link]("This animal eats food.");
​ }
}

class Dog extends Animal {


​ void sound() {
​ [Link]("Bark");
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Animal animal = new Dog();
​ [Link](); // Output: Bark
​ }
}

· Interfaces: An interface is a contract that a class must adhere to. It only contains
method signatures and constants (no implementation). A class that implements
an interface must provide concrete implementations for all methods.

○​ Syntax:

java

interface Animal {
​ void sound(); // Interface method
}

class Dog implements Animal {


​ public void sound() {
​ [Link]("Bark");
​ }
}

5. Encapsulation

●​ Definition: Encapsulation is the concept of wrapping data (variables) and methods


(functions) into a single unit known as a class. It also involves restricting direct
access to some of the object's components by making fields private and providing
public methods (getters and setters) to access and modify them.
●​ Benefits:
○​ Data hiding (protection of data).
○​ Code maintainability and flexibility.
●​ Syntax for Encapsulation:

java

class Person {
​ private String name; // private variable

​ // Getter method
​ public String getName() {
​ return name;
​ }

​ // Setter method
​ public void setName(String name) {
​ [Link] = name;
​ }
}
public class Main {
​ public static void main(String[] args) {
​ Person person = new Person();
​ [Link]("John");
​ [Link]([Link]()); // Output: John
​ }
}

6. Polymorphism

· Definition: Polymorphism is the ability of one object to take many forms. In Java,
it can be achieved through method overloading (compile-time polymorphism) and
method overriding (runtime polymorphism).

1. ​ Method Overloading (Compile-time Polymorphism):

■​ When multiple methods with the same name exist, but with different
parameters (number or type).
■​ Example:

java

class Calculator {
​ int add(int a, int b) {
​ return a + b;
​ }

​ double add(double a, double b) {


​ return a + b;
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Calculator calc = new Calculator();
​ [Link]([Link](2, 3)); ​ // Output: 5
​ [Link]([Link](2.5, 3.5)); // Output: 6.0
​ }
}

2. ​ Method Overriding (Runtime Polymorphism):

■​ When a subclass provides a specific implementation of a method


already defined in its superclass.
■​ Example:

java
class Animal {
​ void sound() {
​ [Link]("Animal makes a sound");
​ }
}

class Dog extends Animal {


​ @Override
​ void sound() {
​ [Link]("Dog barks");
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Animal myDog = new Dog();
​ [Link](); // Output: Dog barks
​ }
}

7. Constructors

●​ Definition: A constructor is a special method in Java used to initialize objects. It is


automatically called when an object is created.
●​ Key Points:
○​ A constructor has the same name as the class.
○​ It doesn’t have a return type.
○​ It can be overloaded (multiple constructors with different parameters).
●​ Types:
1.​ Non parametrised Constructor: A constructor with no arguments.

java

class Person {
​ String name;
​ int age;

​ // Default constructor
​ public Person() {
​ name = "Unknown";
​ age = 0;
​ }
}

2. Parameterized Constructor: A constructor that takes arguments to initialize object


attributes.
java

class Person {
​ String name;
​ int age;

​ // Parameterized constructor
​ public Person(String name, int age) {
​ [Link] = name;
​ [Link] = age;
​ }
}

8. this Keyword and super Keyword

· this Keyword:

○​ Refers to the current object of the class.


○​ It can be used to refer to instance variables, methods, and constructors of the
current class.
○​ Example:

java

class Person {
​ String name;

​ public Person(String name) {


​ [Link] = name; // 'this' refers to the current object's name variable
​ }
}

· super Keyword:

○​ Refers to the superclass (parent class) of the current object.


○​ It can be used to access superclass methods and constructors.
○​ Example:

java

class Animal {
​ void sound() {
​ [Link]("Animal sound");
​ }
}

class Dog extends Animal {


​ void sound() {
​ [Link](); // Calls the superclass method
​ [Link]("Dog barks");
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Dog dog = new Dog();
​ [Link](); // Output: Animal sound, Dog barks
​ }
}

Daily task
Functionalities:

●​ Deposit: Accepts an amount and adds it to the account’s balance.


●​ Withdraw: Accepts an amount, checks if the balance is sufficient,
and deducts if possible.
●​ View Balance: Displays the current account balance.

OOP Principles:

●​ Encapsulation: Use private access modifiers for account properties


and provide public methods to interact with them.
●​ Abstraction: Use methods to hide implementation details of
deposit, withdrawal, and balance checking.
●​ Modularity: Separate functionalities into methods within the class.

Testing:

●​ Add sample accounts and perform operations to validate each


functionality.

Module 7: Command-Line Arguments (Duration: 1 hr)

1. What is a Command-Line Argument?

●​ Definition: Command-line arguments are inputs that are passed to a Java program at
the time of execution, allowing the user to provide input without modifying the code.
●​ Purpose: They are useful for passing configuration parameters, file names, or user
inputs without requiring interaction during runtime.
●​ How They Work:
○​ Command-line arguments are passed to the main() method of a Java class.
○​ They are stored as an array of strings (String[] args).
○​ Example: Running a Java program with arguments from the command line
might look like this:

java MyProgram arg1 arg2 arg3

2. Java Application with Command-Line Arguments

· Syntax:

○​ In Java, the main method accepts a parameter String[] args, which stores
the arguments.
○​ Example:

java

public class CommandLineExample {


​ public static void main(String[] args) {
​ // Check if arguments are passed
​ if ([Link] > 0) {
​ [Link]("Arguments passed: ");
​ for (String arg : args) {
​ [Link](arg);
​ }
​ } else {
​ [Link]("No arguments passed.");
​ }
​ }
}

· Explanation:

○​ When you run this program with arguments, for example:

java CommandLineExample Hello World 123

It will output:

yaml

Arguments passed:
Hello
World
123

○​ Accessing Arguments: You can access the arguments by their index in the args
array:

java

String firstArg = args[0]; // Access first argument

· Important Notes:

○​ Command-line arguments are always passed as strings. You can convert


them to other data types using methods like [Link](),
[Link](), etc.

Module 9: Inner Class (Duration: 1 hr)

1. First View of Inner Class

· Definition: An inner class is a class defined within another class. It has access to
the members (including private members) of the outer class.

· Purpose: Inner classes are used to logically group classes that are only used in
one place, increase readability, and allow access to the outer class’s members.

· Syntax:

java

class OuterClass {
​ int outerVariable = 10;

​ // Inner class
​ class InnerClass {
​ void display() {
​ [Link]("Outer variable: " + outerVariable);
​ }
​ }
}

public class Main {


​ public static void main(String[] args) {
​ OuterClass outer = new OuterClass();
​ [Link] inner = [Link] InnerClass();
​ [Link](); // Output: Outer variable: 10
​ }
}

· Explanation:

○​ The InnerClass is defined inside the OuterClass.


○​ An instance of the InnerClass is created using the syntax [Link]
InnerClass() because it needs an instance of the outer class to access its
members.

2. Outer Class Access

· Accessing Members of Outer Class from Inner Class:

○​ An inner class can directly access the variables and methods of its outer
class, even if they are private.
○​ Example:

java

class Outer {
​ private String message = "Hello from Outer Class";

class Inner {
​ void showMessage() {
​ // Accessing outer class's private member
​ [Link](message);
​ }
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Outer outer = new Outer();
​ [Link] inner = [Link] Inner();
​ [Link](); // Output: Hello from Outer Class
​ }
}

· Access to Outer Class from Inner Class:

○​ An inner class can access all members of the outer class, including private
fields and methods, directly without needing special access methods.
3. Types of Inner Class

Java has four types of inner classes:

1. ​ Non-static Inner Class (Member Inner Class)

○​ Defined inside the outer class and associated with an instance of the outer
class.
○​ Can access all members of the outer class.
○​ Example:

java

class Outer {
​ private String outerMessage = "Message from Outer class";

​ class Inner {
​ void displayMessage() {
​ [Link](outerMessage); // Access outer class member
​ }
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Outer outer = new Outer();
​ [Link] inner = [Link] Inner();
​ [Link](); // Output: Message from Outer class
​ }
}

2. ​ Static Nested Class

○​ A static class inside another class, not tied to an instance of the outer class.
○​ It can only access the static members of the outer class.
○​ Example:

java

class Outer {
​ static String outerMessage = "Message from Outer class";

​ static class Inner {


​ void displayMessage() {
​ [Link](outerMessage); // Access outer class static
member
​ }
​ }
}
public class Main {
​ public static void main(String[] args) {
​ [Link] inner = new [Link]();
​ [Link](); // Output: Message from Outer class
​ }
}

3. ​ Local Inner Class

○​ A class defined inside a method or a block, with limited scope to that


method/block.
○​ Example:

java

class Outer {
​ void display() {
​ class LocalInner {
​ void show() {
​ [Link]("Inside Local Inner Class");
​ }
​ }

LocalInner inner = new LocalInner();
​ [Link](); // Output: Inside Local Inner Class
​ }
}

public class Main {


​ public static void main(String[] args) {
​ Outer outer = new Outer();
​ [Link]();
​ }
}

4. ​ Anonymous Inner Class

○​ A class without a name, typically used for instantiating an interface or class


with just one method.
○​ Example:

java

interface Greeting {
​ void sayHello();
}

public class Main {


​ public static void main(String[] args) {
​ Greeting greeting = new Greeting() {
​ public void sayHello() {
​ [Link]("Hello from Anonymous Inner Class!");
​ }
​ };
​ [Link](); // Output: Hello from Anonymous Inner Class!
​ }
}

Module 14: Using Predefined Package & Other Classes (Duration: 2 hrs)

1. [Link] Hierarchy

●​ The [Link] package is automatically imported in every Java program, providing


fundamental classes and functionalities.
●​ Key Classes in [Link] package:
○​ Object (Root class of all classes)
○​ String, StringBuilder, StringBuffer
○​ Math, System, Runtime
○​ Thread, Throwable, Exception, Error

2. Object Class and Using toString(), equals(), hashCode(), clone(),


finalize() etc.

Object Class:

●​ Root of all classes in Java.


●​ All classes inherit methods from Object.

Key Methods of Object:

1. ​ toString():

○​ Returns a string representation of the object.


○​ Override this method to provide meaningful string output for an object.
○​ Example:

java

class Person {
​ String name;
​ int age;

@Override
​ public String toString() {
​ return "Person{name='" + name + "', age=" + age + "}";
​ }
}

2. ​ equals():

○​ Checks if two objects are logically equivalent.


○​ Default implementation compares memory addresses, so it should be
overridden for value-based comparison.
○​ Example:

java

class Person {
​ String name;
​ int age;

​ @Override
​ public boolean equals(Object obj) {
​ if (this == obj) return true;
​ if (obj == null || getClass() != [Link]()) return false;
​ Person person = (Person) obj;
​ return age == [Link] && [Link]([Link]);
​ }
}

3. ​ hashCode():

○​ Returns a hash code for the object. It should be consistent with equals().
○​ Example:

java

@Override
public int hashCode() {
​ return [Link](name, age);
}

4. ​ clone():

○​ Creates a shallow of an object.


○​ To use clone(), the class must implement Cloneable.
○​ Example:

java
class Person implements Cloneable {
​ String name;
​ int age;

​ @Override
​ protected Object clone() throws CloneNotSupportedException {
​ return [Link]();
​ }
}

5. ​ finalize():

○​ Called by the garbage collector before the object is destroyed.


○​ Example:

java

@Override
protected void finalize() throws Throwable {
​ [Link]("Object is being garbage collected");
​ [Link]();
}

3. Using Runtime Class, Process Class to Play Music, Video from Java
Program

Runtime Class:

●​ Provides a way to interact with the Java runtime environment.


●​ Methods:
○​ getRuntime(): Returns the current runtime.
○​ exec(): Executes system commands.

Example: Playing music/video using Runtime:


java

import [Link];

public class PlayMedia {


​ public static void main(String[] args) {
​ try {
​ // Playing a music file using default media player
​ [Link]().exec("cmd /c start wmplayer \"C:\\path\\to\\your\\file.mp3\"");
​ } catch (IOException e) {
​ [Link]();
​ }
​ }
}

4. Primitives and Wrapper Classes

●​ Primitives: int, char, boolean, etc.


●​ Wrapper Classes: Integer, Character, Boolean, etc., which wrap primitive types as
objects.
●​ Autoboxing and Unboxing: Automatic conversion between primitives and their
corresponding wrapper classes.
○​ Autoboxing: Automatic conversion from primitive to wrapper class (e.g., int to
Integer).
○​ Unboxing: Automatic conversion from wrapper class to primitive (e.g.,
Integer to int).
○​ Example:

java

Integer i = 10; // Autoboxing


int j = i; ​ // Unboxing

5. Math Class

●​ Provides mathematical operations.


●​ Key methods:
○​ [Link](), [Link](), [Link](), [Link](), [Link](),
[Link]().

Example:

java

double result = [Link](16); // result = 4.0

6. String, StringBuffer, StringBuilder Class

String Class:

●​ Immutable class representing a sequence of characters.


●​ Key methods: length(), charAt(), substring(), concat(), etc.

StringBuffer & StringBuilder Classes:

●​ Mutable versions of the String class.


●​ StringBuffer is synchronized (thread-safe).
●​ StringBuilder is not synchronized (faster than StringBuffer in single-threaded
scenarios).
●​ Key methods: append(), insert(), delete(), reverse(), etc.

7. String Constant Pool

●​ A special memory region in Java that stores unique string literals.


●​ Benefits: Reduces memory usage by reusing string literals.

Example:

java

String str1 = "Hello";


String str2 = "Hello"; // Both reference the same memory location

8. Wrapper Classes

●​ Wrapper classes provide methods to convert between primitive types and their
corresponding objects.
●​ Example:

java

Integer i = [Link](100); // Boxing


int num = [Link](); ​ // Unboxing

9. System Class using gc(), exit() etc.

●​ [Link](): Requests garbage collection.


●​ [Link](): Terminates the program.

Example:

java

[Link](0); // Exit the program with a status code

Module 15: New Concepts in Package (Duration: 1 hr)

1. Auto-boxing and Auto-unboxing


●​ Auto-boxing: Automatic conversion from primitive to wrapper class.
●​ Auto-unboxing: Automatic conversion from wrapper class to primitive.

Example:

java

Integer i = 10; // Auto-boxing


int j = i; ​ // Auto-unboxing

2. Static Import

●​ Allows direct access to static members of a class without using the class name.

Example:

java

import static [Link].*; // Import all static methods from Math class

public class Example {


​ public static void main(String[] args) {
​ [Link](sqrt(16)); // No need for [Link]
​ }
}

3. Instance of Operator

●​ Tests if an object is an instance of a specific class or implements an interface.

Example:

java

if (obj instanceof String) {


​ [Link]("It's a String");
}

4. Enum and Its Use in Java

●​ Enums are special classes that represent fixed sets of constants.

Example:

java
enum Day {
​ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class Example {


​ public static void main(String[] args) {
​ Day today = [Link];
​ [Link](today); // Output: MONDAY
​ }
}

5. Working with JAR (Java Archive)

●​ JAR files are compressed files used to package Java classes and other resources.
●​ Creating JAR: jar cf [Link] *.class
●​ Extracting JAR: jar xf [Link]

Module 16: Garbage Collection (Duration: 0.5 hr)

1. Garbage Collection Introduction

●​ Automatic memory management process where the Java Virtual Machine (JVM)
removes unused objects from memory to free up space.

2. Advantages of Garbage Collection

●​ Automatic memory management reduces the programmer's responsibility.


●​ Avoids memory leaks and improves efficiency.

3. Garbage Collection Procedure

●​ The JVM performs mark-and-sweep or generational garbage collection.

4. Java API

●​ [Link](): Suggests garbage collection.


●​ Finalization: Objects may override finalize() to clean up before garbage collection.
Module 17: Exception Handling (Duration: 2 hrs)

1. Introduction to Exceptions

●​ Exception: An event that disrupts the normal flow of a program.


●​ Exceptions are objects that represent errors.

2. Effects of Exceptions

●​ Interrupts the normal program flow.


●​ Requires handling to prevent termination of the program.

3. Exception Handling Mechanism

●​ Use try-catch-finally blocks to handle exceptions.

4. Try, Catch, Finally Blocks

●​ try: Contains code that may throw an exception.


●​ catch: Handles the exception.
●​ finally: Code that always executes, regardless of whether an exception occurred.

5. Rules of Exception Handling

●​ Catch the most specific exceptions first.


●​ A finally block always runs, even if an exception is thrown.

6. Exception Class Hierarchy

●​ Throwable → Exception (checked) and Error


●​ Checked Exceptions: Must be declared or caught (e.g., IOException).
●​ Unchecked Exceptions: Runtime exceptions (e.g., NullPointerException).
7. Throw and Throws Keyword

●​ throw: Used to explicitly throw an exception.


●​ throws: Declares the exceptions a method can throw.

8. Chained Exception

●​ Passing an exception to another exception using [Link]().

Module 21: Collection Framework (Duration: 3 hrs)

1. Generics (Templates)

●​ Definition: Generics provide a way to define classes, interfaces, and methods with
type parameters, enabling the use of different types while ensuring type safety at
compile-time.
●​ Purpose: Avoids the need for casting and enables code reusability.

Example:
java

// Generic class
class Box<T> {
private T value;

public void setValue(T value) {


[Link] = value;
}

public T getValue() {
return value;
}
}

public class Main {


public static void main(String[] args) {
Box<Integer> intBox = new Box<>();
[Link](10);
[Link]([Link]()); // Output: 10
}
}

2. What is a Generic?

●​ Generic Type: A placeholder for a data type to be defined later. This allows classes
or methods to operate on objects of different types while providing compile-time type
safety.
●​ Advantages of Generics:
○​ Type safety: Reduces runtime errors due to class type mismatches.
○​ Code reusability: Same code can be applied to different types.

3. Creating User-Defined Generic Classes

●​ A user-defined class can be made generic by introducing a type parameter inside


angle brackets (<T>).

Example of a Generic Class:


java

class Pair<T, U> {


private T first;
private U second;

public Pair(T first, U second) {


[Link] = first;
[Link] = second;
}

public T getFirst() {
return first;
}

public U getSecond() {
return second;
}
}

public class Main {


public static void main(String[] args) {
Pair<Integer, String> pair = new Pair<>(1, "Apple");
[Link]([Link]()); // Output: 1
[Link]([Link]()); // Output: Apple
}
}

4. The [Link] Package

●​ The [Link] package provides a collection of utility classes and interfaces,


including collections, generics, date/time utilities, and more.

5. Collection

●​ Collection Interface: The root interface in the collection framework. It defines basic
methods for adding, removing, and manipulating elements.
●​ Types of Collections:
○​ List: Ordered collection (e.g., ArrayList, LinkedList).
○​ Set: Unordered collection with no duplicates (e.g., HashSet, TreeSet).
○​ Queue: Collection that represents a queue (e.g., PriorityQueue).
○​ Map: Collection of key-value pairs (e.g., HashMap, TreeMap).

6. What is Collection Framework?

●​ A unified architecture for representing and manipulating collections, such as lists,


sets, and maps.
●​ Key interfaces in Collection Framework:
○​ Collection: The root interface.
○​ List: Ordered collection.
○​ Set: Unordered collection with unique elements.
○​ Queue: Used for holding elements prior to processing.
○​ Map: Stores key-value pairs.

7. List, Set & Map Interfaces

●​ List Interface: An ordered collection that allows duplicates. Examples: ArrayList,


LinkedList.
○​ Methods: add(), remove(), get(), set(), contains().
●​ Set Interface: A collection that does not allow duplicates. Examples: HashSet,
TreeSet, LinkedHashSet.
○​ Methods: add(), remove(), contains().
●​ Map Interface: A collection that stores key-value pairs. Examples: HashMap,
TreeMap, LinkedHashMap.
○​ Methods: put(), get(), remove(), containsKey(),
containsValue().

8. Using Vector, ArrayList, Stack, LinkedList, etc.

●​ ArrayList: A resizable array implementation of the List interface.

Example:​
java​

ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");

○​
●​ Vector: Similar to ArrayList, but synchronized.
●​ Stack: A last-in-first-out (LIFO) collection. Inherits from Vector.

Example:​
java​

Stack<Integer> stack = new Stack<>();
[Link](1);
[Link](2);
[Link](); // Removes 2

○​
●​ LinkedList: A doubly linked list implementation of the List and Deque interfaces.

Example:​
java​

LinkedList<String> list = new LinkedList<>();
[Link]("A");
[Link]("B");

○​
9. Using Collections Class for Sorting
The Collections class provides static methods for manipulating collections (e.g., sorting,
reversing, etc.).​
Example:​
java​

List<Integer> numbers = [Link](4, 2, 8, 5);
[Link](numbers); // Sorts in ascending order
[Link](numbers); // Output: [2, 4, 5, 8]

●​

10. Using Hashtable, HashMap, TreeMap, SortedMap, LinkedHashMap,


etc.

●​ HashMap: Stores key-value pairs and allows fast lookups. Keys are unique, but
values can be duplicated.

Example:​
java​

HashMap<Integer, String> map = new HashMap<>();
[Link](1, "One");
[Link](2, "Two");

○​
●​ Hashtable: Synchronized version of HashMap. Generally slower than HashMap.
●​ TreeMap: A Map that orders keys based on their natural ordering or a custom
comparator.
●​ LinkedHashMap: Maintains the insertion order of keys.
●​ SortedMap: A map that guarantees the keys are sorted.

11. Iterator, Enumerator

●​ Iterator: Provides methods for iterating over collections (e.g., hasNext(), next(),
remove()).

Example:​
java​

Iterator<String> iter = [Link]();
while ([Link]()) {
[Link]([Link]());
}

○​
●​ Enumerator: Older interface for traversing collections (now replaced by Iterator).

12. Using Queue, Deque, SortedQueue, etc.

●​ Queue: Represents a collection designed for holding elements before processing.


○​ Example: PriorityQueue, LinkedList
●​ Deque: Double-ended queue, allows elements to be added or removed from both
ends.
●​ SortedQueue: A queue that orders elements in a specific order.

13. Using HashSet, TreeSet, LinkedHashSet

●​ HashSet: A collection that does not allow duplicate elements and does not guarantee
any specific order.
●​ TreeSet: A Set that orders elements according to their natural ordering or a
comparator.
●​ LinkedHashSet: A Set that maintains the insertion order.

14. Using Random Class

●​ The Random class is used to generate random numbers.

Example:​
java​

Random rand = new Random();
int randomNum = [Link](100); // Generates a random number
between 0 and 99

○​

15. Using Properties in a Java Program

●​ Properties is a subclass of Hashtable, used for storing key-value pairs, typically


for configuration settings.
Example:​
java​

Properties props = new Properties();
[Link]("username", "admin");
[Link]("password", "12345");

○​

16. Using User-Defined Class for Data Structure

●​ You can create your own data structure by using user-defined classes that implement
the appropriate interfaces, such as List, Set, or Map.

17. Using Date and Formatting Date Class

●​ The Date class is used to represent dates and times.

Example:​
java​

Date date = new Date();
[Link](date);

○​
●​ SimpleDateFormat: Used to format and parse dates.

Example:​
java​

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = [Link]("21/01/2025");

○​

Module 22: Java 8/9/10 Features (Duration: 1 hr)

1. Java 8 Features
●​ Lambda Expressions: Provide a clear and concise way to express instances of
single-method interfaces (functional interfaces).

Example:​
java​

List<String> list = [Link]("apple", "banana", "cherry");
[Link](s -> [Link](s)); // Lambda expression

○​
●​ Streams API: Allows functional-style operations on streams of data (filter, map,
reduce, etc.).
●​ Default Methods in Interfaces: Interfaces can now have default methods with a
body.
●​ Functional Interfaces: Interfaces with a single abstract method (e.g., Runnable,
Callable).

2. Java 9 Features

●​ Module System: Introduced the module system for better code encapsulation and
dependency management.
●​ JShell: A command-line REPL (Read-Eval-Print Loop) for interactive testing and
exploration of Java code.

3. Java 10 Features

●​ Local Variable Type Inference: The var keyword allows local variables to be
declared without explicitly specifying their type.

Example:​
java​

var list = new ArrayList<String>();

○​
●​ Improved Container Awareness: Java 10 introduced more JVM optimizations for
containers (e.g., Docker).
Advanced Java Concepts: JDBC and Servlets

JDBC (Java Database Connectivity)

1. Introduction to JDBC

●​ JDBC is an API that allows Java programs to connect and interact with relational
databases (like MySQL, PostgreSQL, Oracle, etc.).
●​ It provides a standard interface for database operations like querying, updating, and
managing data.

2. JDBC Architecture

●​ JDBC Drivers: These are platform-specific implementations of the JDBC interface


that connect Java programs to specific databases.
○​ Types of JDBC Drivers:
1.​ JDBC-ODBC Bridge Driver (Type 1)
2.​ Native-API Driver (Type 2)
3.​ Network Protocol Driver (Type 3)
4.​ Thin Driver (Type 4) — Most commonly used.

3. JDBC Components

●​ Connection Interface: Used to establish a connection to the database.


●​ Statement Interface: Used to execute SQL queries and updates.
●​ PreparedStatement Interface: Used to execute precompiled SQL queries.
●​ CallableStatement Interface: Used to execute stored procedures.
●​ ResultSet Interface: Used to store and manipulate the result of a database query.

4. Basic Steps for Using JDBC

1.​ Load the JDBC Driver:

Example:​
java​

[Link]("[Link]");

○​
2.​ Establish a Database Connection:

Example:​
java​

Connection con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"username", "password");

○​
3.​ Create a Statement Object:

Example:​
java​

Statement stmt = [Link]();

○​
4.​ Execute a Query:

Example:​
java​

ResultSet rs = [Link]("SELECT * FROM users");

○​
5.​ Process the Result:

Example:​
java​

while ([Link]()) {
[Link]([Link]("name"));
}

○​
6.​ Close Connections:

Always close the statement, result set, and connection objects.​


java​

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

○​

5. JDBC Example
java

import [Link].*;

public class JDBCExample {


public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
// Load the driver
[Link]("[Link]");

// Establish connection
con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"root", "password");

// Create statement
stmt = [Link]();

// Execute query
rs = [Link]("SELECT id, name FROM users");

// Process results
while ([Link]()) {
[Link]("ID: " + [Link]("id") + ",
Name: " + [Link]("name"));
}
} catch (SQLException | ClassNotFoundException e) {
[Link]();
} finally {
try {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

Servlets
1. What is a Servlet?

●​ A Servlet is a Java class that runs on a web server or application server and
responds to requests from a web client (such as a browser).
●​ Servlets are a fundamental component of Java web applications, serving as the
"controller" part of the Model-View-Controller (MVC) architecture.

2. Servlet Life Cycle

●​ 1. Loading and Instantiation: When a request is made to a servlet, the server loads
and instantiates the servlet class.
●​ 2. Initialization (init method): The server calls the init() method to initialize the
servlet.
●​ 3. Request Handling (service method): The service() method processes
incoming requests.
●​ 4. Destruction (destroy method): The destroy() method is called when the
servlet is removed from memory.

3. Basic Servlet Structure

●​ A simple Servlet:

java

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloServlet extends HttpServlet {


// Initialization method
public void init() throws ServletException {
// Initialization code
}

// Service method to handle requests


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Set response content type
[Link]("text/html");

// Get the writer to send the response


PrintWriter out = [Link]();

// Write response
[Link]("<html><body>");
[Link]("<h1>Hello, Servlet!</h1>");
[Link]("</body></html>");
}

// Destruction method
public void destroy() {
// Cleanup code
}
}

4. Steps to Deploy a Servlet

1.​ Create the Servlet: Write the servlet class and define the doGet or doPost method.

Configure the Servlet: Define the servlet in [Link] (deployment descriptor).​


xml​

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

2.​
3.​ Compile and Package: Compile the servlet and package it in a .war file.
4.​ Deploy on a Web Server: Deploy the .war file to a servlet container (e.g., Apache
Tomcat).
5.​ Access the Servlet: Open a web browser and visit
[Link]

5. HTTP Methods (GET, POST, PUT, DELETE)

●​ GET: Retrieves data from the server.


●​ POST: Submits data to the server (e.g., form submissions).
●​ PUT: Updates existing resources.
●​ DELETE: Deletes resources on the server.

Example of Handling GET and POST Requests in a Servlet:

java
public class LoginServlet extends HttpServlet {
// Handling GET request
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Process GET request
}

// Handling POST request


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");

// Handle login logic


if ("admin".equals(username) && "password".equals(password))
{
[Link]().println("Login successful!");
} else {
[Link]().println("Invalid login
credentials.");
}
}
}

6. Servlet vs JSP

●​ Servlet: Java class used to process requests and generate responses.


●​ JSP (JavaServer Pages): A more concise, HTML-based approach for creating
dynamic web pages. JSPs are compiled into Servlets behind the scenes.

7. Servlet Security

●​ Use HTTPS to secure the communication between the client and the server.
●​ Implement user authentication (e.g., using cookies or session management).

8. Session Management
●​ Session: A mechanism to maintain state (like user login) across multiple HTTP
requests.
●​ HttpSession Interface: Used to track user sessions.

Example:

java

// Creating a session
HttpSession session = [Link]();
[Link]("username", "admin");

// Retrieving a session attribute


String username = (String) [Link]("username");

9. Advanced Servlet Techniques

●​ Filters: Used to perform preprocessing or postprocessing of requests and responses


(e.g., for logging, authentication).
●​ Listeners: Used to listen to events such as session creation and destruction.

Module 7: Design Patterns (Duration: 2 hrs)

1. Singleton Design Pattern

●​ Definition: The Singleton pattern ensures that a class has only one instance and
provides a global point of access to that instance.
●​ Use Cases: Useful when exactly one object is needed to coordinate actions across
the system, e.g., a configuration manager or logging system.

Example:

java

public class Singleton {


private static Singleton instance;

// Private constructor to prevent instantiation


private Singleton() {}
// Public method to provide access to the instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

2. DAO (Data Access Object) Pattern

●​ Definition: DAO is used to abstract and encapsulate all interactions with a data
source, providing an interface for the persistence layer.
●​ Use Cases: It allows for separation between business logic and data access logic.

Example:

java

public interface UserDAO {


void save(User user);
User getUserById(int id);
}

public class UserDAOImpl implements UserDAO {


@Override
public void save(User user) {
// Code to save user to database
}

@Override
public User getUserById(int id) {
// Code to fetch user from database
return new User();
}
}

3. DTO (Data Transfer Object) Pattern

●​ Definition: DTO is a simple object that is used to transfer data between layers, such
as from the data access layer to the presentation layer.
●​ Use Cases: When you want to pass data without exposing business logic or complex
operations.
Example:

java

public class UserDTO {


private String name;
private int age;

// Getters and Setters


}

4. MVC (Model-View-Controller) Pattern

●​ Definition: MVC is an architectural pattern that separates an application into three


interconnected components:
○​ Model: Handles data and business logic.
○​ View: Represents the UI and presents data.
○​ Controller: Manages user input and updates the model and view.

Example:

●​ Model: [Link] (business logic and data)


●​ View: [Link] (displays user data)
●​ Controller: [Link] (handles user requests)

5. Front Controller Pattern

●​ Definition: The Front Controller pattern provides a centralized entry point for
handling requests, often used in web applications.
●​ Use Cases: It simplifies request routing and handling in large applications.

Example: A DispatcherServlet in Spring MVC that routes requests to different


controllers.

6. Factory Method Pattern

●​ Definition: The Factory Method pattern provides an interface for creating objects, but
allows subclasses to alter the type of objects that will be created.
●​ Use Cases: When the creation of an object involves complex logic or needs to vary.

Example:

java

public abstract class Animal {


public abstract void speak();
}
public class Dog extends Animal {
@Override
public void speak() {
[Link]("Woof!");
}
}

public class Cat extends Animal {


@Override
public void speak() {
[Link]("Meow!");
}
}

public class AnimalFactory {


public static Animal getAnimal(String type) {
if ("Dog".equalsIgnoreCase(type)) {
return new Dog();
} else if ("Cat".equalsIgnoreCase(type)) {
return new Cat();
}
return null;
}
}

7. Abstract Factory Pattern

●​ Definition: The Abstract Factory pattern provides an interface for creating families of
related or dependent objects without specifying their concrete classes.
●​ Use Cases: Useful when you have multiple families of products or objects that need
to be created in a consistent manner.

Example:

java

// Abstract Factory
public interface AnimalFactory {
Animal createAnimal();
}

// Concrete Factory
public class DogFactory implements AnimalFactory {
@Override
public Animal createAnimal() {
return new Dog();
}
}

Module 8: JUnit (Duration: 1 hr)

1. JUnit: What and Why?

●​ What is JUnit?: JUnit is a popular testing framework for Java. It provides


annotations and methods to write and run tests to ensure that your code works as
expected.
●​ Why JUnit?: It promotes automated testing, supports test-driven development
(TDD), and helps identify bugs early in the development process.

2. Annotations Used in JUnit

●​ @Test: Marks a method as a test case.


●​ @Before: Runs before each test method. Used to set up common resources.
●​ @After: Runs after each test method. Used to clean up resources.
●​ @BeforeClass: Runs once before any test methods are executed (static context).
●​ @AfterClass: Runs once after all test methods are executed (static context).
●​ @Ignore: Used to ignore a test method.

Example:

java

import [Link].*;

public class CalculatorTest {


private Calculator calculator;

@Before
public void setUp() {
calculator = new Calculator();
}

@Test
public void testAddition() {
[Link](5, [Link](2, 3));
}
@After
public void tearDown() {
// Clean up resources if needed
}
}

3. Assert Class

●​ The Assert class in JUnit provides static methods to assert the results of test cases.
○​ assertEquals(expected, actual): Asserts that two values are equal.
○​ assertTrue(condition): Asserts that a condition is true.
○​ assertFalse(condition): Asserts that a condition is false.
○​ assertNull(object): Asserts that an object is null.
○​ assertNotNull(object): Asserts that an object is not null.

4. Test Cases

●​ A test case is a method annotated with @Test that verifies the behavior of a single
unit of code (e.g., a method in a class).
●​ A test suite is a collection of test cases grouped together to run as a batch.

Module 9: Maven (Duration: 1 hr)

1. What is Maven?

●​ Maven is a build automation tool used primarily for Java projects. It helps in
managing project dependencies, building projects, and deploying applications.
●​ Purpose: It simplifies the process of building and managing projects by using a
central repository for dependencies and providing standard project structures.

2. Maven Basics

●​ [Link]: The configuration file for a Maven project. It contains information about the
project, its dependencies, build plugins, and more.

Example of [Link]:

xml

<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

3. Key Maven Commands

●​ mvn clean: Cleans the project by removing target/ directory.


●​ mvn compile: Compiles the source code of the project.
●​ mvn test: Runs the tests in the project.
●​ mvn package: Packages the compiled code into a .jar or .war file.
●​ mvn install: Installs the project to the local Maven repository.
●​ mvn deploy: Deploys the project to a remote repository.

4. Maven Phases and Goals

●​ Phases: Represent stages in the build lifecycle (e.g., compile, test, package).
●​ Goals: Specific tasks associated with a phase (e.g., mvn clean executes the clean
goal).

●​

Life Cycle of JSP


A JSP (JavaServer Pages) file goes through several stages before it is executed as a web
page. The life cycle of a JSP involves the following steps:

1. Translation Phase 📝
●​ The JSP file is translated into a Servlet by the JSP engine.
●​ The .jsp file is converted into a Java .java file (a servlet class).

2. Compilation Phase 🔧
●​ The generated Java file (servlet) is compiled into a .class file (bytecode).

3. Loading & Initialization Phase 🚀


●​ The servlet class is loaded into the JVM.
●​ The jspInit() method is called once when the JSP is initialized.

4. Request Processing Phase 🔄


●​ The request is handled by the _jspService() method.
●​ This method contains the Java code inside scriptlets (<% ... %>), expressions (<%=
... %>), and declarations (<%! ... %>).

5. Destroy Phase 🛑
●​ When the JSP is no longer needed, jspDestroy() is called to clean up resources.

1. Scriptlet Tag (<% ... %>)

●​ The scriptlet tag is used to write Java code inside a JSP file.
●​ Code written inside the scriptlet tag is placed inside the _jspService() method of
the servlet that the JSP is translated into.
●​ You can use it for looping, conditionals, and calling methods.

Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
int a = 10;
int b = 20;
int sum = a + b;
[Link]("Sum: " + sum); // Outputting to response
%>
</body>
</html>

2. Expression Tag (<%= ... %>)

●​ The expression tag is used to output values directly into the response.
●​ It is a shortcut for [Link](), meaning whatever is inside <%= ... %> is
evaluated and written to the response.

Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<h2>Sum: <%= 10 + 20 %></h2> <!-- Prints Sum: 30 -->
<h2>Current Time: <%= new [Link]() %></h2> <!-- Prints
current date -->
</body>
</html>

3. Declaration Tag (<%! ... %>)

●​ The declaration tag is used to declare methods and variables that are placed
outside the _jspService() method, making them part of the generated servlet
class.
●​ It is mainly used for defining class-level variables and methods.

Example:
jsp
CopyEdit
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%!
int square(int num) {
return num * num;
}
%>
<h2>Square of 5: <%= square(5) %></h2> <!-- Calls declared
method -->
</body>
</html>

Summary
Tag Purpose Scope

<% ... %> Executes Java Inside


code _jspService()

<%= ... %> Outputs a value Inside


_jspService()

<%! ... %> Declares At class level


methods/variabl
es

You might also like