Java Basics: Common Operators, Methods, Flow Control, Access Modifiers

1. Symbols and Types

1.1 Adding Comments

  • Comments: Explanations of code intended to make code easier to understand. They are essential but do not affect compilation or execution.
  • Java has single-line and multi-line comments:
    • Single-line: // comment
    • Multi-line: /* comment */

1.2 Keywords

  • Keywords: Predefined words in Java with special meaning (e.g., public, class, static, void). They are all lowercase and highlighted in editors like Notepad++.
  • Do not memorize all at once; learn as you go.

1.3 Identifiers

  • Identifiers: Names defined by the programmer for classes, methods, variables, etc.
  • Naming Rules (mandatory):
    • Can contain letters (case-sensitive), digits 0-9, $, and _.
    • Cannot start with a digit.
    • Cannot be a keyword.
  • Naming Conventions (recommended):
    • Class names: PascalCase (e.g., HelloWorld).
    • Method names: camelCase (e.g., helloWorld).
    • Variable names: all lowercase (e.g., total).

1.4 Constants

Type Meaning Example
Integer constant All integers 0, 1, 567, -9
Floating-point constant All decimals 0.0, -0.1, 2.55
Character constant Single character in single quotes 'a', ' ', '好'
String constant Multiple characters in double quotes "A", "Hello", ""
Boolean constant Only two values true, false
Null constant Only one value null
public class ConstantDemo {
    public static void main(String[] args) {
        System.out.println(123);        // integer constant
        System.out.println(0.125);      // floating-point constant
        System.out.println('A');        // character constant (single character)
        System.out.println(true);       // boolean constant
        System.out.println("Hello Java"); // string constant
        // null cannot be printed directly
    }
}

1.5 Variables and Data Types

  • Variable: A value that can change during program execution. Each variable must hold a specific data type.
  • Data Types:
    • Primitive: integer, floating-point, character, boolean.
    • Reference: class, array, interface.

Primitive Data Types

Type Keyword Size Range
Byte byte 1 byte -128 to 127
Short short 2 bytes -32,768 to 32,767
Int (default) int 4 bytes -2^31 to 2^31-1
Long long 8 bytes -2^63 to 2^63-1
Float float 4 bytes 1.4013E-45 to 3.4028E+38
Double (default) double 8 bytes 4.9E-324 to 1.7977E+308
Char char 2 bytes 0 to 65,535
Boolean boolean 1 byte true, false
String (reference) String -- --

Variable Declaration

dataType variableName = value;

Example:

public class VariableDemo {
    public static void main(String[] args) {
        byte byteVar = 100;
        System.out.println(byteVar);

        short shortVar = 1000;
        System.out.println(shortVar);

        int intVar = 123456;
        System.out.println(intVar);

        long longVar = 12345678900L;  // 'L' suffix for long
        System.out.println(longVar);

        float floatVar = 5.5F;  // 'F' suffix for float
        System.out.println(floatVar);

        double doubleVar = 8.5;
        System.out.println(doubleVar);

        boolean flag = false;
        System.out.println(flag);

        char charVar = 'A';
        System.out.println(charVar);
    }
}

Note: Use L for long literals and F for float literals.

1.6 Type Conversion

Automatic Type Conversion

When performing operations, smaller types are automatical promoted to larger types to avoid data loss.

public static void main(String[] args) {
    int intVal = 1;
    byte byteVal = 2;
    // byte result = byteVal + intVal; // Error: int cannot convert to byte
    int result = byteVal + intVal;  // byte promoted to int
    System.out.println(result);
}

Promotion order: byte -> short -> char -> int -> long -> float -> double

Explicit Type Casting

To convert a larger type to a smaller type, use casting.

public static void main(String[] args) {
    short shortVal = 1;
    // shortVal = shortVal + 1; // Error: int cannot be assigned to short
    shortVal = (short)(shortVal + 1); // Cast int to short
    System.out.println(shortVal);
}

1.7 ASCII Encoding Table

