0% found this document useful (0 votes)
46 views73 pages

Core Java Lab Experiments Guide

The document outlines the curriculum for a Core Java course for the academic year 2025-26, detailing various lab experiments and exercises focused on Java programming concepts. Key topics include Java basics, decision-making structures, iteration structures, classes and objects, and exception handling. Each section includes learnings, code examples, and worksheets for practical understanding and assessment.
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)
46 views73 pages

Core Java Lab Experiments Guide

The document outlines the curriculum for a Core Java course for the academic year 2025-26, detailing various lab experiments and exercises focused on Java programming concepts. Key topics include Java basics, decision-making structures, iteration structures, classes and objects, and exception handling. Each section includes learnings, code examples, and worksheets for practical understanding and assessment.
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

Academic Year: 2025-26 Subject: Core Java Semester: III

INDEX
Lab Page No. Date of Date of Grade/ Signature of
No. Experiment Title (From - To) Performance Submission Remarks Facilitator

1 Introduction to Java Programming


Variables, Identifiers, datatypes and
2 Operators
Decision Structures and break
3 statement
Iteration Structures and continue
4 statement

5 Class-Based Program Design

6 Student Record System

7 Employee Hierarchy

8 Shape Area Calculation

9 Role Management with Enums

10 Array Operations

11 String Handling
Voting Eligibility with Custom
12 Exception

13 Collections Framework

14 Generic and wildcards

15 CRUD Operations using JDBC

Signature of Staff I/C

Page 1
LAB EXERCISE-1
LAB EXERCISE NAME: Understanding the Basic Java Code

Learnings:

1. Java is a Case Sensitive Language.


2. Java file name should match with public class name, and java files extension will be
.java.
3. The piece of logic we write is called a block of code and they are enclosed in {...}.
4. In Java, functions are called Methods.
5. A class is a block of code which contains member variables and methods.
6. The line of logic is called a statement in java, and they are ended with the ;.
7. Java Code execution starts from the main method, in the main method execution follows
line by line, user defined methods will not execute until and unless they have been called
in the main method. When the user defined method is called, then execution of the main
method will get paused and the user defined method starts execution and once the user
defined method is ended, then the main method will restarts its execution.
8. Commenting can be done as follows:
Single-line: // comment
Multi-line: /* comment block */
9. Method Structure:

10. Access Modifiers define accessibility of member variables and methods.

Page 2
11. Dot Operator is used for accessing:
i. SubPackage of a Package
ii. Class of a Package
iii. A variable of a class
iv. A method of a class

12. Errors are those which occur during CompileTime.


Exceptions are those which occur during RunTime.
13. Text Editor: A text editor is a software that can only edit text. They are super lightweight
and usually come pre-installed on your system.
Examples of text editors include Notepad and Notepad++.
14. Code Editor: When additional functionalities are added to a text editor, making it
appropriate for coding, it becomes a code editor.
Code editors can:
● Edit text
● Highlight syntax
● Autocomplete code
● Compile or run code directly

Examples of code editors include Notepad++, Visual Studio Code (VS Code), Atom, and
Sublime Text Editor.

15. Integrated Development Environments (IDEs): An IDE is a software that provides


comprehensive facilities to computer programmers for software development. An IDE
normally consists of at least a source code editor, build automation tools, and a
debugger.
Examples of IDEs include Eclipse, IntelliJ IDEA, and NetBeans.
16. Online IDEs: Online IDEs are web-based applications that allow you to write, run, and
debug code in various programming languages. They are similar to code editors and
IDEs but are accessible through a web browser. This means you don't need to install any
additional software on your system.
Examples of online IDEs include [Link], CodePen, and Glitch.
17. Console/Terminal is the place where output will be displayed and input is provided to the
code.

Page 3
Code:

Page 4
Worksheet:

1. What is the difference between a Text Editor, Code Editor, and IDE?

2. What is the role of the main() method in Java?

3. What is the difference between Errors and Exceptions in Java?

4. What is the use of the dot (.) operator in Java?

5. Why must the Java file name match the public class name?

Page 5
LAB EXPERIMENT-2
LAB EXPERIMENT NAME: Java Variables, Identifiers, datatypes and Operators

Learnings:

1. A class is a Blueprint, An Object is an instance of a class which is a real world entity.

2. Scanner class is used to take inputs from the console. Scanner class is an inbuilt class
in JRE, so we will create an Object of it to use in our code.

To create an Object syntax is:


<ClassName> <ObjectName> = new <Constructor>
Example: Scanner sc = new Scanner([Link]);
In the above line, Scanner is the class name, sc is the object name, new keyword is
used to allocate memory, and [Link] is an input stream.

3. For different datatypes we have different methods in Scanner class to take the inputs
from the console.
i. int → nextInt()
ii. double → nextDouble()
iii. Single word String → next()
iv. Multiple words String → nextLine()
v. Long → nextLong()
vi. Float → nextFloat()
vii. Boolean → nextBoolean()
viii. char → next().charAt(0)

4. If we read Number first and then followed by a String, then the string will not be read
from the console, so we need to call the method nextLine() after reading Number from
the console.
5. Close the scanner class once the reading of input is done from the console by using
close() method.

Page 6
6. The Scanner object can accept input from various sources like an input stream, a string,
a file, etc.

While the Scanner class is fairly efficient, it is not the best choice for reading large
volumes of data from a source. In such cases, other classes like BufferedReader can be
used.

7. While taking inputs, it's important to handle exceptions that might occur due to incorrect
or unexpected user inputs. For example, if the user provides a string when an integer is
expected, an InputMismatchException will be thrown. Similarly, if the user provides no
input when one is expected, a NoSuchElementException will be thrown. To handle these
exceptions, you can use try-catch blocks in your code. This will allow your program to
continue running even when an exception occurs.

8. Scanner class has a function “hasNext()” to check any value available on the console.

