Processmining Dharmateja-1
Processmining Dharmateja-1
on
JAVA FULLSTACK
BACHELOR OF TECHNOLOGY
in
Submitted by
Mudigonda Dharmateja (20501A05B9)
CERTIFICATE
This is to certify that the Internship Summary Report on “Java Fullstack” is the
bonafide work of MUDIGONDA DHARMATEJA (Regd. No. 20501A05B9), in
partial fulfillment of the requirements for the award of the degree of BACHELOR
OF TECHNOLOGY in COMPUTER SCIENCE AND ENGINEERING
submitted
during the academic year 2023-24.
1
ACKNOWLEDGEMENT
We are highly grateful and obliged for the most cooperative attitude of Dr. A.
JAYALAKSHMI, Head of Computer Science and Engineering Department in preparing
our internship.
We are thankful to our beloved Principal Dr. K. SIVAJI BABU for his encouragement
and the facilities provided to us.
We are also thankful to all our staff members for their valuable support for the
completion of the Internship.
Finally, we express our thanks to the members who directly and indirectly helped us in
completing this internship.
Mudigonda
Dharmateja
(20501A05B9)
2
INDEX
S. No. Contents Pg. No.
Introduction to Java
1 Flow of Java Program
4– 12
WORA features of Java
Java Installation
Introduction to datatypes
Type Casting
Reading Input
Object Oriented Programming
Constructors
Arrays
Conditional Statements
2 Strings 13– 19
Methods
Memory Management
Method Overloading
Looping Control Constructs
Encapsulation
Inheritance
SQL
3 Polymorphism 20 – 26
Abstraction
Abstract Class vs Interface
Static Keyword
Main Method
Exception Handling
4 Multithreading 27 – 30
Java Collections
Java Generics
Autoboxing
5 Java JDBC 31 – 33
Introduction to Frontend Technologies
Frontend – HTML
6 Java Hibernate 34 – 37
Frontend – CSS
7 Java Spring 38 – 42
Autowiring
Setter Injection – Constructor injection
Collection Injection
Frontend – JavaScript
8 Client-Server Architecture 43 – 46
MVC design patterns
Introduction to Springboot
3
Section-1
Introduction to Java
Java is a powerful and versatile programming language widely used for developing a variety of
applications, ranging from mobile apps to enterprise-level systems. Created by Sun
Microsystems (now owned by Oracle Corporation), Java was designed with the goal of being
platform-independent, meaning that Java programs can run on any device or operating system
that has the Java Virtual Machine (JVM) installed.
One of the key features of Java is its "write once, run anywhere" principle, which allows
developers to write code once and then run it on any platform without modification. This is
achieved through the use of the JVM, which translates Java bytecode into machine-specific
instructions at runtime.
Java is an object-oriented language, which means that it revolves around the concept of objects
and classes. Objects are instances of classes,
which act as blueprints for creating objects. This
object-oriented approach promotes modularity,
reusability, and flexibility in code development.
Java also emphasizes strong typing and automatic
memory management through its use of a garbage
collector, which automatically deallocates
memory when objects are no longer in use.
In addition to its core features, Java also boasts a
rich ecosystem of libraries, frameworks, and tools
that simplify and accelerate the development
process. Popular frameworks like Spring and
Hibernate provide solutions for building
enterprise applications, while tools like Maven
and Gradle streamline the build and dependency
management process.
Overall, Java's combination of portability, performance, and robustness has made it one of the
most widely used programming languages in the world, with applications spanning from
desktop software to web development, mobile apps, and beyond. In this document, we will
explore the fundamentals of Java programming, covering key concepts, syntax, and best
practices to help you become proficient in Java development.
The flow of a Java program follows a specific sequence of steps from its initialization to its
execution. Here's an overview of the typical flow of a Java program:
1. Source Code: The Java program begins with the source code written by the developer. This
source code is typically saved in files with a ".java" extension.
4
2. Compilation: The source code is then compiled
using the Java compiler (`javac`). During compilation,
the compiler checks the syntax of the code and
generates bytecode, which is a platform-independent
intermediate representation of the program. If there are
any syntax errors, the compiler will report them at this
stage.
5. Linking: After loading the bytecode, the JVM performs linking, which involves combining the
bytecode with the necessary runtime libraries and resolving references to other classes and
methods.
6. Initialization: Once the bytecode and its dependencies are linked, the JVM initializes the
program by executing the `main()` method of the class specified as the entry point of the program.
This is typically the class containing the `main()` method, which serves as the starting point for
program execution.
7. Execution: The `main()` method contains the code that defines the main logic of the program.
Java's "WORA" (Write Once, Run Anywhere) principle is one of its defining features, enabling
developers to write code that can run on any device or platform with a Java Virtual Machine
(JVM) installed. Here are some key aspects of Java's WORA features:
1. Platform Independence: Java achieves platform independence by compiling source code into
an intermediate bytecode format rather than directly into machine code. This bytecode can be
executed on any platform with a compatible JVM. As a result, Java programs can run unchanged
on diverse hardware and operating systems, including Windows, macOS, Linux, and various
embedded systems.
2. JVM Abstraction: The JVM serves as a layer of abstraction between Java bytecode and the
underlying hardware and operating system. It provides a consistent execution environment for
Java programs, regardless of the specifics of the underlying platform. The JVM interprets
bytecode or compiles it into native machine code using a just-in-time (JIT) compiler for improved
performance.
3. Standard Libraries: Java's standard libraries provide a comprehensive set of APIs for
5
common tasks such as I/O operations, networking, database access, graphical user interface (GUI)
development, and more. These libraries are part of the Java Development Kit (JDK) and are
available on all platforms where Java is supported. By relying on standard libraries, developers
can write code that remains portable across different environments.
5. Security and Sandbox Model: Java's WORA features are complemented by its robust security
model, which helps ensure that Java programs remain secure and reliable across different
environments. Java's security architecture includes features such as bytecode verification, class
loading restrictions, and a security manager that enforces access controls on various system
resources.
Java Installation
To install Java, follow these steps:
1. Download the appropriate Java Development Kit (JDK) for your operating system from the
official Oracle website.
2. Run the installer and follow the on-screen instructions to complete the installation process.
3. Set the JAVA_HOME environment variable to the directory where Java is installed.
4. Add the "bin" directory of the Java installation to the system PATH variable to enable access to
Java commands from the command line.
5. Verify the installation by opening a terminal or command prompt and typing "java -version" to
check the installed Java version.
6. Optionally, configure any additional settings or options based on your development needs.
Introduction to datatypes
In Java, data types define the type of data that can be stored in a variable. They specify the size
and format of the values that can be stored, as well as the operations that can be performed on
them. Various data types available in Java:
6
- Classes: User-defined data types that can contain both primitive and reference data types.
- Interfaces: Similar to classes but can only contain method signatures and constants.
- Enumerations (Enums): Special data types that consist of a fixed set of constants.
3. Wrapper Classes: Java provides wrapper classes for each primitive data type, allowing them
to be treated as objects. For example, `Integer` for int, `Double` for double, etc. These classes
provide utility methods for working with primitive data types in an object-oriented way.
4. String: Although not a primitive data type, strings are commonly used in Java to represent
sequences of characters. Java provides a built-in `String` class for creating and manipulating
strings.
Type Casting
Type casting in Java refers to the process of converting a value of one data type into another.
There are two types of type casting: implicit and explicit.
Type casting allows developers to manipulate and transform data of different types as needed within
a program. However, it's important to be cautious when performing explicit type casting, as it can
lead to loss of precision or unexpected behavior if not done carefully.
Reading Input
Reading input from the user is a common task in Java, especially when building interactive
console-based applications. There are several ways to read input in Java:
1. Using Scanner Class: The `Scanner` class is a convenient way to read input from various
sources, including the console, files, or strings. To read input from the console, you can create a
`Scanner` object and use its methods like `nextInt()`, `nextLine()`, etc.
Example:
7
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close(); // Remember to close the scanner
}
}
Example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your age: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("Your age is: " + age);
reader.close(); // Remember to close the reader
}
}
8
enables the creation of modular, reusable, and maintainable code. Object-oriented programming is
widely used in various domains, including software development, game development, and web
development, due to its flexibility, scalability, and code organization capabilities.
Constructors
Constructors in Java are special methods used for initializing objects of a class. They have the
same name as the class and do not have a return type, not even void. Constructors are called
implicitly when an object of the class is created using the `new` keyword. They can be used to
initialize instance variables, perform setup tasks, and ensure that the object is in a valid state.
1. Initialization: Constructors initialize the newly created object. They can initialize instance
variables, set default values, and perform other initialization tasks.
2. Default Constructor: If a class does not explicitly define any constructors, Java provides a
default constructor with no parameters. This constructor initializes instance variables to their
default values (0 for numeric types, null for reference types, false for boolean).
4. Constructor Overloading: Like methods, constructors can be overloaded, which means a class
can have multiple constructors with different parameter lists. Java determines which constructor
to call based on the arguments passed when creating an object.
6. No Return Type: Constructors do not have a return type, not even void. They are
automatically called when an object is created and cannot be invoked explicitly like regular
methods.
Example:
public class MyClass {
private int value;
// Parameterized constructor
public MyClass(int val) {
this.value = val;
}
public int getValue() {
return value;
}
9
public static void main(String[] args) {
// Creating an object of MyClass and initializing it using the constructor
MyClass obj = new MyClass(10);
System.out.println("Value: " + obj.getValue());
}
}
In this example, the constructor `MyClass(int val)` initializes the `value` instance variable with the
value passed as an argument. When an object of `MyClass` is created using `new MyClass(10)`, the
constructor is automatically called, setting the `value` to 10.
Arrays
Arrays in Java are used to store multiple values of the same data type under a single variable
name. They provide a way to group similar items together, making it easier to work with
collections of data. Here are some key points about arrays in Java:
1. Declaration and Initialization: Arrays are declared by specifying the data type of the
elements followed by square brackets `[]` and the array name. Arrays can be initialized either at
the time of declaration or later using the `new` keyword.
Example:
// Declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
2. Accessing Elements: Array elements are accessed using an index, which starts from 0 for the
first element and increments sequentially.
Example:
3. Length: The length of an array (the number of elements it can hold) is fixed and determined at
the time of initialization. The length of an array can be obtained using the `length` property.
Example:
int arrayLength = numbers.length;
4. Iterating Over Arrays: Arrays can be traversed using loops such as `for`, `while`, or
`foreach`.
Example:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
10
}
// Enhanced for loop (foreach)
for (int num : numbers) {
System.out.println(num);
}
6. Array Manipulation: Java provides various utility methods in the `java.util.Arrays` class for
sorting, searching, and manipulating arrays.
Example:
Arrays.sort(numbers); // Sort the array
int index = Arrays.binarySearch(numbers, 3); // Binary search
Arrays are a fundamental data structure in Java and are used extensively in programming to store
and manipulate collections of data efficiently. Understanding arrays and their operations is essential
for writing Java programs that deal with data in a structured manner.
Conditional Statement
Conditional statements in Java allow you to control the flow of your program based on certain
conditions. These statements help you make decisions and execute specific blocks of code
accordingly. Here are the main conditional statements in Java:
1. if Statement: The `if` statement evaluates a boolean expression and executes a block of code if
the condition is true.
Example:
int x = 10;
if (x > 5) System.out.println("x is greater than 5");
2. if-else Statement: The `if-else` statement executes one block of code if the condition is true and
another block if the condition is false.
Example:
int x = 10;
if (x > 5) System.out.println("x is greater than 5");
else System.out.println("x is not greater than 5");
3. else-if Statement: The `else-if` statement allows you to evaluate multiple conditions
sequentially.
Example:
int x = 10;
if (x > 10) System.out.println("x is greater than 10");
else if (x < 10) System.out.println("x is less than 10");
11
else System.out.println("x is equal to 10");
4. Nested if Statement:
You can nest `if` statements within other `if`, `else if`, or `else` statements to create more complex
conditions.
Example:
int x = 10;
if (x > 5)
if (x < 15)
System.out.println("x is between 5 and 15");
5. Switch Statement:The `switch` statement evaluates the value of an expression against a list of
case values and executes the corresponding block of code.
Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// More cases...
default:
System.out.println("Invalid day");
}
12
Section-2
Strings
Strings in Java represent sequences of characters and are widely used for storing and manipulating
textual data. Here are some key points about strings in Java:
1. String Declaration and Initialization: Strings can be created using the `String` class, which is
part of the `java.lang` package and is automatically imported into every Java program. Strings can
be declared and initialized using double quotes (`"`) to enclose the textual data.
Example:
String str1 = "Hello, world!";
String str2 = new String("Java is awesome!");
2. String Concatenation: String concatenation is the process of combining two or more strings into
a single string. In Java, string concatenation can be performed using the `+` operator.
Example:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // fullName will be "John Doe"
3. String Length: The length of a string (the number of characters it contains) can be obtained
using the `length()` method.
Example:
String str = "Hello";
int length = str.length(); // length will be 5
4. String Methods: The `String` class provides many methods for manipulating strings, such as
`charAt()`, `substring()`, `indexOf()`, `toUpperCase()`, `toLowerCase()`, `trim()`, `startsWith()`,
`endsWith()`, and many more.
Example:
String str = "Java Programming";
char firstChar = str.charAt(0); // firstChar will be 'J'
String subStr = str.substring(5); // subStr will be "Programming"
int index = str.indexOf('P'); // index will be 5
5. String Comparison: String comparison can be performed using the `equals()` method to check if
two strings have the same content, or using the `compareTo()` method to compare strings
lexicographically.
Example:
String str1 = "hello";
String str2 = "HELLO";
boolean isEqual = str1.equals(str2); // isEqual will be false
int result = str1.compareTo(str2); // result will be < 0
6. String Immutability: Strings in Java are immutable, meaning that their values cannot be
changed after they are created. Any operation that appears to modify a string actually creates a new
string object.
13
Example:
String str = "Hello";
str = str + " World"; // This creates a new string object
Methods
Methods in Java encapsulate a block of code that performs a specific task and can be invoked or
called from other parts of the program. They can have parameters and return values, providing
modularity and code reuse.
Example:
// Method definition
public static int add(int a, int b) {
return a + b;
}
// Method invocation
int result = add(5, 3); // result will be 8
In this example, the `add()` method takes two parameters (`a` and `b`), adds them together, and
returns the result. The method is then invoked with arguments `5` and `3`, and the returned value is
stored in the variable `result`.
Memory Management in Java involves automatic memory allocation and deallocation through
garbage collection. Method overloading, on the other hand, allows the definition of multiple
methods with the same name in a class, differentiating them by their parameter lists. This enables
developers to create functions with the same name but different behaviors.
Example:
public class Calculator {
// Method Overloading
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public String add(String str1, String str2) {
return str1 + str2;
}
}
In this example, the `add()` method is overloaded to handle integer addition, double addition, and
string concatenation. Java manages memory allocation for each method call and executes the
appropriate version of the method based on the arguments provided.
14
Looping Control Constructs
Looping control constructs in Java allow for repeated execution of a block of code based on a
specified condition. There are several looping constructs available in Java:
3. do-while Loop: Similar to the while loop but guarantees that the block of code is executed at
least once before checking the condition.
Example:
int i = 0;
do {
System.out.println("Iteration: " + i);
i++;
} while (i < 5);
4. Enhanced for Loop (for-each): Iterates over elements of an array or a collection without using
an explicit loop counter.
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number: " + num);
}
6. continue Statement: Skips the current iteration of the loop and proceeds to the next iteration.
Example:
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
Encapsulation is one of the four fundamental principles of object-oriented programming (OOP) and
is aimed at bundling data (attributes) and methods (functions) that operate on the data into a single
unit, called an object. Encapsulation helps in hiding the internal state of an object and only exposing
the necessary functionality through methods, thereby promoting modularity and information hiding.
1. Data Hiding: Encapsulation hides the internal state of an object from the outside world,
preventing direct access to its attributes. This protects the integrity of the data and ensures that it
can only be accessed and modified through defined methods.
2. Access Modifiers: In Java, access modifiers such as `private`, `protected`, and `public` are used
to control the access level of attributes and methods. By marking attributes as `private`, they can
only be accessed within the same class, while methods can provide controlled access to these
attributes through getters and setters.
3. Getters and Setters: Getters (accessor methods) and setters (mutator methods) are used to access
and modify the private attributes of a class, respectively. Getters allow read-only access to the
attributes, while setters enable controlled modification of the attributes, often including validation
logic.
4. Encapsulation Example:
Encapsulation promotes data integrity, code maintainability, and reusability by encapsulating data
and methods within objects and controlling access to them through well-defined interfaces. It is a
fundamental concept in OOP and is widely used in Java programming to create robust and modular
code.
Inheritance
1. Extending Classes: In Java, inheritance is achieved using the `extends` keyword, which allows a
subclass to inherit members (fields and methods) from a superclass. The subclass can then add new
members, modify existing ones, or inherit behavior directly from the superclass.
2. Superclass and Subclass: The superclass is the class being inherited from, while the subclass is
the class inheriting from the superclass. The subclass inherits all non-private members of the
superclass, including fields, methods, and constructors.
3. Access Modifiers: In Java, access modifiers such as `public`, `protected`, and `private` control
the visibility of members inherited from the superclass. Subclasses can access public and protected
members of the superclass, but not private members.
4. Method Overriding: Subclasses can override (redefine) methods inherited from the superclass to
provide specialized implementations. Method overriding allows subclasses to customize behavior
inherited from the superclass while maintaining a common interface.
5. Super Keyword: The `super` keyword in Java is used to refer to the superclass from within the
subclass. It can be used to access superclass members, invoke superclass constructors, and
distinguish between overridden methods and superclass methods.
6. Inheritance Example:
// Superclass
public class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
Inheritance promotes code reuse, modularity, and extensibility by allowing classes to inherit and
extend functionality from existing classes. It is a powerful mechanism in OOP and is widely used in
Java programming to create class hierarchies and organize code effectively.
SQL
SQL (Structured Query Language) is a standardized language used for managing and manipulating
relational databases. Here are some key concepts and commands in SQL:
2. Database:
A database is an organized collection of data, typically stored and accessed electronically from a
computer system. It consists of one or more tables, each containing rows and columns of data.
3. Tables:
A table is a collection of related data organized in rows and columns. Each row represents a
record, and each column represents a field or attribute. Tables are created using the `CREATE
TABLE` statement.
7. SQL Queries:
SQL queries are statements used to retrieve specific data from a database.
18
The `SELECT` statement is the most commonly used SQL query for retrieving data from one or
more tables based on specified criteria.
8. Constraints:
-Constraints are rules that enforce data integrity and consistency in the database. Common
constraints include:
`PRIMARY KEY`: Ensures uniqueness of values in a column.
`FOREIGN KEY`: Establishes a relationship between two tables.
`NOT NULL`: Specifies that a column cannot contain null values.
`UNIQUE`: Ensures that all values in a column are unique.
9. Joins:
Joins are used to combine rows from two or more tables based on a related column between them.
Common types of joins include:
`INNER JOIN`: Returns only the rows that have matching values in both tables.
`LEFT JOIN` (or `LEFT OUTER JOIN`): Returns all rows from the left table and matching rows
from the right table.
`RIGHT JOIN` (or `RIGHT OUTER JOIN`): Returns all rows from the right table and matching
rows from the left table.
`FULL JOIN` (or `FULL OUTER JOIN`): Returns all rows when there is a match in either table.
SQL is a powerful language for managing and querying relational databases, and mastering its
concepts and commands is essential for database administrators, developers, and data analysts.
Section-3
19
Polymorphism
1. Method Overriding:
- Polymorphism is often achieved through method overriding, where a subclass provides a
specific implementation of a method that is already defined in its superclass.
- The subclass method must have the same signature (name and parameters) as the superclass
method it overrides.
2. Dynamic Binding:
- Polymorphism allows the selection of the appropriate method implementation at runtime,
based on the actual type of the object rather than the reference type.
- This is achieved through dynamic binding, where the JVM determines the appropriate method
implementation to invoke at runtime.
3. Common Interface:
- Polymorphism relies on the concept of a common interface, where objects of different classes
share a common set of methods declared in a superclass or interface.
- This allows objects to be treated uniformly, simplifying code and promoting modularity and
extensibility.
Example:
// Superclass
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass 1
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
// Subclass 2
class Cat extends Animal {
@Override
20
public void makeSound() {
System.out.println("Cat meows");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
In this example, both `Dog` and `Cat` classes inherit from the `Animal` superclass and override
the `makeSound()` method with their specific implementations. When `makeSound()` is called on
objects of type `Dog` and `Cat`, the JVM dynamically binds the appropriate method
implementation based on the actual object type, demonstrating polymorphic behavior.
Polymorphism promotes code reuse, flexibility, and maintainability by allowing objects to exhibit
different behaviors based on their specific types while adhering to a common interface. It is a key
concept in OOP and is widely used in Java programming to create flexible and extensible code.
Abstraction
3. Encapsulation of Complexity:
- Abstraction encapsulates complexity by providing a simplified and unified interface to interact
with complex systems.
- It allows users to interact with objects through well-defined interfaces, hiding the internal
workings and implementation details of the system.
Example:
// Abstract class representing a Shape
abstract class Shape {
// Abstract method to calculate area
public abstract double calculateArea();
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Main class
public class Main {
public static void main(String[] args) {
// Creating a Circle object
Circle circle = new Circle(5.0);
22
Abstract classes and interfaces are both mechanisms in Java for achieving abstraction, but they
serve different purposes and have distinct characteristics.
Abstract classes are classes that cannot be instantiated on their own and may contain both abstract
(unimplemented) and concrete (implemented) methods. They are typically used when you want to
define a common superclass for a group of related classes, providing default behavior that
subclasses can inherit and override as needed. Abstract classes can have constructors and instance
variables, and they can also contain method implementations. They serve as a blueprint for other
classes to inherit from, allowing for code reuse and promoting consistency among subclasses.
On the other hand, interfaces in Java define a contract or set of methods that a class must
implement, but they do not provide any method implementations themselves. Interfaces cannot
have constructors or instance variables; they only define method signatures (names, parameters,
and return types). Classes can implement multiple interfaces but can only extend one superclass.
Interfaces are often used to define common behavior across unrelated classes, enabling
polymorphism and facilitating loose coupling between components in a system. They serve as a
way to enforce a certain behavior without prescribing any specific implementation details.
In summary, abstract classes provide a way to define a common superclass with both abstract and
concrete methods, while interfaces define a contract for classes to implement without providing
any method implementations themselves. Abstract classes are used to create a hierarchy of related
classes with shared behavior, while interfaces define a common set of methods that unrelated
classes can implement to achieve polymorphic behavior. Both mechanisms are important tools for
achieving abstraction and designing flexible, maintainable Java applications.
Static Keyword
The `static` keyword in Java is used to define members (variables and methods) that belong to the
class itself, rather than to instances of the class. It can be applied to variables, methods, and nested
classes, but not to top-level classes.
1. Static Variables:
Static variables, also known as class variables, are shared among all instances of a class.
They are initialized only once, at the start of the program's execution, and retain their values
throughout the program's lifetime. Static variables are accessed using the class name, rather than
through instances of the class.
Example:
public class MyClass {
public static int count = 0; // Static variable
}
2. Static Methods:
Static methods belong to the class rather than to any specific instance. They can be called
directly using the class name, without the need to create an object of the class. Static methods
cannot access instance variables or call instance methods directly, as they are not associated with
any specific instance.
Example:
23
public class MyClass {
public static void printMessage() { // Static method
System.out.println("Hello, world!");
}
}
3. Static Blocks:
Static blocks are used to initialize static variables or perform any other one-time initialization
tasks for the class. They are executed only once when the class is loaded into memory, before any
instances of the class are created or any static methods are called.
Example:
public class MyClass {
static {
System.out.println("Static block executed");
}
}
The `static` keyword is commonly used in Java to define members that are shared among all
instances of a class or to perform class-level initialization tasks. It promotes code efficiency,
memory management, and organization by providing a way to define class-level members and
behaviors.
Main Method
The `main` method in Java is the entry point of any Java program. It is the method that the Java
Virtual Machine (JVM) looks for when starting the execution of a Java program. The `main`
method has a specific signature and is where the execution of the program begins.
The `main` method must be declared with the following signature:
public static void main(String[] args)
It is a `public` method so that the JVM can access it from outside the class. It is a `static` method
because it belongs to the class rather than to any specific instance.
The `main` method accepts a single parameter of type `String[]`, which represents the command-
line arguments passed to the program. The `args` parameter allows the program to receive input
from the command line when it is executed. The `main` method has a `void` return type,
indicating that it does not return any value. When a Java program is executed, the JVM looks for
24
the `main` method in the specified class. The `main` method is invoked automatically by the JVM
to start the execution of the program.
In this example, the `HelloWorld` class contains a `main` method that prints "Hello, world!" to
the console. When this program is executed, the JVM locates the `main` method in the
`HelloWorld` class and starts the execution of the program from there.
Exception Handling
Exception handling in Java is a mechanism that allows developers to gracefully handle runtime
errors and exceptional situations that may occur during program execution. By handling
exceptions, you can prevent the program from crashing and provide alternative flows or error
messages to the user.
Types of Exceptions:
- Java distinguishes between two types of exceptions: checked exceptions and unchecked
exceptions.
- Checked exceptions are checked at compile time and must be either caught by a `try-catch`
block or declared in the method signature using the `throws` keyword.
- Unchecked exceptions (runtime exceptions) are not checked at compile time and can be caught
or left unhandled.
try-catch Block:
The `try-catch` block is used to catch and handle exceptions that occur within a block of code.
The `try` block contains the code that may throw an exception, and the `catch` block handles the
exception if it occurs. Multiple `catch` blocks can be used to handle different types of exceptions.
try {
// Code that may throw an exception
} catch (ExceptionType1 ex) {
// Handle ExceptionType1
} catch (ExceptionType2 ex) {
// Handle ExceptionType2
} finally {
// Optional finally block for cleanup code
}
throws Keyword:
The `throws` keyword is used in method declarations to indicate that the method may throw
25
certain types of exceptions. It delegates the responsibility of handling the exception to the caller
of the method.
Example:
public void method() throws SomeException {
// Code that may throw SomeException
}
finally Block:
The `finally` block is used to execute cleanup code that should always be executed, regardless
of whether an exception occurs or not. It is typically used to release resources such as file handles,
database connections, etc.
try {
// Code that may throw an exception
} catch (Exception ex) {
// Handle the exception
} finally {
// Cleanup code that always executes
}
Custom Exceptions:
In addition to built-in exceptions, developers can define custom exception classes to represent
specific error conditions in their applications. Custom exceptions should extend the `Exception`
class or one of its subclasses.
Exception handling is a critical aspect of Java programming, as it helps to create robust and
reliable applications that gracefully handle errors and unexpected situations. Proper exception
handling can improve the stability and user experience of your software.
Section-4
26
Multithreading
Multithreading in Java refers to the ability of a Java program to execute multiple threads
concurrently, allowing it to perform multiple tasks simultaneously. Multithreading is a powerful
technique for improving the responsiveness and efficiency of applications, especially in scenarios
where tasks can be executed independently or concurrently.
2. Creating Threads:
Threads in Java can be created in two ways: by extending the `Thread` class or by implementing
the `Runnable` interface.
Example of extending the `Thread` class:
class MyThread extends Thread {
public void run() {
// Thread execution logic
}
}
Example of implementing the `Runnable` interface:
class MyRunnable implements Runnable {
public void run() {
// Thread execution logic
}
}
4. Thread States:
Threads in Java can be in various states, such as new, runnable, blocked, waiting, timed waiting,
or terminated. The `Thread` class provides methods to query and manipulate the state of a thread.
5. Thread Synchronization:
Multithreading introduces the risk of race conditions and data inconsistencies when multiple
threads access shared resources concurrently. Thread synchronization mechanisms such as
synchronized blocks and locks are used to ensure that only one thread can access a critical section
of code at a time, preventing data corruption and maintaining consistency.
27
6. Thread Pools:
Thread pools are a collection of pre-initialized threads that can be reused to execute tasks.
They improve performance and resource management by reducing the overhead of creating and
destroying threads for each task. Java provides the `Executor` framework and related classes in
the `java.util.concurrent` package for managing thread pools and executing concurrent tasks.
Multithreading in Java allows developers to harness the power of modern multi-core processors
and build responsive, scalable, and efficient applications that can handle concurrent tasks
effectively. However, it also introduces complexities such as thread synchronization and
coordination, which must be carefully managed to ensure the correctness and reliability of
multithreaded programs.
Java Collections
Java collections provide a framework for storing and manipulating groups of objects. They offer a
wide range of data structures and algorithms to suit different requirements, making it easier to
work with data in Java applications. Java collections are part of the Java Collections Framework
(JCF), which includes interfaces, implementations, and algorithms for working with collections.
1. Interfaces:
- The Java Collections Framework defines several core interfaces that represent different types
of collections:
- `Collection`: The root interface in the collection hierarchy, representing a group of objects.
- `List`: An ordered collection that allows duplicate elements.
- `Set`: A collection that contains no duplicate elements.
- `Map`: A mapping between keys and values, where each key is associated with exactly one
value.
- `Queue`: A collection designed for holding elements prior to processing, typically following
the FIFO (first-in, first-out) order.
2. Implementations:
- The Java Collections Framework provides concrete implementations of the core interfaces:
- `ArrayList`, `LinkedList`, and `Vector` are implementations of the `List` interface.
28
- `HashSet`, `LinkedHashSet`, and `TreeSet` are implementations of the `Set` interface.
- `HashMap`, `LinkedHashMap`, and `TreeMap` are implementations of the `Map` interface.
- Various implementations are available for the `Queue` interface, such as `ArrayDeque` and
`PriorityQueue`.
3. Utility Classes:
- The `Collections` class provides static methods for working with collections, such as sorting,
searching, and synchronizing collections.
- The `Arrays` class provides static methods for working with arrays, including converting
arrays to collections and vice versa.
4. Iterators:
- Iterators are used to traverse elements in a collection sequentially.
- Each collection class provides an iterator through which elements can be accessed
sequentially, allowing for easy iteration over the elements in the collection.
Java collections are widely used in Java programming for tasks such as data storage,
manipulation, iteration, and searching. They provide efficient and flexible data structures that can
be tailored to specific application requirements, making them an essential part of Java
development.
Java Generics
Java generics allow you to create classes, interfaces, and methods that operate on a type
parameter, enabling you to write more flexible and reusable code. With generics, you can define
classes and methods that work with any data type, providing type safety and reducing the need for
explicit type casting.
public T getValue() {
return value;
}
}
29
Box<String> stringBox = new Box<>();
stringBox.setValue("Hello");
String stringValue = stringBox.getValue(); // No need for type casting
In this example, the `Box` class is defined with a type parameter `T`, allowing it to work with any
data type. Instances of `Box` can be created with specific types (e.g., `Integer`, `String`),
providing type safety and eliminating the need for explicit type casting when retrieving values.
Generics promote code reuse and enhance the readability and maintainability of Java code.
Autoboxing
Autoboxing is a feature introduced in Java that automatically converts primitive data types into
their corresponding wrapper classes (e.g., `int` to `Integer`, `double` to `Double`) and vice versa
when needed. This feature simplifies code by eliminating the need for manual conversion between
primitives and their wrapper classes, making code more concise and readable. Autoboxing occurs
implicitly during assignments, method calls, and expressions involving primitive types and their
corresponding wrapper classes.
Example:
// Autoboxing: primitive int to Integer
int num = 10;
Integer integerNum = num; // Autoboxing
In the example, autoboxing occurs when assigning a primitive `int` to an `Integer` and a primitive
`double` to a `Double`. Similarly, unboxing occurs when assigning an `Integer` to a primitive `int`
and a `Double` to a primitive `double`. Autoboxing and unboxing help to streamline code and
enhance readability, especially in scenarios where primitive types and their corresponding
wrapper classes are used interchangeably.
Section-5
30
Java JDBC
1. Introduction to JDBC:
Java JDBC is a Java API for connecting and executing queries against a database. It provides a
standard interface for accessing relational databases from Java programs, allowing developers to
interact with databases such as MySQL, Oracle, PostgreSQL, and more. JDBC enables database-
independent connectivity, making it possible to write database applications that can seamlessly
switch between different database vendors without code changes.
2. JDBC Architecture:
31
- ResultSet: Represents the result of a database query and provides methods for iterating over
the results and accessing individual columns.
3. Stablishing Connection:
To establish a connection to a database using JDBC, you need to follow these steps:
- Load the appropriate JDBC driver using `Class.forName()` or
`DriverManager.registerDriver()` method.
- Obtain a connection to the database using `DriverManager.getConnection()` method,
specifying the database URL, username, and password.
- Close the connection when finished using `Connection.close()` method to release resources.
4. Executing Queries:
After establishing a connection, you can execute SQL queries against the database using
`Statement`, `PreparedStatement`, or `CallableStatement`.
- Use `Statement` for simple SQL queries.
- Use `PreparedStatement` for precompiled SQL queries with parameters to prevent SQL
injection attacks and improve performance.
- Use `CallableStatement` for executing stored procedures.
5. Handling ResultSets:
ResultSets are returned when executing SELECT queries and allow you to retrieve and process
the query results. You can iterate over the ResultSet using `next()` method to move to the next
row and retrieve column values using getter methods such as `getInt()`, `getString()`, etc. Make
sure to close the ResultSet, Statement, and Connection objects after use to release database
resources and prevent memory leaks.
Frontend – HTML
HTML (Hypertext Markup Language) is the standard language used to create and design web
pages. It consists of a set of markup tags that define the structure and content of a web page. Basic
HTML tags include:
`<html>`: Defines the root of an HTML document.
`<head>`: Contains metadata, such as the page title and links to stylesheets and scripts.
`<title>`: Sets the title of the web page displayed in the browser's title bar.
32
`<body>`: Contains the visible content of the web page.
`<h1>` to `<h6>`: Defines headings of different sizes, with `<h1>` being the largest and
`<h6>` being the smallest.
`<p>`: Represents a paragraph of text.
`<a>`: Creates hyperlinks to other web pages or resources.
`<img>`: Inserts images into the web page.
`<ul>` and `<ol>`: Define unordered and ordered lists, respectively.
`<li>`: Represents list items within `<ul>` or `<ol>`.
These tags form the foundation of HTML documents and are used to structure content, create
links, display images, and organize information on web pages.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My web page</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is my first web page.</p>
<p>It contains a
<strong>main heading</strong> and <em> paragraph </em>.
</p>
</body>
</html>
Output:
Section-6
33
Java Hibernate
Example:
using Hibernate to map a Java class to a database table and perform CRUD operations:
Suppose we have a Java class `Student` that we want to map to a database table called `students`,
which has columns for `id`, `name`, and `age`.
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
34
private String name;
private int age;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// Create session
Session session = factory.getCurrentSession();
try {
// Create a student object
Student student = new Student();
student.setName("John");
student.setAge(25);
// Start a transaction
session.beginTransaction();
// Save the student object to the database
session.save(student);
// Commit the transaction
session.getTransaction().commit();
System.out.println("Student saved with id: " + student.getId());
// Retrieve the student from the database
session = factory.getCurrentSession();
session.beginTransaction();
Frontend – CSS
CSS (Cascading Style Sheets) is a powerful styling language used to control the presentation and
layout of web pages. It allows developers to customize the appearance of HTML elements, such
as text, images, and layout, making websites visually appealing and user-friendly.
These CSS attributes play a crucial role in styling web pages and creating visually appealing
layouts. By using them effectively, developers can achieve desired design outcomes and enhance
the user experience of their websites.
37
Section-7
Java Spring
Spring is a powerful and widely-used framework for building Java applications, particularly web
applications. It provides comprehensive infrastructure support and a rich set of features for
developing robust and scalable applications.
1. Dependency Injection (DI): Spring's DI container manages the creation and injection of objects,
promoting loose coupling and facilitating easier testing and maintenance.
3. Spring MVC: Spring MVC is a web framework built on top of the Spring framework,
providing a model-view-controller architecture for developing web applications. It simplifies the
development of web applications by providing features like handler mapping, view resolution,
and data binding.
5. Integration with Other Technologies: Spring seamlessly integrates with various Java EE
technologies such as Hibernate, JPA, JMS, and JDBC, as well as third-party frameworks like
Thymeleaf, Apache Tiles, and more.
6. Testing Support: Spring's testing framework facilitates unit testing and integration testing of
Spring applications, providing features like the Spring TestContext Framework and mock objects
for easier testing.
38
Autowiring
Autowiring is a feature of the Spring framework that automatically injects dependencies into
Spring-managed beans. It reduces the need for explicit configuration of bean dependencies,
making the code more concise and readable. Autowiring can be configured using annotations or
XML-based configuration. Spring supports several autowiring modes:
1. ByType: Spring looks for a single bean of the same type as the dependency and injects it. If
multiple beans of the same type are found, an error occurs.
2. ByName: Spring matches the name of the dependency with the bean's name and injects it. If no
bean with the matching name is found, an error occurs.
Setter Injection and Constructor Injection are two common approaches for injecting dependencies
into Spring-managed beans.
1. Setter Injection:
Setter Injection involves injecting dependencies using setter methods. In this approach, Spring
invokes setter methods on the bean after it has been instantiated and before it is put into service.
Example:
public class MyService {
private MyDependency dependency;
// Setter method for dependency injection
public void setDependency(MyDependency dependency) {
this.dependency = dependency;
}
}
39
This configuration tells Spring to inject the `MyDependency` bean into the `MyService` bean
using the `setDependency()` method.
2. Constructor Injection:
Constructor Injection involves injecting dependencies through constructor arguments. In this
approach, dependencies are provided to the constructor when the bean is created.
Example:
public class MyService {
private MyDependency dependency;
This configuration tells Spring to inject the `MyDependency` bean into the `MyService` bean
through its constructor.
Both Setter Injection and Constructor Injection have their advantages and use cases. Constructor
Injection is generally preferred for mandatory dependencies, while Setter Injection is more
suitable for optional dependencies or when the number of dependencies is large. Choose the
approach that best fits the requirements and design of your application.
Collection Injection
Collection Injection in Spring involves injecting a collection of objects (such as lists, sets, or
maps) into a Spring-managed bean. This allows for the injection of multiple dependencies of the
same type into a single bean. Spring provides support for injecting collections through XML-
based configuration or annotations.
1. List Injection:
List Injection involves injecting a list of objects into a bean. Each element in the list represents a
dependency.
Example using XML-based configuration:
2. Set Injection:
Set Injection involves injecting a set of objects into a bean. Each element in the set represents a
unique dependency.
Example:
3. Map Injection:
Map Injection involves injecting a map of objects into a bean, where each entry in the map
consists of a key-value pair. Here's an example using XML-based configuration:
<bean id="myBean" class="com.example.MyBean">
<property name="myMap">
<map>
<entry key="key1" value-ref="dependency1"/>
<entry key="key2" value-ref="dependency2"/>
</map>
</property>
</bean>
<bean id="dependency1" class="com.example.Dependency1"/>
<bean id="dependency2" class="com.example.Dependency2"/>
Collection Injection in Spring provides flexibility and allows for the injection of multiple
dependencies into a single bean, catering to various use cases in application development. Choose
the appropriate collection type based on your requirements and design considerations.
Frontend – JavaScript
41
JavaScript is a versatile scripting language used for adding interactivity and dynamic behavior to
web pages. It runs client-side in web browsers, enabling developers to manipulate HTML
elements, handle user events, and make asynchronous requests to servers.
JavaScript is essential for creating interactive web applications. It enables developers to respond
to user actions, validate input, manipulate the DOM, and make AJAX requests, enhancing the
user experience.
Important Functionalities:
1. Manipulating HTML Elements:
Section-8
42
Client-Server Architecture
1. Client-Side Technologies:
- Java Swing or JavaFX: For building desktop applications with graphical user interfaces
(GUIs).
- Android: For developing mobile applications for Android devices using Java.
2. Server-Side Technologies:
- Java Servlets: Server-side Java programs that handle HTTP requests and generate HTTP
responses. They are commonly used in web applications.
- Java EE (Enterprise Edition) / Jakarta EE: A collection of Java APIs and specifications for
building enterprise applications, including servlets, JSP, EJB, JPA, and more.
- Spring Framework: A comprehensive framework for building Java enterprise applications,
providing support for dependency injection, MVC architecture, and various other features.
3. Communication Protocols:
- HTTP/HTTPS: Used for communication between web clients (browsers or other HTTP
clients) and web servers.
- TCP/IP: A low-level networking protocol used for communication between Java applications
over the internet or a local network.
4. Deployment Options:
43
- Standalone Applications: Java applications that run independently on a user's device without
requiring a server.
- Web Applications: Java applications deployed on web servers (such as Apache Tomcat, Jetty,
or JBoss) that serve requests from clients over the internet or an intranet.
Introduction to Springboot
44