Computers store data in binary; encoding tables map human-readable characters to numbers. The ASCII table is one such standard.

(Image: ASCII table showing mapping of characters to decimal values)

2. Operators

2.1 Arithmetic Operators

Operator Meaning
+ Addition, string concatenation
- Subtraction
* Multiplication
/ Division (integer division for integers)
% Modulo (remainder, integer only)
++, -- Increment/decrement

Increment and Decrement

  • Independent operation: ++i and i++ behave the same.
  • Mixed operation:
    • Prefix (++i): increments first, then returns the new value.
    • Postfix (i++): returns the old value, then increments.
public static void main(String[] args) {
    int a = 1;
    int b = ++a;  // a=2, b=2
    System.out.println(a); // 2
    System.out.println(b); // 2

    int x = 1;
    int y = x++;  // x=2, y=1
    System.out.println(x); // 2
    System.out.println(y); // 1
}

String Concatenation with +

When + is used with strings, it performs concatenation.

public static void main(String[] args) {
    System.out.println("5+5=" + 5 + 5); // Output: 5+5=55
}

2.2 Assignment Operators

Operator Example Equivalent to
= a = b Assigns b to a
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a * b
/= a /= b a = a / b
%= a %= b a = a % b
public static void main(String[] args) {
    short s = 1;
    // s = s + 1; // Error: int cannot be assigned to short
    s += 1;  // Equivalent to s = (short)(s + 1)
    System.out.println(s); // 2
}

2.3 Comparison Operators

Operator Meaning Example (true)
== Equal to 1 == 1
!= Not equal to 1 != 2
< Less than 1 < 2
> Greater than 3 > 2
<= Less than or equal 2 <= 2
>= Greater than or equal 3 >= 2

2.4 Logical Operators

Operator Meaning Short-circuit
&& (AND) Both true → true If left is false, right not evaluated
` ` (OR)
! (NOT) Inverts boolean value N/A
public static void main(String[] args) {
    System.out.println(true && true);  // true
    System.out.println(true && false); // false
    System.out.println(false || false); // false
    System.out.println(!true); // false
}

2.5 Ternary Operator

variable = (boolean expression) ? valueIfTrue : valueIfFalse;

Example:

int i = (1 == 2) ? 100 : 200;  // i = 200
int j = (3 <= 4) ? 500 : 600;  // j = 500

2.6 Operations with Constants vs. Variables

public static void main(String[] args) {
    byte b1 = 1;
    byte b2 = 2;
    byte b3 = 1 + 2;   // OK: constants, result within byte range
    // byte b4 = b1 + b2; // Error: variables produce int result
    System.out.println(b3);
}

Reason: When using constants, the compiler can evaluate the expression and if it fits the target type, assignment is allowed. For variables, the result is always promoted to int.

3. Introduction to Methods

Method: A block of code that performs a specific task, defined once and called multiple times to avoid redundancy.

3.1 Method Definition

modifier returnType methodName(parameter list) {
    // code
    return value;
}
  • Modifiers: public, default, private, protected.
  • Return type: void, int, double, etc.
  • Method name: follows identifier rules.
  • Parameters: none yet; covered later.
  • return: optional if return type is void.

Example:

public static void simpleMethod() {
    System.out.println("This is a method.");
}

3.2 Method Invocation

Methods must be called to execute. In main, simply write the method name.

public static void main(String[] args) {
    simpleMethod();
}

public static void simpleMethod() {
    System.out.println("Method called from main.");
}

3.3 Important Points

  • Methods must be defined inside a class but outside other methods.
  • Methods cannot be nested in side another method.
public class Demo {
    public static void main(String[] args) {}
    public static void myMethod() {}   // Correct
}

// Incorrect:
public class Demo {
    public static void main(String[] args) {
        // public static void myMethod() {} // Error: cannot define method inside another
    }
}

4. Flow Control Statements

4.1 Sequence Structure

Statements execute in the order they are written.

public static void main(String[] args) {
    System.out.println("First");
    System.out.println("Second");
    System.out.println("Third");
}