9. Variable Creation:
<DataType> <VariableName> = <Value> [this process is called as Initialization]

10. Type Conversions: It refers to changing a variable from one datatype to another
datatype.

Order of Memory space occupied by Number Datatypes from small to Large:


byte → short → int → long → float → double

Implicit Type Conversion: Converting smaller data types to larger data types, Performed
Automatically by the compiler.

Explicit Type Conversion: Explicit type conversion is the process of manually converting
a variable from one data type to another, usually from a larger data type to a smaller
one, or to force a specific conversion. It is done using type casting syntax and may result
in data loss or truncation.

<TargetDataType> <VariableName> = (<TargetDataType>) <Value>

Code:

Draw the flowchart and write the pseudocode and java code to calculate the area of a circle.

Remember, you need to take one input:


The radius of the circle (r).
And print the area of the circle as output.
You are expected to design a flowchart and write the pseudocode to implement this logic in
[Link], and execute the java code.

Page 7
Flow Chart : PseudoCode:

Start
Take radius value as input from the user
Create variable area and assign it with 2*pi*r
Output the calculated area
End

Page 8
Worksheet:

1. What is the purpose of the Scanner class in Java?

2. What is the difference between implicit and explicit type conversion?

3. What is the difference between next() and nextLine() methods in the Scanner class?

4. What kind of exception occurs if a user enters the wrong input type in Scanner?

5. Explain the difference between primitive and non-primitive data types in Java.

Page 9
LAB EXPERIMENT-3
LAB EXPERIMENT NAME: Understanding Java Decision Makings and break statement

Learnings:

Decision/Selection Structure changes the flow of execution according to a condition or decision


taken. There are two types of decision structures: if-elseif-else and switch.

if block:

‘If’ is a block containing relational and logical expressions (which return true or false as result) in
the condition check, if the result returns true then the block of code will execute otherwise it is
skipped.

Syntex:

if (<condition>) {
//statements
}

else block:

The else block does not contain any conditions to check, it will execute the block of code when
the condition returns false. else block is an optional.

Note:
1. Always else block comes after an if-block, an alone else block will throw an error.
2. There should not be any statements in between if and else blocks.

Syntex:

if (<condition>) {
//statements
}
else{
//statements
}

else if block:

It is a combination of else and if. It extends an if statement to execute a different set of


statements in case of if evaluates to false.

Page 10
The conditions present inside the else-if block are checked. Once a condition evaluates to true,
remaining else-if and else blocks are skipped.

Syntex:

if (<condition 1>) {
//statements
}
else if(<condition 2>){
//statements
}
else{
//statements
}

Note:
1. In the if-elseif-else block’s, if there is only 1 statement then { } is not mandatory.
2. For decision making there can be multiple else-if blocks but only 1 if and else blocks are
allowed.

Nested if-elseif-else structures:

Nested if-elseif-else blocks occur when an if, else-if, or else block contains another if-elseif-else
structure inside it. This allows multiple levels of decision making, where a secondary condition is
checked only if the primary condition evaluates to true (or false, depending on the placement).

Syntex:

if (<condition 1>) {
//statements
if (<condition 2>) {
//statements
}
else if (<condition 3>) {
#statements
}
else {
//statements
}
}
else {
//statements
}

Page 11
break Statement:

The break statement is used to terminate the current block immediately, transferring control to
the statement following the terminated block.

Switch Structure:

The switch structure is a multi-way decision-making structure that executes one block of code
among many alternatives based on the value of an expression. It is often used when a variable
is compared against constant values. The expression must return a single value of type int,
char, String, or enum. Each case inside of the switch defines a constant value to match against
the expression.

Syntex:

switch (<expression>) {
case <value1>:
//statements
break;
case <value2>:
//statements
break;
default:
//statements
}

Note:

1. break is mandatory unless fall-through to the next case is intended.


2. Multiple case statements can share the same code.
3. Expressions in switch must return a single value; relational or logical or boolean
expressions are not allowed directly.

Code:

Student result evaluation system: Input the marks of a student (0-100). Use if-else-if ladder to
assign a grade:

90-100 → A
75-89 → B
50-74 → C
<50 → F

Page 12
Use a switch statement to display remarks based on the grade:

A → “Excellent”
B → “Good”
C → “Average”
F → “Fail”

If the marks entered are invalid (not in 0-100), print “Invalid marks” using if.

Demonstrate nested if inside switch: For grade A, check if marks are above 95 for “Distinction”
remark.

Output:

Page 13
Worksheet:

1. What is the main difference between if-else and switch statements in Java?

2. Can we use relational or logical expressions inside a switch statement? Why or why not?

3. What happens if you omit the break statement in a switch case? Explain with an example.

4. What is a nested if statement? Give a situation where it might be useful.

5. What is fall-through behavior in a switch case?

Page 14
LAB EXPERIMENT- 4
LAB EXPERIMENT NAME: Understanding Java Iteration Structures and continue statement

Learnings:

Iteration Structures repeatedly executes the same block of code based on some condition.
There are three types of Iteration Structures: for, while, do-while.

for loop:

Used when the number of iterations is known in advance. The loop has an initialization,
condition check, and update expression.

Syntex:

for (initialization; condition; update) {


// statements
}

Initialization happens once. Condition is checked before every iteration. Body executes if
condition is true. Update executes after each iteration.

Note:
All three parts (initialization, condition, update) are optional. If not coded then an infinite loop will
be formed.

while loop:

Used when the number of iterations is not known in advance; executes as long as the condition
is true.

Syntex:

while (condition) {
// statements
}
Condition is checked before every iteration. If the condition is false initially, the loop never
executes. Used when we need entry-controlled looping.

Page 15
do-while loop:

Similar to while, but the condition is checked after executing the body ensuring the loop runs at
least once.

Syntex:

do {
// statements
} while (condition);

Note:

1. Known as an exit-controlled loop.


