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

Study Material

The document provides an overview of important Java concepts including object-oriented programming principles like inheritance, polymorphism, and encapsulation. It also covers Java syntax and language features, and the collections framework.

Uploaded by

The Rooban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Study Material

The document provides an overview of important Java concepts including object-oriented programming principles like inheritance, polymorphism, and encapsulation. It also covers Java syntax and language features, and the collections framework.

Uploaded by

The Rooban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Important Basic Java Knowledge

1. Java is OOP Language:

object

Class

inhertance

polymorphism

Encapsulation

abstraction

Classes and Objects:

Class - Template / Blueprint

properties, Actions

Object - Memory Representation

properties, Actions

Class specific properties, behaviours

Object specific properties, behaviours

Object- Memory Representation of a class

Object cannot exist without class

// Class definition

class Car {

// Attributes

private String brand;

private String model;


// Constructor

public Car(String brand, String model) {

this.brand = brand;

this.model = model;

// Method

public void drive() {

System.out.println("Driving the " + brand + " " + model);

// Creating objects of the class

public class Main {

public static void main(String[] args) {

// Creating objects of Car class

Car car1 = new Car("Toyota", "Camry");

Car car2 = new Car("Honda", "Accord");

// Calling methods on objects

car1.drive();

car2.drive();

}
Inheritance:

Inheritance: Parent Child Relationship

An object of one class acting as an object of another class

// Parent class

public class Animal {

public void eat() {

System.out.println("Animal is eating");

// Child class inheriting from Animal

public class Dog extends Animal {

public void bark() {

System.out.println("Dog is barking");

// Creating objects of the classes

public class Main {

public static void main(String[] args) {

// Creating objects of Animal and Dog classes

Animal animal = new Animal();

Dog dog = new Dog();


// Calling methods on objects

animal.eat(); // Output: Animal is eating

dog.eat(); // Output: Animal is eating (inherited from Animal class)

dog.bark(); // Output: Dog is barking

Polymorphism:

Poly - Many

morph - face many faces

// Parent class

public class Shape {

public void draw() {

System.out.println("Drawing shape");

// Child classes overriding the draw method

public class Circle extends Shape {

@Override

public void draw() {

System.out.println("Drawing circle");

}
public class Rectangle extends Shape {

@Override

public void draw() {

System.out.println("Drawing rectangle");

// Creating objects of the classes

public class Main {

public static void main(String[] args) {

// Polymorphic behavior

Shape shape1 = new Circle();

Shape shape2 = new Rectangle();

// Calling draw method

shape1.draw(); // Output: Drawing circle

shape2.draw(); // Output: Drawing rectangle

Encapsulation:

Data Binding:

Personal - neighbours - relatives - public =access authorization


// Class with encapsulated attributes

public class Student {

private String name;

private int age;

// Getter and setter methods for encapsulated attributes

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

if (age >= 0 && age <= 100) {

this.age = age;

} else {

System.out.println("Invalid age");

}
}

// Creating objects of the class and accessing attributes using encapsulation

public class Main {

public static void main(String[] args) {

// Creating object of Student class

Student student = new Student();

// Setting attributes using setter methods

student.setName("John");

student.setAge(25);

// Getting attributes using getter methods

System.out.println("Name: " + student.getName()); // Output: Name: John

System.out.println("Age: " + student.getAge()); // Output: Age: 25

// Setting invalid age

student.setAge(150); // Output: Invalid age

Abstraction

Data Hiding

Showing only necessary data and hiding the unwanted data.


Laptop --> power button press

keyboard, monitor, OS - booting

// Abstract class representing a Shape

abstract class Shape {

// Abstract method to calculate area (implementation left to subclasses)

abstract double calculateArea();

// Concrete subclass representing a Circle

class Circle extends Shape {

private double radius;

// Constructor

public Circle(double radius) {

this.radius = radius;

// Implementation of abstract method to calculate area for Circle

@Override

double calculateArea() {

return Math.PI * radius * radius;

}
// Concrete subclass representing a Rectangle

class Rectangle extends Shape {

private double length;

private double width;

// Constructor

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

// Implementation of abstract method to calculate area for Rectangle

@Override

double calculateArea() {

return length * width;

// Main class to demonstrate abstraction

public class AbstractionExample {

public static void main(String[] args) {

// Creating instances of Circle and Rectangle

Circle circle = new Circle(5);

Rectangle rectangle = new Rectangle(4, 6);


// Calling calculateArea method without knowing the specific implementation

System.out.println("Area of Circle: " + circle.calculateArea());

System.out.println("Area of Rectangle: " + rectangle.calculateArea());

2.Java Syntax and Language Features

Java Syntax: Java syntax refers to the rules and conventions for writing Java code.

Data Types: Java supports various data types such as int, double, boolean, char, etc., which
specify the type of data that a variable can hold.

Control Structures: Control structures in Java include loops (for, while, do-while) and
conditionals (if-else, switch-case) that allow you to control the flow of execution in your
program.

Exception Handling: Exception handling in Java allows you to gracefully handle runtime
errors or exceptional situations that may occur during program execution using try-catch
blocks.

example program demonstrating Java syntax and language features:

public class JavaSyntaxExample {

public static void main(String[] args) {

// Declare and initialize variables

int number1 = 10;

int number2 = 5;

// Arithmetic operations

int sum = number1 + number2;

int difference = number1 - number2;

int product = number1 * number2;


double quotient = (double) number1 / number2;

System.out.println("Sum: " + sum);

System.out.println("Difference: " + difference);

System.out.println("Product: " + product);

System.out.println("Quotient: " + quotient);

// Conditional statement (if-else)

if (number1 > number2) {

System.out.println(number1 + " is greater than " + number2);

} else if (number1 < number2) {

System.out.println(number1 + " is less than " + number2);

} else {

System.out.println(number1 + " is equal to " + number2);

// Loop (for loop)

System.out.println("Printing numbers from 1 to 5:");

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

System.out.println(i);

// Exception handling (try-catch)

try {

int result = number1 / 0; // This will throw an ArithmeticException


} catch (ArithmeticException e) {

System.out.println("Error: Division by zero");

3.Collections Framework

Usage: Helps in Storing and Processing of Data Efficiently

List: A List is an ordered collection that allows duplicate elements. Elements in a List are
accessed by their index.

import java.util.ArrayList;

import java.util.List;

public class ListExample {

public static void main(String[] args) {

// Creating a List of Strings

List<String> names = new ArrayList<>();

// Adding elements to the List

names.add("Alice");

names.add("Bob");

names.add("Charlie");

// Accessing elements by index

System.out.println("First element: " + names.get(0));


// Iterating over the List

System.out.println("All elements:");

for (String name : names) {

System.out.println(name);

Set: A Set is a collection that does not allow duplicate elements. It does not guarantee the
order of elements.

import java.util.HashSet;

import java.util.Set;

public class SetExample {

public static void main(String[] args) {

// Creating a Set of integers

Set<Integer> numbers = new HashSet<>();

// Adding elements to the Set

numbers.add(10);

numbers.add(20);

numbers.add(30);

numbers.add(10); // This will not be added as it's a duplicate

// Iterating over the Set

System.out.println("All elements:");
for (Integer number : numbers) {

System.out.println(number);

Map: A Map is a collection of key-value pairs where each key is unique. It does not allow
duplicate keys.

import java.util.HashMap;

import java.util.Map;

public class MapExample {

public static void main(String[] args) {

// Creating a Map of names and ages

Map<String, Integer> ages = new HashMap<>();

// Adding key-value pairs to the Map

ages.put("Alice", 30);

ages.put("Bob", 25);

ages.put("Charlie", 35);

// Accessing value by key

System.out.println("Age of Alice: " + ages.get("Alice"));

// Iterating over the Map

System.out.println("All entries:");
for (Map.Entry<String, Integer> entry : ages.entrySet()) {

System.out.println(entry.getKey() + " - Age: " + entry.getValue());

Queue: A Queue is a data structure that follows the First-In-First-Out (FIFO) principle, where
elements are inserted at the rear and removed from the front.

import java.util.LinkedList;

import java.util.Queue;

public class QueueExample {

public static void main(String[] args) {

// Creating a Queue of integers

Queue<Integer> queue = new LinkedList<>();

// Adding elements to the Queue

queue.offer(10);

queue.offer(20);

queue.offer(30);

// Printing the Queue

System.out.println("Queue: " + queue);

// Removing and printing the head of the Queue

int head = queue.poll();


System.out.println("Removed element: " + head);

// Printing the updated Queue

System.out.println("Updated Queue: " + queue);

// Peeking at the head of the Queue without removing it

int peekedElement = queue.peek();

System.out.println("Peeked element: " + peekedElement);

// Printing the Queue again

System.out.println("Queue after peek: " + queue);

4.Concurrency

Basic understanding of concurrency concepts such as threads, synchronization, and thread


safety

Threads: Threads are the smallest unit of execution within a process. In Java, you can create
and manage threads using the Thread class or by implementing the Runnable interface.

Example program demonstrating creating and starting a thread:

public class ThreadExample {

public static void main(String[] args) {

Thread thread = new Thread(() -> {

// Code to be executed in the thread

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


System.out.println("Thread: " + i);

try {

Thread.sleep(1000); // Pause for 1 second

} catch (InterruptedException e) {

e.printStackTrace();

});

thread.start(); // Start the thread

Synchronization: Synchronization is the process of controlling access to shared resources


among multiple threads to prevent data corruption and ensure thread safety. In Java, you can
use synchronized blocks or methods to synchronize access to critical sections of code.

Example program demonstrating synchronization using synchronized block:

public class SynchronizationExample {

private static int counter = 0;

public static void main(String[] args) {

Thread thread1 = new Thread(() -> {

synchronized (SynchronizationExample.class) {

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

counter++;

}
}

});

Thread thread2 = new Thread(() -> {

synchronized (SynchronizationExample.class) {

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

counter++;

});

thread1.start();

thread2.start();

// Wait for threads to finish

try {

thread1.join();

thread2.join();

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Counter: " + counter);

}
Thread Safety: Thread safety ensures that a piece of code or data can be safely accessed and
manipulated by multiple threads without causing data corruption or unexpected behavior.
Techniques such as synchronization, atomic operations, and immutable objects are used to
achieve thread safety.

5.Java Annotations

Spring Boot extensively uses annotations for configuration and dependency injection.

@Autowired: Used to automatically wire beans (dependencies) by type. It injects the bean
instance into a field, setter method, or constructor.

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class MyService {

private MyRepository myRepository;

@Autowired

public MyService(MyRepository myRepository) {

this.myRepository = myRepository;

@Component: Indicates that a class is a Spring component and should be automatically


detected and registered as a bean.
import org.springframework.stereotype.Component;

@Component

public class MyComponent {

// Class implementation

@Service: Annotates a class to indicate that it's a service component in the business layer.

import org.springframework.stereotype.Service;

@Service

public class MyService {

// Class implementation

@RestController: Combines @Controller and @ResponseBody annotations to simplify


RESTful web service development. It indicates that the class provides RESTful endpoints and
automatically serializes the return value to JSON or XML.

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class MyController {

@GetMapping("/hello")

public String hello() {

return "Hello, World!";

}
}

@RequestMapping: Maps HTTP requests to specific handler methods or controller classes. It


specifies the URL path and HTTP method for handling requests.

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/api")

public class MyController {

@GetMapping("/hello")

public String hello() {

return "Hello, World!";

6.Dependency Injection (DI):

Dependency Injection (DI) is a design pattern commonly used in software development,


especially in frameworks like Spring Boot. It promotes loose coupling between classes by
removing the responsibility of creating and managing dependencies from the class itself.
Instead, dependencies are provided (injected) from external sources, typically through
constructor injection, setter injection, or field injection.

Here's a brief overview of Dependency Injection along with example programs demonstrating
constructor injection and setter injection:

Constructor Injection: Dependencies are injected into a class through its constructor. This is
the preferred method as it ensures that all required dependencies are provided at object
creation time.

public class MyService {


private MyRepository myRepository;

// Constructor Injection

public MyService(MyRepository myRepository) {

this.myRepository = myRepository;

// Other methods using myRepository

Setter Injection: Dependencies are injected into a class through setter methods. Setter
injection allows for optional dependencies or changing dependencies at runtime.

public class MyService {

private MyRepository myRepository;

// Setter Injection

public void setMyRepository(MyRepository myRepository) {

this.myRepository = myRepository;

// Other methods using myRepository

In Spring Boot, dependency injection is facilitated by the Spring IoC container. Spring Boot
automatically scans for components annotated with @Component, @Service, @Repository,
etc., and manages their dependencies. When a bean is created, Spring injects any required
dependencies based on the constructor or setter methods.
The benefits of Dependency Injection include improved modularity, testability, and
maintainability of code. By decoupling classes from their dependencies, DI makes it easier to
replace or update components without affecting other parts of the system.

Understanding Dependency Injection and its principles is crucial for effectively developing
Spring Boot applications and leveraging the benefits of the Spring framework.

Inversion of Control (IoC) is a design principle where the control of object creation and
lifecycle management is inverted from the application code to an external framework or
container. In IoC, the framework controls the flow of the program and manages the
dependencies between objects. Dependency Injection (DI) is a specific implementation of
IoC, where dependencies are injected into a class rather than being created by the class itself.
DI patterns provide guidelines and best practices for implementing DI effectively.
Dependency Injection frameworks provide tools and mechanisms to facilitate the
implementation of DI in software applications.

Here's an explanation of IoC, DI patterns, and dependency injection frameworks along with
example programs:

Inversion of Control (IoC):

In IoC, the control flow of an application is shifted from the application code to a central
framework or container. The framework manages object creation, configuration, and lifecycle,
allowing developers to focus on implementing business logic rather than managing
dependencies.

Example program demonstrating IoC:

In Spring Boot, the IoC container manages the creation and dependency injection of beans.

Here's a simple Spring Boot application demonstrating IoC:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication

public class MyApplication {

public static void main(String[] args) {

SpringApplication.run(MyApplication.class, args);

Dependency Injection (DI) Patterns:

DI patterns provide guidelines and best practices for implementing Dependency Injection
effectively. Some common DI patterns include Constructor Injection, Setter Injection, and
Interface Injection.

Example program demonstrating DI patterns:

Here's an example demonstrating Constructor Injection using Spring Boot:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class MyService {

private MyRepository myRepository;

@Autowired

public MyService(MyRepository myRepository) {

this.myRepository = myRepository;

Dependency Injection Frameworks:


Dependency Injection frameworks provide tools and mechanisms to facilitate the
implementation of DI in software applications. Spring Framework is one of the most popular
DI frameworks in Java, offering comprehensive support for DI and IoC.

Example program demonstrating Spring Framework's DI:

Here's an example demonstrating dependency injection using Spring Framework's


@Autowired annotation:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class MyService {

private MyRepository myRepository;

@Autowired

public void setMyRepository(MyRepository myRepository) {

this.myRepository = myRepository;

7.Java EE Basics

Java EE (Enterprise Edition) provides a set of specifications, APIs, and runtime environments
for developing enterprise-scale applications in Java. While not mandatory for using Spring
Boot, having a basic understanding of Java EE concepts can be helpful, especially when
dealing with web applications and database connectivity. Here's a brief overview of Java EE
basics along with example programs:

Servlets:

Servlets are Java classes that handle HTTP requests and generate HTTP responses. They are
the foundation of Java web development and are used to create dynamic web pages, handle
form submissions, and perform server-side processing.
Example program demonstrating a simple servlet:

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("/hello")

public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.getWriter().println("Hello, World!");

JSP (JavaServer Pages):

JSP is a technology that allows developers to embed Java code in HTML pages to create
dynamic web content. JSP files are compiled into servlets by the server at runtime.

Example program demonstrating a simple JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"%>

<!DOCTYPE html>

<html>

<head>

<title>Hello JSP</title>

</head>
<body>

<h1>Hello, <%= request.getParameter("name") %>!</h1>

</body>

</html>

JDBC (Java Database Connectivity):

JDBC is an API for connecting Java applications to relational databases and executing SQL
queries. It provides a set of classes and interfaces for database access and manipulation.

Example program demonstrating JDBC usage:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class JdbcExample {

public static void main(String[] args) {

try (Connection connection =


DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");

Statement statement = connection.createStatement();

ResultSet resultSet = statement.executeQuery("SELECT * FROM users")) {

while (resultSet.next()) {

System.out.println("ID: " + resultSet.getInt("id") + ", Name: " +


resultSet.getString("name"));

} catch (SQLException e) {
e.printStackTrace();

8.Lambda Expressions and Streams:

Lambda expressions and streams were introduced in Java 8 to facilitate functional-style


programming and make Java code more concise and expressive. Here's a brief overview of
lambda expressions and streams along with example programs:

Lambda Expressions:

Lambda expressions are anonymous functions that allow you to treat functionality as a
method argument or to create concise instances of single-method interfaces (functional
interfaces).

Example program demonstrating lambda expressions:

interface MyInterface {

void myMethod(String s);

public class LambdaExample {

public static void main(String[] args) {

MyInterface myInterface = s -> System.out.println("Hello, " + s);

myInterface.myMethod("World");

Streams:

Streams provide a powerful way to process collections of objects in a functional style. They
allow you to perform aggregate operations on collections (such as filter, map, reduce) in a
concise and declarative manner.
Example program demonstrating streams:

import java.util.Arrays;

import java.util.List;

public class StreamExample {

public static void main(String[] args) {

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Emma");

// Filter names starting with 'A' and convert them to uppercase

names.stream()

.filter(name -> name.startsWith("A"))

.map(String::toUpperCase)

.forEach(System.out::println);

You might also like