JAVA Internship
JAVA Internship
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().
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.
Single-Line Comments:
Example:
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:
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.
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:
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.
Object Types:
String: Represents a sequence of characters (text).
Array: Represents an ordered collection of elements.
Example:
Java operation:
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;
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:
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.
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:
if Statement:
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:
Nested if Statements:
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:
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:
Example:
In Java, break and continue are control flow statements used within loops
to alter the normal flow of execution.
break statement:
Example:
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:
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.
To declare an array, you specify the type of elements it will hold, followed
Creating an Array:
You need to create an array and specify its size using the new keyword:
Initializing an Array:
Array Length:
Multidimensional Arrays:
Java also supports multidimensional arrays, which are arrays of arrays. For
example, a 2D array can be declared and initialized as follows:
Day-5
Java Methods:
Declaring a Method:
returnType:
The data type of the value that the method returns. If a method does not
return any value, use void.
methodName:
Method Overloading:
Example:
Access Modifiers:
Example:
// 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:
Instance Methods: Associated with an instance of the class and can access
instance variables.
Example:
Class
Object
Method and method passing
Pillars of OOPs-
Abstraction
Encapsulation
Inheritance
Polymorphism
Classes and Objects:
Example:
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.
// Constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand;
this.model = model;
this.year = year;
this.price = price;
}
Constructors:
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:
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:
public:
The most permissive access level.
Classes, methods, and variables declared as public are accessible from any
other class.
Example:
protected:
Accessible within the same package and by subclasses.
Used for providing visibility to subclasses without making members public.
Example:
Example:
class MyClass {
int myVariable;
void myMethod() {
// code here
}
}
private:
The most restrictive access level.
Accessible only within the same class.
Example:
Non-Access Modifiers:
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:
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:
Example:
DAY-8
Inheritance:
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");
}
}
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:
Method Overriding:
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:
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");
}
}
Example:
// Public constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}
DAY-10
Polymorphism:
Example:
DAY-11
Abstraction:
Example:
// Non-abstract method
void resize() {
System.out.println("Resizing the shape");
}
}
rectangle.draw();
rectangle.resize();
}
Interface:
Exapmle:
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:
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:
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:
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:
}
Exception handling:
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:
Example:
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.
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.
Example:
JDBC:
OUTPUT:
DAY-14
Servlet:
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:
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();
Hibernate:
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;
Spring Framework:
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:
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.
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.