2. Always executes the body once even if the condition is false.

continue statement:

The continue statement skips the remaining statements in the current iteration and jumps to the
next iteration of the loop.

Notes:

1. Can be used inside for, while, or do-while loops.


2. Does not terminate the loop; it only skips the rest of the current iteration.

Nested Loops:

A nested loop means having one loop inside another loop. The inner loop executes completely
for each iteration of the outer loop. Nested loops can be of any type for, while, or do-while
combined in any order.

Code:

Pattern Menu System: Create a menu-driven program where user selects which pattern to
print.
1- Square
2- Right Triangle
3- Inverted Triangle.

Use switch-case inside a while loop.

Page 16
Output:

Page 17
Worksheet:

1. What is the difference between entry-controlled and exit-controlled loops in Java?

2. Explain the purpose of the continue statement. How is it different from break?

3. In what situations is a for loop more suitable than a while loop?

4. If you nest two loops and use continue in the inner loop, what happens to the outer loop?

5. Explain how short-circuiting (&&, ||) inside a loop condition affects performance.

Page 18
LAB EXERCISE - 5
LAB EXERCISE NAME: Understanding Classes and Objects in Java

Learnings:

1. A constructor is a Special Method in java which is used to initialize the class Variables.
A constructor name must match with class Name, the constructor does not have a return
type.

<Access Modifier> CLASSNAME( <values variables for the method> ){


//initialization
}

2. this keyword is used to indicate that a variable is a class variable.

Code:
Class-Based Program Design: Design a BankAccount class with deposit, withdraw, and
balance check methods.

[Link] file:

Page 19
[Link] file:

Output Snippet:

Page 20
Worksheet:

1. What is the purpose of a constructor in Java, and how is it different from a method?

2. What does the this keyword represent in Java, and when should you use it?

3. Can a class have more than one constructor? If yes, how does Java decide which one to call?

4. Explain how encapsulation is achieved in the BankAccount class example.

5. What happens if you don’t define a constructor in your Java class?

Page 21
LAB EXPERIMENT - 6
LAB EXPERIMENT NAME: Understanding Encapsulation and static in java

Learnings:

1. Encapsulation is one of the key concepts in Object-Oriented Programming (OOP). It


refers to the process of binding data (fields) and methods that operate on the data
into a single unit (class), and restricting direct access to the data from outside the
class.

By declaring fields as private and using public getter and setter methods, you can
control how the data is accessed or modified.

Benefits of Encapsulation:
i. Protects data from unauthorized access.
ii. Allows validation before updating values.
iii. Improves code maintainability and flexibility.
iv. Hides internal implementation details.

Syntax for Encapsulation:

public class ClassName {


// Private fields
private DataType fieldName;

// Getter method
public DataType getFieldName() {
return fieldName;
}

// Setter method
public void setFieldName(DataType value) {
[Link] = value;
}
}

Usage:

ClassName objectName = new Constructor();


[Link](value); // Setting value
[Link]([Link]()); // Getting value

Page 22
2. static is a keyword in Java used for memory management. It can be applied to variables,
methods, blocks, and nested classes. Static members belong to the class rather than
an instance of the class.

Key Points about Static:


i. A static variable is shared by all objects of the class.
ii. Static methods can be called without creating an object.
iii. Static members are loaded into memory only once at the time of class loading.

Syntax for Static Variable and Method:

public class ClassName {


static DataType variableName; // Static Variable

static void methodName() { // Static Method


// code
}
}

Usage:

[Link]([Link]); // Access static variable


[Link](); // Call static method

Initialization of a static variable during declaration is not mandatory in Java. If you


don’t explicitly initialize it, the JVM provides default values depending on the data type:

● int, long, short, byte → 0


● float, double → 0.0
● boolean → false
● char → \u0000 (null character)
● Reference types → null

If you want one common (default) value for all objects, then you need to initialize the
static variable either:

● at declaration
● or inside a static block.

Static variables are shared by all objects. If you change it through one object, the
change reflects in all objects, because there is only one copy in memory (at class level).

Page 23
Instance vs Static Members

● Instance Variables/Methods: Belong to the object; each object has its own
copy.
● Static Variables/Methods: Belong to the class; shared among all objects.

3. Access Modifiers, they define the visibility/scope of classes, methods, variables, and
constructors.
● private → The weakest and most restrictive access modifier. Accessible only
within the same class.
● default(Package-private) → accessible within the same package only.
● protected → accessible within the same package + subclasses (even outside
package by using inheritance).
● public → The strongest and least restrictive access modifier. Accessible from
anywhere.

Code:
Student Record System: Create a Student class with static variables and encapsulated fields.

[Link] file:

Page 24
[Link] file:

Output:

Page 25
Worksheet:

1. What is the primary purpose of Encapsulation in Object-Oriented Programming (OOP)?

2. In the context of Encapsulation, what is the typical role of private access modifier for fields and public
access modifier for methods?

3. Explain the key difference between a static variable and an instance variable.

4. Explain the roles of Getter and Setter methods in the context of Encapsulation.

5. How does Encapsulation contribute to better Code Maintainability and Flexibility?

Page 26
LAB EXERCISE - 7
LAB EXERCISE NAME: Understanding Inheritance in Java

Learnings:

[Link] is an Object-Oriented Programming concept where one class (child or subclass


or derived) acquires the properties and behaviors (fields and methods) of another class (parent
or superclass or base).It helps in code reusability and creating a hierarchical relationship
between classes. It is also called as “is-a” relationship.

Key Points about Inheritance

1. Extends Keyword
○ Used by a subclass to inherit a superclass.
2. Types of Inheritance in Java (Supported)
○ Single Inheritance: One class inherits from another.
○ Multilevel Inheritance: A class inherits from a derived class.
○ Hierarchical Inheritance: Multiple classes inherit from the same base
class.

