Java Learning Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Java Learning Notes

1. Basics of Programming

- Syntax: Java programs start with a class definition and contain a main method to run the code.

Example:

```java

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

```

- Variables: Used to store data.

Example:

```java

int age = 25;

String name = "John";

```

- Data Types: Java has primitive data types like int, float, char, etc., and reference types like String.

- Comments: Use `//` for single-line comments, and `/* ... */` for multi-line comments.

2. Input and Output

- Taking Input: Using Scanner class for user input.

Example:

```java

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);


System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.println("Hello, " + name);

```

- Displaying Output: Using `System.out.println()` to print output.

3. Operators

- Arithmetic Operators: `+`, `-`, `*`, `/`, `%`.

Example:

```java

int a = 5, b = 3;

int sum = a + b; // sum is 8

```

- Relational Operators: `==`, `!=`, `>`, `<`, `>=`, `<=`.

- Logical Operators: `&&`, `||`, `!`.

- Assignment Operators: `=`, `+=`, `-=`.

4. Conditional Statements

- If Statements: Used to execute code conditionally.

Example:

```java

int age = 18;

if (age >= 18) {

System.out.println("You are an adult.");

} else {

System.out.println("You are a minor.");

```
5. Looping Structures

- For Loop: Repeats code a set number of times.

Example:

```java

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

System.out.println("Hello, World!");

```

- While Loop: Repeats code based on a condition.

Example:

```java

int i = 0;

while (i < 5) {

System.out.println("Hello, World!");

i++;

```

6. Functions and Methods

- Defining Functions: Functions in Java are created with `public`, `static`, and `void` keywords (in simple cases).

Example:

```java

public static void greet() {

System.out.println("Hello, World!");

```

- Calling Functions:
Example:

```java

greet();

```

- Return Values: Methods can return values of specified data types.

7. Data Structures

- Arrays: Used to store multiple values of the same type.

Example:

```java

int[] numbers = {1, 2, 3, 4, 5};

System.out.println(numbers[0]);

```

- ArrayList (from java.util package): Dynamic arrays.

Example:

```java

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<String>();

list.add("Hello");

System.out.println(list.get(0));

```

You might also like