Operators & User Input
Arithmetic operators
+ - * / %
7 / 2→3(int ÷ int drops the decimals)7 / 2.0→3.5(one double makes the result a double)7 % 2→1(the remainder; handy for checking even/odd)
Assignment shortcuts
x += 5 means x = x + 5. The same works for -= *= /= %=.
Increment & decrement
int a = 5;
int b = a++; // postfix: b = 5, then a becomes 6
int c = ++a; // prefix: a becomes 7, then c = 7
Comparison operators → boolean
== != > < >= <=
Logical operators
&&AND → true only if both sides are true||OR → true if at least one side is true!NOT → flips true/false
They short-circuit: in a && b, if a is false, b is never checked.
Ternary operator
String result = marks >= 40 ? "Pass" : "Fail";
Comparing Strings ⚠️
Use s1.equals(s2) to compare text. == checks whether both are the same object, which often gives the wrong answer.
Reading user input with Scanner
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.out.print("Your name: ");
String name = sc.nextLine();
System.out.print("Your age: ");
int age = sc.nextInt();
💡 nextInt() leaves the Enter key in the input buffer. Call sc.nextLine() once before reading another line of text.
Example
import java.util.Scanner;
public class MiniCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("First number: ");
int a = sc.nextInt();
System.out.print("Second number: ");
int b = sc.nextInt();
System.out.println("Sum: " + (a + b));
System.out.println("Remainder: " + (a % b));
System.out.println(a % 2 == 0 ? "First is even" : "First is odd");
}
}