(Note: Java does not support Multiple Inheritance with classes to avoid ambiguity,
use interfaces instead.)

3. Method Overriding
○ Subclass provides a new implementation of a method that already exists
in the parent [Link] @Override annotation.
4. Access Control
○ Private members of the superclass are not accessible directly in the
subclass.
○ Protected members can be accessed in subclasses.

Syntax Example:

Page 27
2. Overriding allows a different implementation of parent methods with the same signature in
the child classes, and this process is called Dynamic Polymorphism or Runtime
Polymorphism. Such parent methods are said to be overridden. The methods should not have
weaker(most restrictive) access modifiers.

“@Override” annotation is used above the method signature in child class to achieve method
overriding.

Invoking overridden methods:


Case-1: Reference of parent class and object of parent class, then parent method will be
invoked.
Case-2: Reference of child class and object of child class, then child method will be
invoked.
Case-3: Reference of parent class and object of child class, then child method will be
invoked.

3. The version of the method that will be called is determined by the object, and this decision is
taken at runtime, this is called Dynamic binding or Late Binding.

If a parent class reference refers to a child class object. The version of the method invoked is
determined by the object. Only the overridden method can be called using the parent class
reference. Any new method created in the child class will not be accessible using the parent
class reference.

4. Calls to static methods are resolved at compile time, a process known as static binding or
early binding. The compiler decides which method to call based on the type of the reference
variable, not the type of the object it refers to.

Unlike instance methods, static methods belong to the class itself, not to any specific object
instance. When a static method is defined with the same signature in a child class, it's not
overriding the parent's method; it's simply hiding it. The two methods are entirely separate.

5. The super keyword in Java is a reference variable used inside a child class to refer to the
immediate parent class.

It has three main uses in inheritance:


● Call Parent Constructor – using super() to invoke parent’s constructor (must be the first
statement).
● Access Parent Variables – when a child class has a variable with the same name,
[Link] accesses the parent’s variable.
● Access Parent Methods – when child class overrides a method, [Link]()
calls the parent’s version of the method.

Page 28
Example:

Page 29
6. Constructors are not inherited, but are always executed in the hierarchy. When a child class
object is created, the parent class constructor is always executed first, then the child’s
constructor. This happens because the child class constructor implicitly calls super() (i.e.,
parent’s no-arg constructor/default constructor) as the first statement.

Example:

Case-1: If Parent has only parameterized constructor. The child must explicitly call
super(arguments) as the first statement in the child constructor, otherwise
compilation error.

Case-2: If Parent has parameterized constructor’s, Child constructor must call a


specific parent constructor using super(args). And it must be the first statement in
the child constructor.

Case-3: Multi-level inheritance Constructors are called in chain order, Top-most


parent → Middle parent → Child.

super() and this() cannot be used together in the same constructor for the same fields
(only one can be the first statement).

7. If the parent class has multiple variables and the child inherits them, but only initializes or
sets some of them then Java will not give a compilation error. The remaining variables will
simply hold their default values (for primitives: 0, 0.0, false, \u0000; for objects: null).

Page 30
Code:
Employee Hierarchy: Build a base Employee class and derive Manager, Developer with
overrides.

[Link] file:

[Link] file:

[Link] file:

Page 31
[Link] file:

Output:

Page 32
Worksheet:

1. What are the types of inheritance supported in Java?

2. What are the super, this, extends keywords used for in the context of inheritance?

3. Can a final method and can a constructor be overridden in Java?

4. Differentiate between Method Overloading and Method Overriding. Which one is related to
Polymorphism at Compile Time, and which one is related to Polymorphism at Run Time?

5. Can we use multiple inheritance in Java using classes? If not, how can we achieve it?

Page 33
LAB EXERCISE - 8
LAB EXERCISE NAME: Understanding Abstraction and Interfaces in Java

Learnings:

1. The final keyword is a non-access modifier used for variables, methods, and classes
to impose restrictions.
1. Final Variable: A final variable becomes a constant, its value cannot be changed
once assigned. A final variable must be initialized (either at declaration, in
constructor, or in initializer block). If not initialized, it causes a compilation error
because a final variable cannot remain unassigned. If a variable is final, it cannot
be initialized or reassigned inside a method.
2. Final Method: A final method cannot be overridden in a subclass, but it can
be overloaded within the same class.
3. Final Class: A final class cannot be inherited (no subclass can extend it).

Example:

2. Abstraction
○ Abstraction means hiding implementation details and exposing only the
necessary functionalities to the user.
○ It focuses on "what to do"(rules) rather than "how to do".
○ Achieved in Java using abstract classes and interfaces.

Page 34
3. Abstract Class
○ Declared with the abstract keyword. It signifies that something is not complete.
○ Can contain abstract methods (without a body) and concrete methods (with a
body), partial abstraction (rules, what to do + some common implementation,
how to do).
○ If a class contains at least one abstract method, the class should be abstract.
A class can be made abstract even without any abstract methods.
○ Cannot be instantiated directly; it must be inherited by a subclass.
○ Used when classes share common functionality but also need to enforce some
specific implementations in child classes.
○ Abstract classes enforce inheritance(since they cannot be instantiated) and
Abstract methods enforce overriding(as they are incomplete with no
implementation). So while creating an object, If a reference is abstract, the object
must be of a child.

Syntax:
abstract class Shape {
abstract double calculateArea();
}

4. Interface
○ An Interface is used to define a generic template which can be implemented by
various classes. It contains method signature and constant declarations.
○ The methods declared in an interface are implicitly public and abstract and also
can be explicitly public and static and data fields are implicitly public, static and
final.
○ Declared with the interface keyword,and it is full abstraction (only rules,What
to do).
○ The implements keyword is used to implement an interface. An Interface and
class can implement more than one interface. This can be used to simulate
multiple inheritance in java. The classes implementing an interface must
implement all the specified methods. Otherwise they should be made
abstract.
○ An Interface creates a type. Hence, its reference can be used to refer to the
objects of the classes which implement that interface. This leads to dynamic
binding.

