Java CT2
Java CT2
Syntax:
java
CopyEdit
(parameters) -> expression
Or for multi-line:
java
CopyEdit
(parameters) -> {
// statements
}
Example:
java
CopyEdit
// Before Java 8
Runnable r = new Runnable() {
public void run() {
System.out.println("Running thread");
}
};
// With Lambda
Runnable r = () -> System.out.println("Running thread");
Advantages:
Reduces boilerplate code.
Enhances the readability of code.
Supports functional programming style.
Example:
java
CopyEdit
List<String> list = Arrays.asList("Java", "Python", "C++",
"JavaScript");
list.stream()
.filter(str -> str.startsWith("J"))
.forEach(System.out::println);
Features:
Lazy execution: operations are only performed when a terminal
operation is invoked.
Supports both sequential and parallel processing.
Doesn't modify the original data source.
Main Components:
Intermediate Operations: map, filter, sorted
Terminal Operations: collect, forEach, reduce
Syntax:
java
CopyEdit
interface MyInterface {
default void show() {
System.out.println("This is a default method");
}
}
Why useful:
Allows adding new methods to interfaces without breaking the
existing implementation.
Enables backward compatibility with older codebases.
Supports code reuse within interfaces.
Types:
1. Reference to a static method – ClassName::staticMethod
2. Reference to an instance method – instance::instanceMethod
3. Reference to a constructor – ClassName::new
Example:
java
CopyEdit
// Using Lambda
list.forEach(s -> System.out.println(s));
Advantages:
Shorter syntax
Better readability
Reusability of existing methods
Example:
java
CopyEdit
String html = """
<html>
<body>
<h1>Hello, World</h1>
</body>
</html>
""";
Benefits:
Eliminates the need for \n and string concatenation.
Preserves formatting.
Improves readability for large string values such as JSON, XML,
or HTML content.
� UNIT 4 – Java Collection Framework
1. What is the Collection Framework in Java?
The Java Collection Framework is a unified architecture that provides
interfaces and classes to store, retrieve, and manipulate groups of objects
efficiently. It includes interfaces like List, Set, Map, Queue, and classes
like ArrayList, HashMap, LinkedList, etc.
Main Interfaces:
List – Ordered collection (ArrayList, LinkedList)
Set – No duplicate elements (HashSet, TreeSet)
Map – Key-value pairs (HashMap, TreeMap)
Queue – FIFO (LinkedList, PriorityQueue)
Advantages:
Reusable data structures
Standardized operations like sorting, searching
Reduces development time and effort
Uses:
1. Dynamic Storage – Automatically grows or shrinks as needed,
unlike arrays.
2. Index-based Access – Allows fast random access to elements via
index.
Example:
java
CopyEdit
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits.get(0)); // Apple
3. Define HashMap
HashMap is a part of Java's Collection Framework and stores data in key-
value pairs. It uses a hashing technique to allow constant-time
performance for get and put operations.
Example:
java
CopyEdit
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
Features:
Keys are unique; values can be duplicated.
Doesn't maintain order.
Allows one null key and multiple null values.
Implementations:
LinkedList
PriorityQueue
ArrayDeque
Example:
java
CopyEdit
Queue<String> queue = new LinkedList<>();
queue.add("A");
queue.add("B");
System.out.println(queue.remove()); // Output: A
Common Methods:
add(), remove(), peek(), poll()
Example:
java
CopyEdit
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Main Methods:
hasNext() – checks if next element exists
next() – returns the next element
remove() – removes the current element (optional)
Use Case:
Useful for safely removing elements during iteration.
� UNIT 5 – Spring Framework & Spring Boot
1. What is Dependency Injection in Spring?
Dependency Injection (DI) is a core feature of Spring. It refers to the
process of injecting object dependencies externally rather than the object
creating them itself. This helps in creating loosely coupled and easily
testable code.
Types:
Constructor Injection
Setter Injection
Example:
java
CopyEdit
@Component
class Engine {}
@Component
class Car {
private final Engine engine;
@Autowired
public Car(Engine engine) {
this.engine = engine;
}
}
Advantages:
Promotes loose coupling
Enhances code testability and reusability
Simplifies unit testing with mock objects
2. Name any two RESTful HTTP methods
RESTful APIs use standard HTTP methods to perform CRUD
operations.
3. Define @RestController
@RestController is a Spring annotation that marks a class as a web
controller where every method returns a domain object rather than a
view. It is a combination of @Controller and @ResponseBody.
Example:
java
CopyEdit
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Purpose:
To build RESTful web services
Automatically converts Java objects into JSON or XML
4. What is Spring Framework?
Spring Framework is a powerful, lightweight, and open-source Java
application framework that provides infrastructure support for building
Java applications.
Key Features:
Inversion of Control (IoC)
Aspect-Oriented Programming (AOP)
MVC Web Framework
Data Access and Transaction Management
Modules in Spring:
Spring Core
Spring AOP
Spring MVC
Spring Data
Spring Security
Key Features:
Auto-configuration of Spring beans
Embedded servers (Tomcat, Jetty)
Opinionated 'starter' dependencies
Production-ready features like health checks, metrics via Spring
Boot Actuator
Example:
java
CopyEdit
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
Benefits:
Rapid application development
Easy integration with cloud and microservices
Simplifies deployment with minimal XML or configuration files