0% found this document useful (0 votes)
24 views

JAVA Internship

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

JAVA Internship

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

1 BASIC-JAVA  Java Introduction

 JDK JRE JVM


 Java Syntax
 Java Output
 Java Comment

2 BASIC-JAVA  Java Variable, Data


Type.
 Java operation
 Java String
3 BASIC-JAVA  Java Conditions
 Java Loop
4 BASIC –JAVA  Java Break/continue
 Java Array
5 CORE-JAVA  Java Methods
6 CORE-JAVA  OPPS Intro
 Classes/Objects
7 CORE-JAVA  Class Attributes
 Class Methods
 Constructors
 Modifiers
8 CORE-JAVA  Inheritance
9 CORE-JAVA  Encapsulation
10 CORE-JAVA  Polymorphism
11 CORE-JAVA  Abstraction
 Interface
12 CORE-JAVA  LIST&Map
 Wrapper class
 Exception handling
 Multi Threading
13 GUI  Java Swing
 JDBC
14 J2EE  Servlet
 Hibernate
15 FRAMEWORK  Spring & Spring Boot
DAY-1
Java Introduction:
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of
Oracle) in the year 1995. James Gosling is known as the father of Java.
Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to
Java.
Platform: Any hardware or software environment in which a program runs,
is known as a platform. Since Java has a runtime environment (JRE) and API,
it is called a platform.

JDK JRE JVM:


JDK (Java Development Kit):
The JDK is a software development kit used for developing Java
applications. It includes a set of tools and libraries that developers need to
create, compile, and run Java programs. The JDK includes the Java Runtime
Environment (JRE), an interpreter/loader (Java), a compiler (javac), an
archiver (jar), a documentation generator (Javadoc), and other tools
needed for Java development. In summary, if you're a Java developer, you
typically install the JDK on your machine.

JRE (Java Runtime Environment):


The JRE is a part of the JDK but can also be installed separately. It provides
the minimum requirements for executing a Java application. It includes the
Java Virtual Machine (JVM), core classes, and supporting files needed to run
Java applications. The JRE does not contain the tools and utilities like the
compiler and debugger that developers need. If you only want to run Java
applications and don't intend to develop them, you can install the JRE.

JVM (Java Virtual Machine):


The JVM is a virtual machine that enables a computer to run Java programs.
It abstracts the hardware and operating system details, providing a
consistent environment for Java applications to run on any device or
platform. When you compile a Java program, it is translated into an
intermediate form called bytecode. The JVM then interprets and executes
this bytecode. The JVM is a crucial component of the Java platform, as it
allows "write once, run anywhere" (WORA) capability, meaning that Java
programs can run on any device or operating system with a compatible
JVM.

In summary:
JDK: For Java developers, includes JRE and development tools.
JRE: For end-users who want to run Java applications.
JVM: Executes Java bytecode and provides a platform-independent runtime
environment. It is included in both the JDK and JRE.

Java Syntax:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Java Output:
In Java, the output of a program is typically produced using the System.out
stream, which is an instance of the PrintStream class. The most common
method for output is System.out.println().

Here's a simple breakdown:


System:
System is a pre-defined class in the java.lang package.
It provides access to the standard input, output, and error streams of the
host environment.

Out:
out is a public static member of the System class and is of type PrintStream.
PrintStream is a class that provides methods to print formatted
representations of objects to a text-output stream.
println():
println() is a method of the PrintStream class.
It is used to print a line of text to the output stream and then terminate the
line by writing the line separator string.
It can be used with various data types, and it automatically adds a newline
character at the end.

Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Java Comment:
In Java, comments are used to add explanatory notes or remarks within the
source code. Comments are ignored by the compiler and do not affect the
execution of the program. They serve the purpose of making the code more
understandable for developers or providing information about the code.

There are two types of comments in Java:

Single-Line Comments:

Single-line comments start with //.

Everything on the line after // is treated as a comment.

Example:

// This is a single-line comment


int x = 5; // This is also a comment at the end of a line
Multi-Line Comments:

Multi-line comments are enclosed between /* and */.

Everything between these symbols is considered a comment, even if it


spans multiple lines.
Example:
/*
* This is a multi-line comment.
* It can span multiple lines.
*/
int y = 10;

DAY-2
Java Variable:

A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
There are two types of data types in Java: primitive and non-primitive.

Types of Variables:

There are three types of variables in Java:


 local variable.
 instance variable.
 static variable.

1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.


2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is


not shared among instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

Example:

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Data Type:

In Java, data types define the type of data that a variable can hold. Java is a
statically-typed language, which means that you must declare the type of a
variable before using it. The language provides a variety of data types to
accommodate different kinds of values. Here are some of the primary data
types in Java:

Primitive Data Types:


These are the most basic data types directly supported by Java. They are
not objects and are stored directly in memory.