Syntax:
interface Drawable {
void draw();
}

5. Implementing an Interface
○ A class uses the implements keyword to provide an implementation for all
methods declared in an interface.

Page 35
Syntax:
class Rectangle implements Drawable {
public void draw() {
[Link]("Drawing Rectangle");
}
}

6. Extending an Abstract Class


○ A class uses the extended keyword to inherit from an abstract class.
○ It must override all abstract methods or be declared abstract itself.

Syntax:
class Rectangle extends Shape {
@Override
double calculateArea() {
return length * width;
}
}

7. Multiple Inheritance via Abstract Class + Interface


○ Java doesn’t allow multiple inheritance with classes, but a class can extend one
abstract class and implement multiple interfaces.

Example:
class Rectangle extends Shape implements Drawable { ... }

8. Advantages of Using Abstraction and Interfaces


○ Code Reusability – Common logic goes into abstract classes.
○ Flexibility – Interfaces allow different classes to share the same method
signatures but have different implementations.
○ Loose Coupling – Code depends on abstractions, not concrete
implementations.
○ Scalability – Adding new shapes in this program requires creating a new class
without changing the existing code (Open/Closed Principle).

Page 36
Code:

Shape Area Calculation: Use abstract classes and interfaces to calculate areas of different
shapes.

[Link] file:

[Link] file:

[Link] file:

[Link] file:

Page 37
[Link] file:

[Link] file:

[Link] file:

Page 38
Output:

Page 39
Worksheet:

1. How can multiple inheritance be achieved in Java using abstraction concepts such as interfaces?

2. In Java interfaces, which of the following are allowed implemented methods, constructors, or a main
method?

3. Can we create an object of an abstract class or an interface? Why or why not?

4. Can an interface extend another interface or an abstract class? How does it work?

5. Can an abstract class have both abstract and non-abstract methods? Explain with an example.

Page 40
LAB EXERCISE - 9
LAB EXERCISE NAME: Understanding Enums & Type Casting in Java

Learnings:

1. Enums are special classes in Java used to define a fixed set of constants. It is a
non-primitive datatype.
They improve code readability and type safety compared to using plain strings or
integers.

Syntax:

enum Role {
ADMIN, MANAGER, DEVELOPER, INTERN
}

Key Points about Enums:

● Each constant is a public static final instance of the enum type implicitly.
● All enums implicitly extend the [Link] class.
● Since enums are reference data types, like class or interface, and hence we can
define constructors, methods, and variables in an enum.
● Values can be provided to enum constants at the time of their creation. These
values are passed to the constructor when the constant is created. It
automatically creates constants that are defined at the beginning of the enum
body. The constructor for an enum type must have default or private access. But
the constructor cannot be invoked using the new operator.
● Useful in scenarios like role management, status codes, etc.

2. Type casting in OOP refers to converting one object type to another within the
inheritance hierarchy.

Types:

1. Upcasting
○ Converting a subclass reference to a superclass type.
○ Done implicitly.

Example:
Employee emp = new Manager(); // Upcasting

○ Purpose: Allows treating all subclasses uniformly.

Page 41
2. Downcasting
○ Converting a superclass reference back to a subclass type.
○ Done explicitly using (Subclass) cast.

Example:
Manager mgr = (Manager) emp; // Downcasting

○ Purpose: Allows access to subclass-specific features.


○ Must be used carefully to avoid ClassCastException.

Code:

Role Management with Enums: Define roles using enums and demonstrate
upcasting/downcasting in class design.

[Link] file:

[Link] file:

Page 42
[Link] file:

[Link] file:

[Link] file:

Page 43
Worksheet:

1. Can we define methods and constructors inside an enum? Explain with an example.

2. Can we perform type casting between incompatible data types or between objects of unrelated classes?
Why or why not?

3. What happens if you try to create an enum instance using the new keyword? Why is it not allowed?

4. What is the purpose of the values() and valueOf() methods in enums, and how are they generated by the
compiler?

5. Can we cast between unrelated object types? What happens at runtime if we try to do so?

Page 44
LAB EXERCISE - 10
LAB EXERCISE NAME: Understanding 1D and 2D array in Java

Learning:

1. 1D Array
Declaration
int[] arr; // Declaration
arr = new int[5]; // Memory allocation
or
int[] arr = new int[5]; // Declaration + allocation
int[] arr2 = {10, 20, 30, 40}; // Declaration + initialization
Indexing starts at 0 and ends at length - 1.
Default values are assigned if not initialized:

○ int → 0
○ double → 0.0
○ boolean → false
○ Object → null
Length is accessed using [Link] (no parentheses, it’s a property).
Enhanced for loop can be used for iteration:
for (int num : arr) { [Link](num); }
Memory – Object is stored in heap, reference stored in stack.
Shallow copy – Assigning one array to another copies the reference, not data.
ArrayIndexOutOfBoundsException occurs if the index is invalid.

2. 2D Array
Declaration
int[][] matrix; // Declaration
matrix = new int[3][4]; // 3 rows, 4 columns
or
int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; // 2 rows, 3 columns
Indexing – First index is row, second is column:
○ matrix[row][col]
Jagged arrays – Each row can have different column sizes:
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[5];
Default values work like in 1D arrays.
Length:
○ [Link] → number of rows
○ matrix[i].length → number of columns in row i

Page 45
Nested loops for traversal:
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
}
Enhanced for loop:
for (int[] row : matrix) {
for (int val : row) {
[Link](val + " ");
}
}
Stored as an array of arrays internally.

Code:

Array Operations: Perform basic operations: insert, delete, sort, search on 1D and 2D arrays.

[Link] file:

Page 46
Output:

[Link] file:

Page 47
Output:

Page 48
Worksheet:

1. How can you convert a sentence (String) into an array of words in Java? Explain with an example.

2. What is the difference between [Link] and array[i].length in a 2D array?

3. What is a 1D array in Java, and how is it declared and initialized? How do you declare, initialize, and
access elements in a 2D array?

4. How are [Link]() and [Link]() used in Java, and what are the differences in their usage for
1D and 2D arrays?

5. How do you use [Link]() with [Link]() in Java, and what are its limitations
when sorting primitive and object arrays?

Page 49
LAB EXERCISE - 11
LAB EXERCISE NAME: Understanding String, StringBuilder and StringBuffer in Java

Learnings:

1. String (Immutable)

● Strings in Java are immutable (cannot be changed once created). Any


modification creates a new object in the String pool or [Link] synchronized
(safe for single-thread). Thread-safe automatically since value never changes.
● Common methods: length(), charAt(), substring(), toUpperCase(), toLowerCase(),
equals(), compareTo(), contains().

Example:
String s = "Hello";
[Link](" World"); // new object created, original "s" remains unchanged
[Link](s); // Output: Hello

2. StringBuilder (Mutable, Not Thread-Safe, Not Syncronized)

● Strings can be modified in place (no new object created). Multiple threads can
modify at the same time, risk of data corruption. Faster in single-threaded
programs. And Faster than StringBuffer.
● Common methods: append(), insert(), delete(), reverse(), replace().

Example:
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](sb); // Output: Hello World

Page 50
3. StringBuffer (Mutable, Thread-Safe, Synchronized)

● Same as StringBuilder but synchronized (safe in multithreading).


● Slightly slower than StringBuilder.

Example:
StringBuffer sbf = new StringBuffer("Hello");
[Link](" World");
[Link](sbf); // Output: Hello World.

Code:

String Handling: Manipulate strings using String, StringBuilder and StringBuffer, check if the
given string's palindromes.

Page 51
[Link] file:

Output:

Page 52
Worksheet:

1. Explain the difference between append(), insert(), replace(), and delete() methods in
StringBuilder/StringBuffer with examples.

2. Can a StringBuilder or StringBuffer object be converted to a String? How does this affect
immutability?

3. What happens internally when you concatenate multiple String objects using + in a loop? How can
StringBuilder improve performance in this scenario?

4. What is the String Pool in Java, and how does it affect memory management and string immutability?
Draw and explain how string literals and new String() objects are stored in heap and stack memory.

Page 53
LAB EXERCISE - 12
LAB EXERCISE NAME: Understanding Exception Handling in Java

Learnings:

1. Exceptions

● An exception is an unwanted event that occurs during program execution, disrupting the
normal flow of the program.
● Examples: dividing by zero, accessing array out of bounds, null reference.

2. Difference Between Error and Exception

● Error: Problems that cannot be handled in code (e.g., OutOfMemoryError,


StackOverflowError).
● Exception: Problems that can be handled using try-catch (e.g., IOException,
ArithmeticException).

3. Types of Exceptions

1. Checked Exceptions
○ Checked at compile-time.
○ Must be handled using try-catch or declared with throws.
○ Example: IOException, SQLException.

2. Unchecked Exceptions
○ Checked at runtime.
○ Example: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException.

4. Exception Handling Keywords

● try – block of code that may cause an exception.


● catch – block to handle the exception.
● finally – block that always executes (cleanup code like closing files).
● throw – used to explicitly throw an exception.
● throws – declares exceptions that a method can throw.

5. Custom Exceptions

● We can create our own exception by extending the Exception class.


● Useful when predefined exceptions don’t fit the requirement.

Example: InvalidAgeException for voting eligibility check.

Page 54
Code:

Voting Eligibility with Custom Exception: Create and throw InvalidAgeException if age is less
than 18.

[Link] file:

Output:

Page 55
Worksheet:

1. What is the purpose of try, catch, finally, and throw keywords in exception handling?

2. What is the difference between Exception, RuntimeException, and Error?

3. Can multiple exceptions be handled in a single catch block? Explain with an example.

4. What is the difference between throw and throws in Java?

5. Explain the difference between checked and unchecked exceptions with examples.

Page 56
LAB EXERCISE - 13
LAB EXERCISE NAME: Understanding Collections Framework in Java

Learnings:

1. Introduction

● Collections framework in Java is a unified architecture for storing and manipulating


groups of objects.
● Provides interfaces, classes, and algorithms to work with data structures.
● Replaces old data structures like Vector, Hashtable, Stack with more modern and flexible
ones.

2. Key Interfaces

● Collection Interface (root interface of the framework). Extended by List, Set, and
Queue.
● List – Ordered, allows duplicates (ArrayList, LinkedList, Vector, Stack).
● Set – Unordered, no duplicates (HashSet, LinkedHashSet, TreeSet).
● Queue – FIFO, supports element insertion/removal (PriorityQueue, ArrayDeque).
● Map (not part of Collection hierarchy, but in framework) – Key-Value pairs (HashMap,
TreeMap, LinkedHashMap, Hashtable).

3. Important Implementations

● ArrayList – Dynamic array, fast random access, slow insertion/deletion in middle.


● LinkedList – Doubly linked list, good for insertion/deletion, slower for random access.
● HashSet – Stores unique elements, unordered, uses hashing.
● TreeSet – Sorted set, elements in natural order.
● HashMap – Key-value pairs, no order guaranteed.
● LinkedHashMap – Maintains insertion order.
● TreeMap – Sorted key-value pairs.

4. Utility Classes

● Collections (utility class) – Provides static methods like sort(), reverse(), shuffle(), min(),
max().
● Arrays – Utility for working with arrays (conversion, sorting, searching).

Page 57
5. Advantages of Collections Framework

● Reduces programming effort – Ready-made data structures and algorithms.


● Increases performance – Efficient implementations of data structures.
● Interoperability – Common interfaces allow switching implementations easily.
● Thread-safety options – Legacy (Vector, Hashtable) are synchronized, and we can
make collections thread-safe using [Link]().