4.2 Conditional Statements

Single if

public static void main(String[] args) {
    int a = 10, b = 20, c = 10;
    if (a == b) {
        System.out.println("a equals b");
    }
    if (a == c) {
        System.out.println("a equals c");
    }
}

if-else

public static void main(String[] args) {
    int num = 1;
    if (num % 2 == 0) {
        System.out.println("Even");
    } else {
        System.out.println("Odd");
    }
}

if-else if-else

public static void main(String[] args) {
    int score = 100;
    if (score < 0 || score > 100) {
        System.out.println("Invalid score");
    } else if (score >= 90) {
        System.out.println("Excellent");
    } else if (score >= 80) {
        System.out.println("Good");
    } else if (score >= 70) {
        System.out.println("Fair");
    } else if (score >= 60) {
        System.out.println("Pass");
    } else {
        System.out.println("Fail");
    }
}

Ternary vs. if

int a = 10, b = 20;
int max;
// Using if-else
if (a > b) {
    max = a;
} else {
    max = b;
}
// Using ternary
max = (a > b) ? a : b;

4.3 switch Statement

switch(expression) {
    case value1:
        // code
        break;
    case value2:
        // code
        break;
    default:
        // code
        break;
}

Example: Rock-Paper-Scissors

public static void main(String[] args) {
    String choice = "scissors";
    switch(choice) {
        case "scissors":
            System.out.println("Rock");
            break;
        case "rock":
            System.out.println("Paper");
            break;
        case "paper":
            System.out.println("Scissors");
            break;
    }
}

Fall-through without break

public static void main(String[] args) {
    int i = 5;
    switch (i) {
        case 0:
            System.out.println("Case 0");
            break;
        case 5:
            System.out.println("Case 5");
        case 10:
            System.out.println("Case 10");
        default:
            System.out.println("Default");
    }
}
// Output:
// Case 5
// Case 10
// Default

4.4 Loop Statemetns

4.4.1 for Loop

Print 9x9 multiplication table:

public static void main(String[] args) {
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            System.out.print(j + "x" + i + "=" + (i * j) + "\t");
        }
        System.out.println();
    }
}

4.4.2 while Loop

Sum numbers from 1 to 100:

public static void main(String[] args) {
    int i = 1, sum = 0;
    while (i <= 100) {
        sum += i;
        i++;
    }
    System.out.println("Sum: " + sum);
}

4.4.3 do-while Loop

Print "JAVA" ten times:

public static void main(String[] args) {
    int count = 1;
    do {
        System.out.println("JAVA");
        count++;
    } while (count <= 10);
}

4.4.4 Differences Between Loops

  • for: Control variable is local to the loop, released after loop ends. Recommended when iteration count is known.
  • while: Used when number of iterations is unknown.
For loop: for (initialization; condition; update) { body }
While loop: while (condition) { body }
Do-while: do { body } while (condition);  // executes at least once

5. Access Modifiers in Java

Order of access: public > protected > default > private

Modifier Same class Same package Subclass (same package) Subclass (different package) Other packages
public Y Y Y Y Y
protected Y Y Y Y(if subclass) / N(if not) N
default Y Y Y N N
private Y N N N N

Note: Interface members cannot be protected.

(Image: Diagram illustrating access levels)

6. Keyboard Input (Scanner)

To read user input, use the Scanner class from java.util package.

import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter name: ");
        String name = scanner.next();

        System.out.print("Enter age: ");
        int age = scanner.nextInt();

        System.out.print("Enter salary: ");
        double salary = scanner.nextDouble();

        System.out.println("Information:");
        System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary);

        scanner.close();
    }
}

Sample output:

Enter name: Alice
Enter age: 25
Enter salary: 50000.0
Information:
Name: Alice, Age: 25, Salary: 50000.0

Tags: java Operators Methods Flow Control Access Modifiers

Posted on Sun, 01 Nov 2026 16:07:26 +0000 by teguh123