Numeric Types:
byte: 8-bit signed integer.
short: 16-bit signed integer.
int: 32-bit signed integer.
long: 64-bit signed integer.
float: 32-bit floating-point number.
double: 64-bit floating-point number.

Reference Data Types:


These data types are used to refer to objects. Unlike primitive types, they
are not stored directly in memory but instead hold references (addresses)
to objects.

Object Types:
String: Represents a sequence of characters (text).
Array: Represents an ordered collection of elements.
Example:

String greeting = "Hello, World!";


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

Java operation:

In Java, operators are special symbols or keywords that perform operations


on operands. Operands can be variables, literals, or expressions. Java
supports a wide range of operators, and they can be categorized into
several types:

Arithmetic Operations:
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%) - Returns the remainder of a division.

Example:
int a = 10;
int b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus

Assignment Operations:
Assigns a value to a variable.
int x = 10;

Comparison Operations:
Compare two values and return a boolean result.
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)

Example:
int p = 10;
int q = 20;
boolean isEqual = (p == q);
boolean isNotEqual = (p != q);
boolean isGreaterThan = (p > q);
boolean isLessThan = (p < q);

Logical Operations:
Combine boolean values using logical operators.
AND (&&)
OR (||)
NOT (!)

Example:
boolean condition1 = true;
boolean condition2 = false;
boolean resultAND = condition1 && condition2;
boolean resultOR = condition1 || condition2;
boolean resultNOT = !condition1;

Increment and Decrement Operations:


Increase or decrease the value of a variable by 1.
Increment (++)
Decrement (--)

Example:
int count = 5;
count++; // Increment by 1
count--; // Decrement by 1
Bitwise Operations:
Perform operations at the bit level.
AND (&)
OR (|)
XOR (^)
NOT (~)
Left shift (<<)
Right shift (>>)

Example:
int num1 = 5;
int num2 = 3;
int bitwiseAND = num1 & num2;
int bitwiseOR = num1 | num2;
int bitwiseXOR = num1 ^ num2;
int bitwiseNOT = ~num1;

Java String:

In Java, a String is a class that represents a sequence of characters. It is part


of the java.lang package and is one of the most commonly used classes in
Java. The String class is immutable, which means that once a String object is
created, its value cannot be changed.

Here are some key features and aspects of Java strings:


Declaration and Initialization:
You can declare and initialize a string in Java using the following methods:
Example:
// Using String literal
String str1 = "Hello, World!";

// Using the new keyword


String str2 = new String("Hello, World!");

Immutable Nature:
Once a String object is created, its value cannot be modified. If you want to
modify a string, a new string object is created.

Example:
String original = "Hello";
String modified = original.concat(", World!"); // creates a new string

String Pool:
Java maintains a special memory area called the "String pool" to store
string literals. When you create a string using a literal, Java checks the pool
first. If the string already exists, the existing reference is returned, reducing
memory usage.

Example:
String str1 = "Hello"; // goes to the string pool
String str2 = "Hello"; // reuses the existing string from the pool
String Concatenation:
Strings can be concatenated using the + operator or the concat() method.

Example:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // or use concat method.

String Methods:
The String class provides a variety of methods for working with strings,
including:
length():
Returns the length of the string.
charAt(index):
Returns the character at the specified index.

substring(startIndex, endIndex):
Returns a substring based on the specified indices.

equals(otherString):
Compares two strings for equality.

toUpperCase() and toLowerCase():


Returns a new string in uppercase or lowercase.
Many more...

Example:
String str = "Java is fun!";
int length = str.length(); // returns 13
char firstChar = str.charAt(0); // returns 'J'
String sub = str.substring(0, 4); // returns "Java"

String Comparison:
To compare strings for equality, you should use the equals() method. The
== operator checks for object reference equality, not content equality.

Example:
String s1 = "Hello";
String s2 = "Hello";
boolean isEqual = s1.equals(s2); // true
DAY-3
Java Conditions:

In Java, conditions are used to control the flow of a program by executing


different blocks of code based on whether a given condition is true or false.
The primary constructs for implementing conditions are the if, else if, and
else statements. Additionally, the switch statement is used for multiple
branching based on the value of an expression.

if Statement:

The if statement is used to execute a block of code if a specified condition


evaluates to true.

Example:

int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}

if-else Statement:

The if-else statement allows you to execute one block of code if the
condition is true and another block if it is false.
Example:

int y = 3;
if (y % 2 == 0) {
System.out.println("y is even");
} else {
System.out.println("y is odd");
}

else if Statement:

The else if statement is used when you have multiple conditions to check. It
follows an if statement and is evaluated only if the preceding if or else if
conditions are false.

Example:

int grade = 85;