6. Differences

● Array vs Collection
○ Array: Fixed size, can hold both primitives & objects.
○ Collection: Dynamic size, can only hold objects.

● List vs Set vs Map


○ List: Allows duplicates, ordered.
○ Set: No duplicates, unordered (except LinkedHashSet).
○ Map: Key-value mapping, keys unique.

Page 58
Code:

Task Manager using ArrayList: Add, view, and remove tasks using ArrayList and enhanced
for-loops.

[Link] file:

Output:

Page 59
Student Directory with Collections: Use HashMap to store student data and HashSet to
ensure unique entries.

[Link] file:

Output:

Page 60
Worksheet:

1. What are the differences between ArrayList and LinkedList in terms of memory, performance, and use
cases.

2. How do PriorityQueue and Deque differ from other collection types? Give use cases.

3. Explain how Comparable and Comparator interfaces are used to sort collections. How do they differ in
flexibility and usage?

4. How do HashMap, LinkedHashMap, and TreeMap differ in terms of ordering, performance, and
internal implementation?

5. What is the difference between ListIterator and Iterator? Can ListIterator traverse backward?

Page 61
LAB EXERCISE - 14
LAB EXERCISE NAME: Understanding Generics, Wildcards, Iterators, Enhanced for-loop

Learnings:

Generics:

Generics enable type-safe programming in Java by allowing classes, interfaces, and methods to
operate on specific data types without requiring explicit typecasting. They provide compile-time
type checking and eliminate runtime type errors.

Syntax:

class ClassName<T> {
T obj;
void set(T obj) { [Link] = obj; }
T get() { return obj; }
}

Wildcards in Generics:

Wildcards (?) are used in generics to allow unknown types when defining methods, parameters,
or collections.

Types of Wildcards:
Type Syntax Description

Unbounded ? Any type is accepted.

Upper Bounded ? extends Type Accepts Type or its subclasses.

Lower Bounded ? super Type Accepts Type or its superclasses.

Iterator Interface:

Iterator is used to traverse elements of a collection sequentially (one by one). It belongs to the
[Link] package and provides fail-safe traversal.

Syntex: Iterator<Type> iteratorName = [Link]();

Important Methods:
hasNext() → Returns true if more elements exist
next() → Returns next element
remove() → Removes current element (optional)

Page 62
Enhanced For-loop:

The enhanced for-loop provides a simpler way to iterate over arrays or collections. It is a
read-only loop used when we do not need to modify or remove elements during traversal.

Syntex:

for (Type variable : collection) {


// use variable
}

Code:
Managing a Student Performance System: You are developing a small part of a Student
Performance Management System for a college. The system should handle lists of students
with their marks and provide a generic way to display and filter them using Generics, Wildcards,
Iterators, and Enhanced For-loop.

Page 63
Output:

Page 64
Worksheet:

1. Differentiate between ? extends and ? super wildcards in Generics. Give an example.

2. What is the purpose of the Iterator interface and how is it different from the enhanced for-loop?

3. How do Generics help prevent runtime type errors in Java?

4. What is the difference between generic classes and generic methods in Java? Can you give an example
of each?

5. What are the limitations of using an enhanced for-loop when working with collections, and how do
Generics and Wildcards affect these limitations?

Page 65
LAB EXERCISE - 14
LAB EXERCISE NAME: JDBC: Architecture, Connection, Statement, ResultSet, CRUD

Learnings:

JDBC (Java Database Connectivity) is an API (Application Programming Interface) that


enables Java programs to interact with databases. It provides methods to connect, execute
queries, and retrieve data from relational databases like MySQL, Oracle, PostgreSQL, etc.

JDBC architecture consists of two layers:

(A) JDBC API (Java Application Layer)

1. Provides classes and interfaces in the [Link] package.


2. Used by the Java application to send SQL queries and retrieve results.

(B) JDBC Driver Layer

1. Translates JDBC API calls into database-specific calls.


2. Each database requires a specific driver (e.g., MySQL Connector/J).

JDBC Components:

DriverManager → Manages database drivers and establishes a connection.


Connection → Represents a connection (session) with a database.
Statement / PreparedStatement → Used to execute SQL queries.
ResultSet → Represents the result of a query (data retrieved).

Page 66
Steps to Connect JDBC to Database:

Step 1: Load the driver class


[Link]("[Link]");
Step 2: Establish connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/studentdb", "root", "password");
Step 3: Create statement
Statement stmt = [Link]();

Step 4: Execute query


ResultSet rs = [Link]("SELECT * FROM students");
Step 5: Process results
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
Step 6: Close connection
[Link]();

CRUD Operations (Create, Read, Update, Delete)

A. INSERT (Create)
String query = "INSERT INTO students (id, name, marks) VALUES (1, 'Amit', 85)";
[Link](query);
[Link]("Record inserted successfully!");

B. SELECT (Read)
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]([Link]("id") + " " + [Link]("name") + " " + [Link]("marks"));
}

C. UPDATE
String query = "UPDATE students SET marks = 90 WHERE id = 1";
[Link](query);
[Link]("Record updated successfully!");

D. DELETE
String query = "DELETE FROM students WHERE id = 1";
[Link](query);
[Link]("Record deleted successfully!");

Page 67
Using PreparedStatement (Safer Approach)
String query = "INSERT INTO students (id, name, marks) VALUES (?, ?, ?)";
PreparedStatement ps = [Link](query);
[Link](1, 2);
[Link](2, "Riya");
[Link](3, 92);
[Link]();
[Link]("Record inserted safely using PreparedStatement!");

ResultSet Navigation Methods

[Link]() → Moves the cursor to the next record.


[Link]() → Moves the cursor to the previous record.
[Link]() → Moves the cursor to the first record.
[Link]() → Moves the cursor to the last record.

