Comprehensive Java Learning Notes
Comprehensive Java Learning Notes
1. Basics of Programming
- Syntax: Java programs must follow a specific syntax structure. Each program starts with a class definition
and a main method. The main method is the entry point where execution begins.
Example:
```java
```
- Variables: A variable stores data that can be used and modified. Variables have a data type, a name, and a value.
Example:
```java
String name = "John"; // 'name' is a variable of type String with value "John"
```
- Data Types: Java has primitive data types (int, float, char, boolean) and reference types like String and arrays.
- Comments: Comments help describe code. Single-line comments use `//`, and multi-line comments use `/* ... */`.
- Taking Input: Java uses the Scanner class to accept user input. Scanner is part of the java.util package and needs to
be imported.
Example:
```java
import java.util.Scanner; // Importing Scanner class
```
3. Operators
- Arithmetic Operators: These perform mathematical operations like addition, subtraction, etc.
Example:
```java
int a = 5, b = 3;
```
- Relational Operators: Used to compare two values and return true or false.
Example:
```java
```
- Logical Operators: Used for combining conditions. `&&` (AND), `||` (OR), `!` (NOT).
Example:
```java
boolean canEnter = isAdult && hasPermission; // false because both conditions aren't true
```
Example:
```java
```
4. Conditional Statements
Example:
```java
} else {
```
Explanation: The `if` statement checks if `age` is 18 or above. If true, it prints "You are an adult";
5. Looping Structures
- For Loop: Repeats code a set number of times, usually when the number of iterations is known.
Example:
```java
```
Explanation: This loop prints "Hello, World!" five times. The loop variable `i` starts from 0, checks `i < 5`,
- While Loop: Repeats code based on a condition, useful when the number of iterations is not known.
Example:
```java
int i = 0;
while (i < 5) {
System.out.println("Hello, World!");
i++;
```
Explanation: This `while` loop works similarly but only continues while `i` is less than 5.
- Defining Functions: Functions (or methods) allow code reuse. Java functions are defined inside classes.
Example:
```java
System.out.println("Hello, World!");
```
Explanation: The `greet` method is created using `public static void`, meaning it has no return type (`void`).
```java
greet();
```
Example:
```java
return a + b;
```
7. Data Structures
Example:
```java
```
Explanation: `numbers` is an array holding integers. `numbers[0]` accesses the first element.
Example:
```java
import java.util.ArrayList;
```