if (grade >= 90) {
System.out.println("A");
} else if (grade >= 80) {
System.out.println("B");
} else if (grade >= 70) {
System.out.println("C");
} else {
System.out.println("F");
}

Nested if Statements:

You can have if statements inside other if statements, creating nested


conditions.
Example:

int num1 = 5;
int num2 = 10;
if (num1 > 0) {
if (num2 > 0) {
System.out.println("Both numbers are positive");
}
}

Switch Statement:

The switch statement is used for multiple branching based on the value of
an expression. It provides an alternative to using a series of if-else if
statements.

Example:

int dayOfWeek = 2;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ... other cases ...
default:
System.out.println("Invalid day");
}
Java Loop:

In Java, loops are used to repeatedly execute a block of code until a certain
condition is met. Java provides several types of loops, each serving a
different purpose. The primary loop constructs in Java are the for loop,
while loop, and do-while loop.

for Loop:

The for loop is used when you know the number of iterations in advance. It
consists of an initialization statement, a condition, and an iteration
statement.

Example:

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


System.out.println("Iteration " + i);
}
Initialization (int i = 0;):
Declares and initializes the loop variable (i in this case).
Condition (i < 5;): Defines the condition for continuing the loop.
Iteration (i++): Specifies how the loop variable is updated after each
iteration.

while Loop:

The while loop is used when the number of iterations is not known in
advance. It repeats a block of code as long as a specified condition is true.
Example:

int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
Condition (count < 3): The loop continues as long as this condition is true.
Iteration (count++): Incrementing the loop variable to eventually satisfy the
exit condition.

do-while Loop:

The do-while loop is similar to the while loop, but it guarantees that the
block of code is executed at least once because the condition is checked
after the loop body.

Example:

int i = 0;
do {
System.out.println("Iteration " + i);
i++;
} while (i < 5);
Iteration (i++): The loop body is executed at least once.
Condition (i < 5): The loop continues if this condition is true.
Break and Continue Statements:

The break statement is used to exit a loop prematurely, breaking out of the
loop's body.
Example:

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


if (i == 5) {
break; // exit the loop when i is 5
}
System.out.println(i);
}
The continue statement is used to skip the rest of the loop's body for the
current iteration and move to the next iteration.

Example:

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


if (i == 2) {
continue; // skip the iteration when i is 2
}
System.out.println(i);
}
DAY-4
Java Break/continue:

In Java, break and continue are control flow statements used within loops
to alter the normal flow of execution.

break statement:

The break statement is used to exit a loop prematurely. When encountered


inside a loop (such as for, while, or do-while), it causes the loop to
terminate immediately, and the program continues with the next
statement after the loop.

Example:

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


if (i == 5) {
break; // exit the loop when i equals 5
}
System.out.println(i);
}
In this example, the loop will print numbers from 0 to 4 because the break
statement is encountered when i becomes 5, causing an immediate exit
from the loop.
continue statement:

The continue statement is used to skip the rest of the code inside a loop for
the current iteration and proceed to the next iteration. When encountered,
it jumps to the next iteration of the loop without executing the remaining
code within the loop body.

Example:

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


if (i == 2) {
continue; // skip the rest of the loop body for i equals 2
}
System.out.println(i);
}
In this example, the loop will print numbers 0, 1, 3, and 4 because the
continue statement skips the code inside the loop when i is equal to 2.

Both break and continue statements are often used to control the flow of
loops based on certain conditions. It's important to use them judiciously to
avoid creating complex and hard-to-understand code.

Java Array:

In Java, an array is a data structure that allows you to store multiple values
of the same type under a single variable name. Arrays provide a convenient
way to work with collections of data, such as a list of numbers, characters,
or objects. Each element in an array is identified by its index, starting from
0 for the first element.

Here's a basic overview of how arrays work in Java:


Declaring an Array:

To declare an array, you specify the type of elements it will hold, followed

by the array name and square brackets:

// Declare an array of integers


int[] myArray;

Creating an Array:

You need to create an array and specify its size using the new keyword:

// Create an array of integers with a size of 5


myArray = new int[5];
Alternatively, you can combine declaration and creation in a single line:

int[] myArray = new int[5];

Initializing an Array:

You can initialize the values of an array at the time of creation:


int[] myArray = {1, 2, 3, 4, 5};
Accessing Elements:
To access elements in an array, you use the index:

int thirdElement = myArray[2]; // Arrays are zero-indexed, so this gets the


third element.

Array Length:

The length property gives you the number of elements in an array:


int arrayLength = myArray.length;
Iterating Through an Array:
You can use loops to iterate through the elements of an array:

for (int i = 0; i < myArray.length; i++) {


System.out.println(myArray[i]);
}

Multidimensional Arrays:

Java also supports multidimensional arrays, which are arrays of arrays. For
example, a 2D array can be declared and initialized as follows:

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