Code:

Managing Student Attendance Data Using JDBC CRUD Operations

The college wants to develop a Student Attendance Management System that stores and
manages attendance details in a MySQL database.
As a Java developer, your task is to design a console-based application using JDBC that can:

Connect to a database

1. Insert new student attendance records=


2. View all attendance records
3. Update attendance for a student
4. Delete a student record

[Link]

Page 68
[Link]:

Page 69
[Link]

Page 70
[Link]

Page 71
Worksheet:

1. Explain the architecture of JDBC. What are the main layers, and how does JDBC interact with the
database?

2. How do you establish a connection to a database in JDBC? What are the different types of JDBC
drivers, and how do they differ?

3. What is the difference between Statement, PreparedStatement, and CallableStatement in JDBC? When
should each be used?

4. What is a ResultSet in JDBC? Explain the different types of ResultSet and how cursor navigation
works.

Page 72
5. How do you perform Create, Read, Update, and Delete operations in JDBC? Explain the role of
executeQuery() and executeUpdate() methods.

Page 73

Common questions

Powered by AI

In Java, the 'extends' keyword is used to indicate that a class is inheriting from another class (or that an interface is extending another interface), enabling the subclass to inherit fields and methods from the superclass. This creates an 'is-a' relationship and supports single inheritance. Conversely, the 'implements' keyword is used by a class to implement the methods of an interface, promoting a 'can do' functionality by adhering to the interface's contract. While 'extends' is used when creating an extended hierarchy, 'implements' is employed when adopting additional behaviors, thus facilitating multiple inheritances through interfaces .

Method overriding in Java occurs when a subclass provides a specific implementation for a method already defined in its superclass. It is a key component of dynamic or runtime polymorphism, allowing method calls to be resolved at runtime based on the actual object's type. When overriding methods, the subclass must match the method signature of the superclass method, and the overridden method cannot have weaker access control. The parent method should be accessible in the child class, typically using public or protected access. The @Override annotation is used to indicate that a method is intended to override a method in a superclass .

The Scanner class in Java is primarily used for capturing input from the user. It provides various methods to read different types of data from different inputs such as the console, a file, or a string. Key methods include nextInt() for integers, nextDouble() for doubles, next() for reading a string of a single word, nextLine() for a full line of text, and others like nextBoolean(), nextFloat(), nextLong() for their respective data types .

Abstraction and encapsulation are two fundamental OOP concepts, though they serve different purposes. Abstraction is about hiding the implementation details and exposing only the essential features of an object. It is achieved using abstract classes and interfaces. Abstract classes provide a template with both abstract (without body) and concrete methods. Interfaces, on the other hand, offer a full abstraction since they can only contain method signatures. Encapsulation involves bundling the data (attributes) and the methods that operate on the data into a single unit or class, and restricting access to some of the object's components. This is typically achieved using private fields and public getters and setters .

Java handles type conversion through implicit and explicit conversions. Implicit type conversion occurs when a smaller data type is converted to a larger data type automatically by the compiler to prevent data loss, for example, converting an int to a long. Explicit type conversion, also known as casting, is done manually by the programmer to convert a larger data type to a smaller one or to enforce a specific conversion, potentially leading to data loss or truncation. The syntax for explicit conversion involves casting, such as (int) 3.14 to convert a float to an int .

Java Generics and Wildcards enhance type safety and code reusability by allowing operations on different data types while reducing code duplication. Generics enable the definition of classes, interfaces, and methods with a type parameter, promoting compile-time type checks and preventing type cast errors at runtime. For instance, a generic List<T> can be specified as List<Integer> or List<String>, enforcing type consistency. Wildcards, like <? extends T> and <? super T>, offer flexibility by allowing parameterized types to work with a range of data types; for example, a method with <? extends Number> can accept Integer, Double etc., ensuring type restrictions and variability .

The 'super' keyword in Java is used within a subclass to refer to the immediate parent class. It facilitates inheritance by allowing access to the parent class's variables and methods. For instance, if a method in a subclass needs to call the overridden method of the parent class, 'super.methodName()' can be used. This is particularly useful when specific functionalities in the parent method need to be retained. Additionally, when a subclass's constructor is invoked, 'super()' can be the first statement to explicitly call one of the parent class constructors, supporting constructor chaining. 'Super' helps overcome the limitation of directly accessing private fields and methods, enabling broader inheritance and code reusability .

Java prevents the ambiguity and complexity associated with multiple inheritance (inheritance from more than one parent class) by not allowing it with classes. Instead, Java uses interfaces to achieve a similar effect. An interface can be implemented by any number of classes, allowing them to define multiple, unrelated capabilities or functionalities. This way, Java achieves a form of multiple inheritance by enabling a class to implement multiple interfaces, which contain only method signatures. This avoids the problems linked to multiple inheritance by keeping the class hierarchy simple and straightforward .

JDBC (Java Database Connectivity) is a framework that allows Java applications to interact with databases. It operates primarily through two layers: the JDBC API and JDBC Driver. The JDBC API provides interfaces and classes for tasks like connecting to databases and executing SQL queries. The Driver Manager is responsible for managing database drivers and establishing connections with databases. Core components include Connection for maintaining a session with the database, Statement or PreparedStatement for executing SQL commands, and ResultSet for processing query results. This setup allows Java programs to perform CRUD operations efficiently with databases like MySQL or Oracle .

Iterators in Java are used to traverse through collections, providing a way to access each element sequentially without exposing the collection's underlying structure. The Iterator interface supports removal of elements through the remove() method, which the enhanced for-loop does not. While the enhanced for-loop provides a simplified syntax for iterating over collections (especially arrays), it is read-only, meaning it does not support removal or modification of elements during iteration. Furthermore, iterators can offer more control and flexibility, like checking for the presence of more elements with hasNext(), which aren't possible with the enhanced for-loop .

You might also like