Java Basics

Lesson 0001 — 30 min read

Write Once, Run Anywhere — Java is a high-level, class-based, object-oriented programming language. Compiled Java code runs on all platforms that support Java without recompilation.

1. Sample Code

The most basic Java program: Hello World.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

Understanding the Parts

2. Comments

Ignored by the compiler; for humans to read.

// This is a single line comment

/*
   This is a
   multi-line comment
*/

3. Data Types

Java has 8 primitive data types:

Type Size Range / Usage
byte 1 byte -128 to 127
short 2 bytes integers
int 4 bytes Most common integer type
long 8 bytes large integers
float 4 bytes decimals, needs f suffix (e.g. 3.14f)
double 8 bytes Most common for decimals
char 2 bytes single character, e.g. 'A'
boolean 1 bit true or false

4. Operators

Arithmetic

+   Addition
-   Subtraction
*   Multiplication
/   Division
%   Modulo (remainder)

Unary

++  Increment (increase by 1)
--  Decrement (decrease by 1)
!   Logical NOT (inverts boolean)

Relational

==  Equal to
!=  Not equal to
>   Greater than
<   Less than
>=  Greater than or equal to
<=  Less than or equal to

Logical

&&  Logical AND — true if both are true
||  Logical OR — true if at least one is true

Assignment

=   Assignment
+=  Add and assign
-=  Subtract and assign
*=  Multiply and assign
/=  Divide and assign
%=  Modulo and assign

5. Strings

Strings are objects in Java, not primitives. They are immutable — modifying creates a new object.

String s1 = "Hello";
char[] arr = {'W', 'o', 'r', 'l', 'd'};
String s2 = new String(arr);          // char array to string
System.out.println(s1 + " " + s2);    // Concatenation: Hello World
System.out.println(s1.charAt(1));     // Char at index 1: 'e'
System.out.println(s1.length());      // Length: 5
System.out.println(s1.substring(0, 2)); // "He"
System.out.println(s1.equals("Hello")); // Content equality: true

6. Input / Output

Use the Scanner class for input.

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        String name = sc.next();
        System.out.println(name + " is " + age);
        sc.close();
    }
}

7. Type Casting

Converting one data type to another.

int myInt = 9;
double myDouble = myInt;     // Automatic: 9.0

double pi = 9.78;
int heavyInt = (int) pi;     // Manual: 9 (fraction lost)

8. Constants

Use final to create constants.

final float PI = 3.14f;
// PI = 3.15f;  // Error — cannot reassign a final variable

9. Arrays

int[] scores = {90, 80, 70};
System.out.println(scores.length); // 3
System.out.println(scores[0]);     // 90

// For-Each Loop
for (int i : scores) {
    System.out.println(i);
}

// 2D Array
int[][] matrix = { {1, 2}, {3, 4} };

10. Conditional Statements

If, Else If, Else

int marks = 85;

if (marks > 90) {
    System.out.println("A");
} else if (marks > 80) {
    System.out.println("B");
} else {
    System.out.println("C");
}
// Output: B

Switch

int day = 2;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Invalid");
}
// Output: Tuesday

break prevents fall-through to the next case. default runs when no case matches.

11. Loops

For Loop

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

While Loop

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

Do-While Loop

int i = 0;
do {
    System.out.println(i);  // Runs at least once
    i++;
} while (i < 5);

12. Exception Handling

try {
    int[] myNumbers = {1, 2, 3};
    System.out.println(myNumbers[10]);  // Error — index out of bounds
} catch (Exception e) {
    System.out.println("Something went wrong.");
} finally {
    System.out.println("The 'try catch' is finished.");
}

Quick check: What does this print?

int x = 5;
int y = ++x + x--;
System.out.println(y);

Code trace: What does this print?

double d = 9.78;
int x = (int) d;
System.out.println(x);

Summary

Primary source: Oracle Java Tutorials — OOP Concepts. Practice writing these snippets to get comfortable with Java syntax. Ask me anything that's unclear.

Notes

Java basics :-

Entry point ⇒ public static void main(String[] args)

System.out.println ⇒ prints + newline

Data types :-

a) Primitives ⇒ 8 types ; stored by value, not object

b) int ⇒ default integer ; double ⇒ default decimal

c) String ⇒ object ⇒ primitive ; immutable (eg .concat() returns new object)

Operators :-

a) Arithmetic ⇒ + - * / %

b) Unary ⇒ ++ -- ! — pre-increment (++x) vs post-increment (x++)

c) Relational ⇒ == != > < >= <=

d) Logical ⇒ && ||

e) Object equality ⇒ == checks reference ; .equals() checks content

Control flow :-

Decision ⇒ if-else ; switch needs break → fall-through

Loops:

a) for ⇒ known iterations ; for (Type x : coll) ⇒ for-each

b) while ⇒ condition first ; do-while ⇒ runs at least once

Safety :-

try-catch-finally:

a) try ⇒ risky code

b) catch ⇒ handle exception (eg Exception e)

c) finally ⇒ always runs (eg cleanup, close resources)

Gotchas :-

a) final ⇒ constant ; variable can't be reassigned

b) Narrowing cast ⇒ explicit (int) ; fraction lost ⇒ automatic

c) Scanner ⇒ sc.close() to release resource

Next: OOP Fundamentals →

Questions? Ask your agent — you can follow up on any concept, quiz answer, or how this applies to a specific coding problem. Review the Java glossary or syntax quick reference for a compressed overview.