Arrays in Java provide a powerful and flexible way to work with collections
of data, and they are widely used in Java programming. Keep in mind that
arrays have a fixed size once created, and if you need a dynamic collection,
you might consider using other data structures like ArrayList.

Day-5
Java Methods:

In Java, a method is a block of code that performs a specific task or set of


tasks and can be invoked (called) from elsewhere in your code. Methods
are fundamental to structuring Java programs and promoting code reuse.
Here's an overview of how methods work in Java:

Declaring a Method:

The basic syntax for declaring a method in Java is as follows:


Example:

returnType methodName(parameterType1 parameterName1,


parameterType2 parameterName2, ...) {
// method body
// code to perform the task
return returnValue; // optional
}

returnType:

The data type of the value that the method returns. If a method does not
return any value, use void.

methodName:

The name of the method.

parameterType1, parameterType2, ...: The types of input parameters that


the method takes (if any).
parameterName1, parameterName2, ...: The names of the input
parameters.
method body: The block of code that defines the tasks performed by the
method.
return returnValue: The return statement is used to exit the method and,
optionally, return a value.
Example:

public class Example {


// A simple method that takes two integers and returns their sum
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum;
}
// A method with no return value (void)
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
int result = addNumbers(5, 3);
System.out.println("Sum: " + result);
greet("John");
}
}

Method Overloading:

Java supports method overloading, which allows you to define multiple


methods with the same name but different parameter lists. The compiler
determines which method to call based on the number and types of
arguments.

Example:

public class Example {


// Method with two integers
public static int addNumbers(int a, int b) {
return a + b;
}

// Method with three integers


public static int addNumbers(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {


System.out.println("Sum (two parameters): " + addNumbers(5, 3));
System.out.println("Sum (three parameters): " + addNumbers(5, 3, 2));
}
}

Access Modifiers:

Java provides access modifiers (public, private, protected, package-private)


to control the visibility of methods. The public modifier, for example, allows
a method to be accessed from any other class.

Example:

public class Example {


// A public method
public static void publicMethod() {
// code here
}

// A private method
private static void privateMethod() {
// code here
}
}
Static and Instance Methods:

Static Methods: Declared with the static keyword, they belong to the class
rather than an instance of the class.

Example:

public class Example {


public static void staticMethod() {
// code here
}
}

Instance Methods: Associated with an instance of the class and can access
instance variables.

Example:

public class Example {


public void instanceMethod() {
// code here
}
}
Day-6
OPPS Intro:

OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that


perform operations on the data, while object-oriented programming is
about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code
and shorter development time.

OOPS concepts are as follows:

 Class
 Object
 Method and method passing

Pillars of OOPs-

 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
Classes and Objects:

Class: A class is a blueprint or template for creating objects. It defines the


properties (fields) and behaviors (methods) that objects of the class will
have.
Object: An object is an instance of a class. It represents a real-world entity
and encapsulates data and behavior.

Example:

// Example class definition


public class Car {
// Fields (properties)
String model;
int year;
// Method (behavior)
void startEngine() {
System.out.println("Engine started!");
}
}
// Creating an object of the Car class
Car myCar = new Car();
Day-7
Class Attributes:

In Java, class attributes are also known as fields or member variables. These
attributes define the characteristics or properties of a class. They represent
the data that an object of the class will hold. Class attributes are declared
within the class but outside of any method, and they determine the state of
objects created from that class.

Here's an example of a Java class with attributes:

public class Car {


// Class attributes (fields)
String brand;
String model;
int year;
double price;

// Constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
}

// Other methods can be added to perform various operations on Car


objects
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
}

public static void main(String[] args) {


// Creating objects of the Car class
Car car1 = new Car("Toyota", "Camry", 2022, 25000.0);
Car car2 = new Car("Honda", "Accord", 2021, 28000.0);

// Accessing and modifying attributes


car1.displayInfo();

// Modifying the price attribute


car1.price = 26000.0;

// Displaying updated information


car1.displayInfo();
}
}

Constructors:

In Java, a constructor is a special method that is used to initialize the state


of an object. It is called when an object of a class is created. The primary
purpose of a constructor is to set up the initial values for the attributes of
the object or perform any necessary setup tasks.

Here are some key points about constructors in Java:


Characteristics of Constructors:
Name:
A constructor has the same name as the class to which it belongs.
No Return Type:
Unlike regular methods, constructors do not have a return type, not even
void.

Initialization:
Constructors are used to initialize the attributes or perform any necessary
setup for the object.

Automatic Invocation:
Constructors are automatically called when an object is created using the
new keyword.

Overloading:
Like methods, constructors can be overloaded, allowing a class to have
multiple constructors with different parameter lists.

Example:

public class Car {


// Class attributes
String brand;
String model;
int year;
double price;
// Default constructor (no parameters)
public Car() {
// Default values or initialization code can be placed here
brand = "Unknown";
model = "Unknown";
year = 0;
price = 0.0;
}
// Parameterized constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
}
// Method to display information about the car
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
System.out.println("Price: $" + price);
}
public static void main(String[] args) {
// Creating objects of the Car class using different constructors
Car defaultCar = new Car(); // Default constructor
Car customCar = new Car("Toyota", "Camry", 2022, 25000.0); //
Parameterized constructor
// Displaying information about the cars
System.out.println("Default Car:");
defaultCar.displayInfo();
System.out.println("\nCustom Car:");
customCar.displayInfo();
}
}

Modifiers:

In Java, modifiers are keywords that define the scope, access level, and
behavior of classes, methods, and variables. There are several types of
modifiers in Java, categorized into two main groups: access modifiers and
non-access modifiers.
Access Modifiers:

Access modifiers determine the visibility of classes, methods, and variables.


They control which other classes can access a particular class or its
members.

public:
The most permissive access level.
Classes, methods, and variables declared as public are accessible from any
other class.

Example:

public class MyClass {


public int myVariable;
public void myMethod() {
// code here
}
}

protected:
Accessible within the same package and by subclasses.
Used for providing visibility to subclasses without making members public.

Example:

protected class MyClass {


protected int myVariable;
protected void myMethod() {
// code here
}
}
default (Package-Private):
If no access modifier is specified, it defaults to package-private.
Accessible only within the same package.

Example:

class MyClass {
int myVariable;
void myMethod() {
// code here
}
}

private:
The most restrictive access level.
Accessible only within the same class.

Example:

public class MyClass {


private int myVariable;
private void myMethod() {
// code here
}
}

Non-Access Modifiers:

Non-access modifiers modify the behavior of classes, methods, and


variables but do not control their visibility.
static:
The static modifier is used to create class methods and variables.
A static method or variable belongs to the class rather than an instance of
the class.
Example:

public class MyClass {


static int staticVariable;
static void staticMethod() {
// code here
}
}

final:
The final modifier is used to make a variable, method, or class constant and
unchangeable.
A final variable cannot be reassigned, a final method cannot be overridden,
and a final class cannot be subclassed.

Example:

public class MyClass {


final int constantVariable = 42;
final void finalMethod() {
// code here
}
}

abstract:
The abstract modifier is used to declare abstract classes and methods.
An abstract class cannot be instantiated, and an abstract method must be
implemented by any non-abstract subclass.

Example:

public abstract class MyAbstractClass {


abstract void abstractMethod();
}
synchronized:

The synchronized modifier is used to control access to methods or code


blocks in a multithreaded environment.
It ensures that only one thread can access the synchronized method or
block at a time.

Example:

public class MyClass {


synchronized void synchronizedMethod() {
// code here
}
}

DAY-8
Inheritance:

Inheritance is one of the fundamental concepts in object-oriented


programming (OOP) that allows a class (subclass or derived class) to inherit
the properties and behaviors of another class (superclass or base class).
This enables code reuse and the creation of a hierarchy of classes,
promoting a modular and organized structure.

Key Concepts in Inheritance:

Superclass (Base Class):

The class whose properties and behaviors are inherited is called the
superclass or base class.
It defines common characteristics that are shared by one or more
subclasses.
Example:

// Superclass
public class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

Subclass (Derived Class):

The class that inherits from a superclass is called the subclass or derived
class.
It can reuse the properties and behaviors of the superclass and can also
have additional or overridden features.

Example:

// Subclass
public class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

Extending a Class:

In Java, the extends keyword is used to indicate that a class is inheriting


from another class.
The subclass inherits all non-private members (fields and methods) of the
superclass.
Example:

public class Dog extends Animal {


// additional members specific to Dog
}

Method Overriding:

Subclasses can provide a specific implementation for a method that is


already defined in the superclass.
This is known as method overriding.

Example:

// In the Animal class


public class Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}
// In the Dog class (method overriding)
public class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}

Access Modifiers in Inheritance:

Access modifiers (public, protected, default, private) control the visibility of


superclass members in the subclass.
The subclass can access public and protected members of the superclass.
Example:

// Superclass
public class Animal {
protected void protectedMethod() {
System.out.println("Protected method");
}
}
// Subclass
public class Dog extends Animal {
void someMethod() {
protectedMethod(); // Accessing protected method from the
superclass
}
}

Constructor in Inheritance:

Constructors are not inherited, but the constructor of the superclass is


called implicitly or explicitly using the super keyword.

Example:

// Superclass
public class Animal {
public Animal() {
System.out.println("Animal constructor");
}
}
// Subclass
public class Dog extends Animal {
public Dog() {
super(); // Calling the constructor of the superclass
System.out.println("Dog constructor"); } }
Example:

// Superclass
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

// Subclass
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}

public class InheritanceExample {


public static void main(String[] args) {
// Creating an object of the subclass
Dog myDog = new Dog();

// Accessing members from the superclass


myDog.eat(); // Inherited method
myDog.bark(); // Method specific to Dog
}
}
DAY-9
Encapsulation:

Encapsulation is one of the four fundamental object-oriented programming


(OOP) concepts, and it refers to the bundling of data (attributes or fields)
and methods (functions) that operate on the data into a single unit known
as a class. The purpose of encapsulation is to hide the internal details of an
object and restrict access to the internal state, allowing controlled access
only through well-defined interfaces.

Example:

public class Student {


// Private fields
private String name;
private int age;

// Public constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Public getter and setter methods


public String getName() {
return name;
}

public void setName(String name) {


// Validation logic can be added here
this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


// Validation logic can be added here
this.age = age;
}
}

DAY-10
Polymorphism:

Polymorphism is one of the key principles in object-oriented programming


(OOP) that allows objects of different types to be treated as objects of a
common base type. It provides a way to create flexible and extensible code
by enabling a single interface to represent different types of objects.
Polymorphism is expressed through two main mechanisms in Java: method
overloading and method overriding.

Example:

public class Calculator {


// Method overloading with different parameter types
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
// Method overloading with a different number of parameters
public int add(int a, int b, int c) {
return a + b + c;
}
}

DAY-11
Abstraction:

Abstraction is one of the four fundamental principles of object-oriented


programming (OOP) and is closely related to encapsulation. Abstraction
involves simplifying complex systems by modeling classes based on their
essential features while hiding unnecessary details. The goal of abstraction
is to focus on what an object does rather than how it achieves its
functionality.

Example:

// Abstract class with abstract and non-abstract methods


abstract class Shape {
// Abstract method
abstract void draw();

// Non-abstract method
void resize() {
System.out.println("Resizing the shape");
}
}

// Concrete subclass providing implementations for abstract methods


class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}

// Concrete subclass providing implementations for abstract methods


class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}

public class AbstractionExample {


public static void main(String[] args) {
// Creating objects of concrete classes
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();

// Invoking abstract and non-abstract methods


circle.draw();
circle.resize();

rectangle.draw();
rectangle.resize();
}
Interface:

In Java, an interface is a reference type that is similar to a class. It is a


collection of abstract methods. When a class implements an interface, it
provides concrete implementations for all the methods declared in the
interface. Additionally, an interface can contain constants, default
methods, and static methods.

Exapmle:

// Implementing the Drawable interface


public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
DAY-12
LIST&Map:

In Java, List and Map are two fundamental interfaces provided in the Java
Collections Framework, which is a set of classes and interfaces that
implement various data structures like lists, sets, maps, and queues. These
interfaces define common methods for manipulating collections of objects.

List Interface:

The List interface represents an ordered collection of elements where


elements can be duplicated. It extends the Collection interface and
provides methods to access elements by their index.

Example:

import java.util.List;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// Creating a List (ArrayList is one of the implementations)
List<String> myList = new ArrayList<>();
// Adding elements to the list
myList.add("Java");
myList.add("Python");
myList.add("JavaScript");
// Accessing elements by index
System.out.println("Element at index 1: " + myList.get(1));
// Iterating through the list
System.out.println("Elements in the list:");
for (String element : myList) {
System.out.println(element);
} } }
Map Interface:

The Map interface represents a collection of key-value pairs, where each


key is associated with exactly one value. It does not extend the Collection
interface. Some common implementations include HashMap, TreeMap, and
LinkedHashMap.

Example:

import java.util.Map;
import java.util.HashMap;
public class MapExample {
public static void main(String[] args) {
// Creating a Map (HashMap is one of the implementations)
Map<String, Integer> myMap = new HashMap<>();
// Adding key-value pairs to the map
myMap.put("Java", 1);
myMap.put("Python", 2);
myMap.put("JavaScript", 3);
// Accessing values by key
System.out.println("Value associated with key 'Java': " +
myMap.get("Java"));
// Iterating through the map
System.out.println("Key-Value pairs in the map:");
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Wrapper class:

In Java, a wrapper class is a class that provides an object representation for


a primitive data type. The Java programming language includes eight
primitive data types: byte, short, int, long, float, double, char, and boolean.
Wrapper classes allow these primitive types to be treated as objects. Each
of the primitive types has a corresponding wrapper class in Java.

Here is a list of the primitive types and their corresponding wrapper classes:
1. byte - Byte
2. short - Short
3. int - Integer
4. long - Long
5. float - Float
6. double - Double
7. char - Character
8. boolean – Boolean

Example:

public class WrapperClassExample {

public static void main(String[] args) {

// Using primitive data types

int intValue = 42;

double doubleValue = 3.14;

char charValue = 'A';

// Using wrapper classes

Integer integerObject = Integer.valueOf(intValue);

Double doubleObject = Double.valueOf(doubleValue);

Character charObject = Character.valueOf(charValue);


// AutoBoxing (automatic conversion from primitive to wrapper)

Boolean booleanObject = true;

// Unboxing (automatic conversion from wrapper to primitive)

boolean booleanValue = booleanObject.booleanValue();

System.out.println("Integer Object: " + integerObject);

System.out.println("Double Object: " + doubleObject);

System.out.println("Character Object: " + charObject);

System.out.println("Boolean Value: " + booleanValue);

}
Exception handling:

Exception handling in Java is a mechanism to deal with runtime errors or


exceptional conditions that may occur during the execution of a program.
Java provides a robust and structured way to handle exceptions using the
try, catch, finally, throw, and throws keywords. Exceptions in Java are
objects derived from the Throwable class.

Example:

try {
// Code that may cause an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code to be executed regardless of whether an exception occurred
}

Multi Threading:

Multithreading in Java allows multiple threads to execute concurrently


within the same program. A thread is a lightweight, independent unit of
execution, and multithreading enables better utilization of CPU resources,
especially in systems with multiple processors or cores.

Example:

class MyThread extends Thread {


public void run() {
// Code to be executed in the thread
}
}

public class ThreadExample {


public static void main(String[] args) {
// Creating and starting a thread
MyThread myThread = new MyThread();
myThread.start();
}
}

Implementing the Runnable Interface:

class MyRunnable implements Runnable {


public void run() {
// Code to be executed in the thread
}
}

public class RunnableExample {


public static void main(String[] args) {
// Creating a thread with a Runnable object
Thread myThread = new Thread(new MyRunnable());
myThread.start();
}
}
DAY-13
Java Swing:

Java Swing is a set of graphical user interface (GUI) components and tools
for building desktop applications in Java. It provides a rich set of libraries
and widgets (components) that enable developers to create interactive and
visually appealing user interfaces. Swing is part of the Java Foundation
Classes (JFC) and is designed to be platform-independent, offering a
consistent look and feel across different operating systems.

Basic Swing Components:

JFrame:
The main window of a Swing application. It provides the overall frame for
the application and can hold other components.

JPanel:
A container that can hold and organize other components. It is often used
to group related components.

JButton:
A button that triggers an action when clicked.

JTextField:
A single-line text input field where the user can enter text.

JTextArea:
A multi-line text input area suitable for larger amounts of text.

JLabel:
A non-interactive component used to display text or an image.
JCheckBox and JRadioButton:
Components for selecting multiple or single options, respectively.

JComboBox:
A drop-down list for selecting an item from a list.

JList and JTable:


Components for displaying lists and tables of data.

Example:
JDBC:

Java Database Connectivity (JDBC) is a Java-based API that provides a


standard interface for connecting to relational databases and executing SQL
queries. JDBC enables Java applications to interact with databases by
providing a set of classes and methods for database operations. Here's an
overview of how JDBC works:

OUTPUT:
DAY-14
Servlet:

A servlet in Java is a server-side program that extends the functionality of a


web server to support dynamic content generation and processing. Servlets
are a key component of Java Enterprise Edition (Java EE) and are used to
create web applications. They provide a way to handle requests from web
clients, process the requests, and generate dynamic responses that can be
sent back to the clients.

Here are some key points about servlets:

1. Lifecycle of a Servlet:
A servlet goes through several stages during its lifecycle:
Initialization: The init() method is called when the servlet is first created. It
is used to perform one-time initialization tasks.
Request Handling: The service() method is called for each incoming HTTP
request. This is where the servlet processes the request and generates a
response.
Destruction: The destroy() method is called when the servlet is being taken
out of service. It is used to perform cleanup tasks.

2. Servlet API:
Servlets interact with the web server using the Servlet API, which includes
interfaces and classes provided by Java EE. Some of the key interfaces and
classes in the Servlet API include:

javax.servlet.Servlet: The interface that all servlets must implement.


javax.servlet.http.HttpServlet: A convenience class that extends Servlet and
provides additional methods specific to HTTP.
3. Handling HTTP Requests and Responses:
Servlets are commonly used to handle HTTP requests and responses. The
HttpServletRequest and HttpServletResponse classes provide methods for
accessing request parameters, headers, and attributes, as well as for
generating dynamic content to be sent back to the client.

4. Deployment Descriptor (web.xml):


Servlets are configured in a deployment descriptor file called web.xml. This
file provides information about the servlet, such as its class name, URL
mapping, initialization parameters, and more.

5. URL Mapping:
Servlets are mapped to specific URLs so that the web server knows which
servlet should handle a particular request. This mapping is typically
specified in the web.xml file or using annotations.

Example:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set the content type of the response
response.setContentType("text/html");
// Get the PrintWriter object to write the response
java.io.PrintWriter out = response.getWriter();

// Write HTML content to the response


out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h2>Hello, this is a simple servlet!</h2>");
out.println("</body>");
out.println("</html>");
}
}

Hibernate:

Hibernate is an open-source object-relational mapping (ORM) framework


for Java that simplifies the development of database-driven applications. It
provides a framework for mapping Java objects to database tables and vice
versa, abstracting the details of database interactions and allowing
developers to focus on working with objects in their application code.
Hibernate is a popular choice for Java developers when building persistence
layers for enterprise applications.
Key features and concepts of Hibernate include:

1. Object-Relational Mapping (ORM):


Hibernate enables developers to map Java objects to database tables and
vice versa. This eliminates the need for direct SQL queries and allows
developers to work with objects in their application code. The mapping is
typically done through XML configuration files or annotations.

2. Mapping Entities:
In Hibernate, a Java class that is mapped to a database table is referred to
as an "entity." Each entity class corresponds to a table in the database, and
each instance of the class represents a row in that table.

Example:

@Entity
@Table(name = "employees")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

// Getters and setters


}
DAY-15
Spring & Spring Boot:

