Java Basics Cheat Sheet β€” Syntax, Variables, Operators, Print | Dataplexa

Java Basics

Syntax rules  Β·  Variables & types  Β·  Operators  Β·  System.out & Scanner  Β·  Type casting

Sheet 1 of 8 Java 17 LTS Beginner Printable

Java Syntax Rules

must know first
Program Structure
// Every Java app needs a class
public class Main {

  // Entry point β€” always this signature
  public static void main(
      String[] args) {

    System.out.println("Hello!");
  }
}
Blocks & Semicolons
// Curly braces define blocks
if (age > 18) {
  System.out.println("adult");
}

// Every statement ends with ;
int x = 10;
int y = 20;

// Single-line block (no braces)
if (x > 0) System.out.println(x);
Case-Sensitivity & Identifiers
// Java is CASE-SENSITIVE
String name  = "Alice";
String Name  = "Bob";    // different!

// Identifier rules
userName   // camelCase   βœ“
_internal  // leading _   βœ“
value2     // letter+digits βœ“
// 2value   β†’ compile error βœ—
// class    β†’ keyword      βœ—
Key difference from Python: Java uses curly braces { } for blocks and a semicolon ; after every statement. Indentation is convention, not syntax β€” but always indent 2 or 4 spaces consistently.

Variables & Declarations

assignment
Declaring & Initializing
// type varName = value;
int     age    = 25;
double  price  = 9.99;
boolean active = true;
String  name   = "Alice";
char    grade  = 'A';

// Declare first, assign later
int score;
score = 100;

// final = constant (like const)
final double PI = 3.14159;
var β€” Local Type Inference (Java 10+)
// var infers the type automatically
var count  = 42;         // int
var label  = "hello";   // String
var ratio  = 0.5;        // double

// var only works for local variables
// Cannot use in method params or fields
Statically typed: Java requires you to declare the type upfront. Once declared, a variable can only hold that type β€” unlike Python's dynamic typing.

Primitive Data Types

8 primitives
TypeSizeRange / NotesDefault
byte 8-bit -128 to 127 0
short 16-bit -32,768 to 32,767 0
int 32-bit -2.1B to 2.1B 0
long 64-bit huge β€” append L: 100L 0L
float 32-bit ~7 decimal digits, append F0.0f
double 64-bit ~15 decimal digits 0.0d
char 16-bit single Unicode char 'A' '\u0000'
boolean 1-bit true / false only false
Wrapper classes: Each primitive has an object version β€” Integer, Double, Boolean, etc. Needed for Collections and generics.

Numbers & Literals

numeric
Integer Literals
int  a = 42;
int  b = 1_000_000;  // underscores ok
int  c = 0b1010;     // binary  β†’ 10
int  d = 0xFF;        // hex     β†’ 255
long e = 9876543210L; // L suffix!
Float, Double & Math Methods
float  f = 3.14f;       // f suffix
double d = 3.14159;
double e = 1.5e3;       // 1500.0

Math.abs(-9)             // 9
Math.round(3.7)          // 4L
Math.pow(2, 8)           // 256.0
Math.max(10, 20)         // 20
Math.sqrt(16.0)          // 4.0
int Γ· int = int: 10 / 3 gives 3, not 3.33. Cast at least one operand: (double)10 / 3 β†’ 3.333…

String β€” Reference Type

java.lang.String
Creating & Common Methods
String s = "Hello, World!";

s.length()           // 13
s.toUpperCase()      // "HELLO, WORLD!"
s.toLowerCase()      // "hello, world!"
s.charAt(0)          // 'H'
s.substring(7, 12)   // "World"
s.contains("World")  // true
s.replace("World", "Java")
s.trim()             // strips whitespace
s.split(",")          // String[]
Concatenation & Text Blocks
// Concatenation with +
String msg = "Hi " + name + "!";

// String.format (like printf)
String r = String.format(
  "%.2f", 3.14159);     // "3.14"

// Text block (Java 15+)
String json = """
    {
      "name": "Alice"
    }
    """;
Never use == to compare Strings. Use .equals() β€” otherwise you compare memory addresses, not content.

Type Conversion & Casting

casting
Widening (Automatic) β€” small β†’ big
int    i = 42;
double d = i;         // 42.0 β€” safe, auto
long   l = i;         // 42L  β€” safe, auto

// byte β†’ short β†’ int β†’ long β†’ float β†’ double
Narrowing (Explicit Cast) β€” big β†’ small
double d = 9.99;
int    i = (int) d;   // 9 β€” truncates!

long  big = 300L;
byte  b   = (byte) big; // 44 β€” overflow!
String ↔ Primitive Conversions
// String β†’ primitive
int    n = Integer.parseInt("42");
double d = Double.parseDouble("3.14");
boolean b = Boolean.parseBoolean("true");

// primitive β†’ String
String s = String.valueOf(42);  // "42"
String t = Integer.toString(42);
Narrowing can lose data. Always use explicit cast syntax (type) when converting from a larger to a smaller type, and watch for overflow.

Operators

