Java notes for unit-1
**Introduction to Java 8**
- **Lambda Expressions** Lambda expressions,
introduced in Java 8, enable the creation of
anonymous functions. They allow for concise and
expressive code.
```java
// Example of a lambda expression
(x, y) -> x + y
```
- **Functional Interfaces** Functional interfaces
have a single abstract method. They are essential
for using lambda expressions effectively.
```java
// Example of a functional interface
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
```
- **Streams** Java 8 introduced the Stream API
for working with collections of data. It enables
powerful operations like filtering and mapping.
```java
// Example using Streams to find the sum of
even numbers
List<Integer> numbers = Arrays.asList(1, 2, 3,
4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
```
- **Default Methods:** Default methods in
interfaces provide a way to add new methods to
existing interfaces without breaking
implementing classes.
```java
// Example of a default method in an interface
interface MyInterface {
default void defaultMethod() {
System.out.println("Default method");
}
}
```
- **Method References:** Method references
simplify lambda expressions by referring to
methods or constructors by name.
```java
// Example of a method reference
List<String> names = Arrays.asList("Alice",
"Bob", "Charlie");
names.forEach(System.out::println);
```
- **Date and Time API:** Java 8 introduced a
modern Date and Time API in the `java.time`
package, addressing the limitations of the older
classes.
```java
// Example using the Date and Time API
LocalDate today = LocalDate.now();
```
- **Optional:** The `Optional` class helps handle
potentially absent values safely and promotes
good coding practices.
```java
// Example using Optional
Optional<String> name =
Optional.ofNullable(getName());
if (name.isPresent()) {
System.out.println("Name: " + name.get());
} else {
System.out.println("Name not available.");
}
```
- **Nashorn JavaScript Engine:** Java 8 replaced
the older Rhino JavaScript engine with Nashorn,
which offers improved JavaScript execution.
**Bytecode and JVM:**
- **Bytecode:** Java source code is compiled into
platform-independent bytecode files (`.class`) by
the Java compiler.
- **Java Virtual Machine (JVM):** The JVM
interprets or compiles bytecode into native
machine code. It manages memory, handles
exceptions, and ensures platform independence.
**Language Basics**
- **Program Structure**- Java programs consist
of classes. The `main()` method serves as the
entry point.
```java
// Example of a Java program structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
```
- **Data Types:** Java has primitive (e.g., `int`,
`char`) and reference (e.g., `String`) data types.
```java
// Example of primitive and reference data
types
int age = 30;
String name = "Alice";
```
- **Identifiers and Variables:** Identifiers are
names for program elements. Variables are
containers for data.
```java
// Example of identifiers and variables
int count = 10;
double price = 29.99;
```
**Writing Programs:**
- **Using `main()`:** The `main()` method is the
entry point for Java programs.
- **Command-line Arguments:** Java programs
can accept command-line arguments.
```java
// Example of using command-line arguments
public static void main(String[] args) {
System.out.println("Arguments received: " +
args.length);
}
```
- **Simple Console Input/Output:** Java provides
classes like `System.out` and `Scanner` for console
I/O.
```java
// Example of simple console input/output
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
```
**Programming with Purpose:**
- **Operators and Expressions:** Java supports
various operators for arithmetic, relational,
logical, and bitwise operations.
```java
// Example of operators and expressions
int x = 10;
int y = 5;
int sum = x + y;
boolean isGreater = x > y;
```
- **Type Conversion Rules:** Java defines rules
for automatic and explicit type casting.
```java
// Example of type conversion rules
int integerNum = 10;
double doubleNum = 5.5;
double result = integerNum + doubleNum; //
Automatic type conversion
int intResult = (int) result; // Explicit type
casting
```
**Control Flow:**
- **If, if/else, and Ternary Operator:** Conditional
statements are used for decision-making based
on conditions.
```java
// Example of conditional statements and
ternary operator
int x = 10
;
int y = 5;
if (x > y) {
System.out.println("x is greater than y");
} else {
System.out.println("y is greater than or
equal to x");
}
// Ternary operator
int max = (x > y) ? x : y;
```
- **Switch:** The `switch` statement allows multi-
branch selection based on the value of an
expression.
```java
// Example of the switch statement
int dayOfWeek = 2;
String day;
switch (dayOfWeek) {
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
default:
day = "Unknown";
}
```
- **While, Do-While, For, For-each Loops:** Java
provides various loop constructs for repetitive
execution.
```java
// Example of loop constructs
int count = 0;
// While loop
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// For loop
for (int i = 0; i < 5; i++) {
System.out.println("i: " + i);
}
// For-each loop
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println("Number: " + number);
}
```
**Declaring and Using Methods:**
- **Methods:** Methods in Java are functions
within classes. They encapsulate behavior and
enhance code organization and reusability.
```java
// Example of declaring and using a method
public int add(int x, int y) {
return x + y;
}
```
**Class Libraries:**
- **Introduction to Classes:** Java provides
standard classes and libraries for various
functionalities.
```java
// Example of using standard classes
String text = "Hello, World!";
Integer integer = 42;
ArrayList<String> names = new ArrayList<>();
Date currentDate = new Date();
```