Spring Framework:

The Spring Framework is a comprehensive, modular, and widely-used


framework for building enterprise Java applications. It provides
infrastructure support for developing Java applications, promoting good
design practices and patterns such as dependency injection and aspect-
oriented programming. The Spring Framework is known for its flexibility,
scalability, and the ability to address various concerns in the development
of complex applications.

Key features of the Spring Framework include:

Inversion of Control (IoC):


Spring promotes the concept of Inversion of Control, where the control of
object creation and lifecycle management is shifted from the application
code to the Spring container. This is achieved through dependency
injection.

Dependency Injection (DI):


Spring facilitates the injection of dependencies into objects, reducing the
coupling between components and promoting modular, reusable code.
Dependency injection is typically achieved through constructor injection or
setter injection.
Aspect-Oriented Programming (AOP):
Spring supports Aspect-Oriented Programming, allowing developers to
separate cross-cutting concerns, such as logging, security, and transactions,
from the main business logic. Aspects can be applied using annotations or
XML configuration.

Data Access:
Spring provides support for data access through JDBC, ORM frameworks
(such as Hibernate), and declarative transaction management. It simplifies
database operations and enhances productivity.

Transaction Management:
Spring offers a declarative approach to transaction management, allowing
developers to define transactions using annotations or XML configuration.
It supports both programmatic and declarative transaction management.

Model-View-Controller (MVC):
The Spring MVC framework provides a flexible and scalable way to build
web applications. It follows the Model-View-Controller architectural
pattern and integrates seamlessly with other Spring features.

Security:
Spring Security is a powerful and customizable authentication and access
control framework for Java applications. It provides comprehensive security
services for Java EE-based enterprise software applications.

Testing:
Spring supports testing through the use of the Spring TestContext
Framework, which provides integration testing support and makes it easier
to write unit tests for Spring components.
Spring Boot:

Spring Boot is an extension of the Spring Framework that simplifies the


process of building production-ready, stand-alone, and web-based
applications. It focuses on convention-over-configuration and provides a set
of defaults and auto-configurations that eliminate much of the boilerplate
code and configuration required in a typical Spring application.

Key features of Spring Boot include:

Opinionated Defaults:
Spring Boot adopts an opinionated approach by providing sensible defaults
and auto-configurations. Developers can get started quickly without
extensive manual configuration.

Embedded Containers:
Spring Boot includes embedded servlet containers (like Tomcat, Jetty, or
Undertow) that allow developers to run applications as standalone JAR
files. This eliminates the need for external deployment.

Auto-Configuration:
Spring Boot automatically configures application components based on the
project's dependencies and the environment. Developers can override or
customize these configurations as needed.
Standalone:
Spring Boot applications are standalone, meaning they have an embedded
web server and require minimal external setup. This makes it easy to
package and deploy applications as self-contained units.

Spring Boot Starters:


Starters are a set of convenient dependency descriptors that simplify the
inclusion of common dependencies in the project. For example, the spring-
boot-starter-web includes everything needed to build a web application.

Spring Boot Actuator:


Actuator provides production-ready features to help monitor and manage
applications. It includes endpoints for health checks, metrics, application
properties, and more.

Spring Boot CLI:


The Spring Boot Command Line Interface (CLI) allows developers to write,
test, and run Spring Boot applications using a command-line interface. It
facilitates rapid prototyping and development.

Microservices:
Spring Boot is well-suited for building microservices architectures. Its
simplicity and convention-over-configuration approach make it easy to
create and deploy microservices independently.

You might also like