arithmetic Β· comparison Β· logical Β· bitwise Β· ternary
Arithmetic
10 +  3   // 13   β€” addition
10 -  3   // 7    β€” subtraction
10 *  3   // 30   β€” multiplication
10 /  3   // 3    β€” integer division!
10 %  3   // 1    β€” modulo (remainder)
// No ** in Java β€” use Math.pow()

// Increment / Decrement
x++  x--         // post
++x  --x         // pre
Comparison & Logical
// Comparison β€” returns boolean
x == y    // equal (value)
x != y    // not equal
x >  y    // greater than
x <  y    // less than
x >= y    // greater or equal
x <= y    // less or equal

// Logical operators
a && b    // AND (short-circuit)
a || b    // OR  (short-circuit)
!a         // NOT
Ternary & instanceof
// Ternary β€” condition ? yes : no
int max = (a > b) ? a : b;
String s = (age >= 18)
    ? "adult"
    : "minor";

// instanceof β€” type check
if (obj instanceof String) {
  String t = (String) obj;
}
Augmented Assignment
x +=  1    // x = x + 1
x -=  1    // x = x - 1
x *=  2    // x = x * 2
x /=  2    // x = x / 2
x %=  3    // x = x % 3
Operator Precedence β€” high β†’ low
  • ++ -- !Unary / logical NOT
  • * / %Multiply, divide, modulo
  • + -Addition and subtraction
  • < <= > >= instanceofComparisons
  • == !=Equality comparisons
  • &&Logical AND
  • ||Logical OR
  • ? :Ternary (lowest)

System.out & Scanner (I/O)

I / O
System.out β€” print methods
// println β€” adds newline
System.out.println("Hello!");

// print β€” no newline
System.out.print("Hi ");
System.out.print("there\n");

// printf β€” formatted output
System.out.printf(
  "Pi = %.2f%n", 3.14159);
// %n = newline (portable)
printf / String.format specifiers
// Common format specifiers
%d    // integer
%f    // floating-point
%.2f  // float, 2 decimal places
%s    // String
%c    // char
%b    // boolean
%10d  // right-align in 10 chars
%-10s // left-align in 10 chars
%n    // platform newline
Scanner β€” reading user input
import java.util.Scanner;

Scanner sc = new Scanner(
                System.in);

String  name  = sc.nextLine();
int     age   = sc.nextInt();
double  price = sc.nextDouble();
boolean flag  = sc.nextBoolean();

sc.close();  // close when done
Scanner pitfall: After nextInt() or nextDouble(), call sc.nextLine() once to consume the leftover newline before reading the next String with nextLine().

Comments & Javadoc

documentation
// Single-line comment

/* Multi-line
   block comment */

/**
 * Javadoc comment β€” used by IDEs and docs.
 *
 * @param  a First number
 * @param  b Second number
 * @return   Sum of a and b
 */
public static int add(int a, int b) {
  return a + b;
}
Javadoc tags: @param for parameters, @return for return value, @throws for exceptions. Run javadoc to generate HTML docs.

Naming Conventions

Java standards
WhatStyleExample
Variable camelCase userName
Method camelCase getData()
Class PascalCase UserProfile
Interface PascalCase Comparable
Constant UPPER_CASE MAX_SIZE
Package lowercase com.company.app
Enum PascalCase DayOfWeek
Enum value UPPER_CASE MONDAY
Java constants are declared public static final TYPE NAME. No standalone constants outside a class.

Common Beginner Errors

debug guide
Compile-Time Errors
// Missing semicolon
int x = 5   // ← Error!
int x = 5;  // ← Fixed

// Wrong type assignment
int y = "hello";  // ← Error!
String y = "hello"; // ← Fixed

// Undeclared variable
System.out.println(count); // Error if not declared!
Runtime Exceptions
// NullPointerException
String s = null;
s.length();   // NPE! Check != null first

// ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
arr[5];        // Error! max index = 2

// ClassCastException
Object o = "text";
int n = (int) o;   // Error! wrong cast
String Comparison Trap
String a = new String("hello");
String b = new String("hello");

a == b            // false! (diff objects)
a.equals(b)       // true  βœ“ use this!
a.equalsIgnoreCase(b) // case-insensitive

// Safe null-first comparison
"hello".equals(a)  // prevents NPE

Java Basics Mastery Checklist

sheet 1 complete
SyntaxKey point
Write a valid Java class + main methodpublic static void main
Use curly braces for blocks{ }
End every statement;
Name variables correctlycamelCase
Variables & TypesKey point
Know the 8 primitive typesint double char boolean…
Declare type before useint x = 5;
Widen vs narrow casting(int) double
Parse String to numberInteger.parseInt()
Operators & I/OKey point
Arithmetic operators + int/int trap/ β†’ 3 not 3.33
Comparison & logical operators== != && || !
Format outputprintf("%.2f", x)
Read user inputScanner sc = new Scanner(…)
Next up β†’ Sheet 2: Java Collections  Β·  ArrayList Β· LinkedList Β· HashMap Β· HashSet Β· Queue Β· Iterator β€” every built-in collection with methods, iteration patterns, and real-world use cases.