




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





class HelloWorld { public static void main(String[] args) { System.out.println("Hello World");
System.out.print("Hello"); // prints without newline System.out.println(" World"); // prints with newline System.out.printf("Age: %d", 20); // formatted output
import java.util.Scanner;
class InputExample {
Primitive Types
Comments
public static void main(String[] args) { Scanner sc = new Scanner(System.in);
String name = sc.nextLine(); // String int age = sc.nextInt(); // int float f = sc.nextFloat(); // float double d = sc.nextDouble(); // double boolean b = sc.nextBoolean(); // boolean char c = sc.next().charAt(0); // char (first char of input)
System.out.println("Name: " + name);
// Single line /* Multi-line / /* Javadoc comment */
Escape Sequences
Type Casting
Widening (automatic)
Narrowing (manual)
int x = 45; double y = x; // OK
double d = 45.9; int n = (int) d; // truncates decimal
Control Flow
if / else if / else
Ternary
switch (Java 7+ supports Strings)
Loops
while
if (x > 0) { ... } else if (x == 0) { ... } else { ... }
String result = (x > 0)? "Positive" : "Negative";
switch(day) { case 1: System.out.println("Mon"); break; ... default: System.out.println("Invalid"); }
while (i < 5) { i++; }
Methods
Method Overloading
Recursion
Strings
static int add(int a, int b) { return a + b; }
public static void main(String[] args) { System.out.println(add(5, 10)); }
void sum(int a, int b) { ... } void sum(double a, double b) { ... }
int fact(int n) { if (n == 0) return 1; return n * fact(n - 1); }
String s = "Hello"; int len = s.length(); s.toUpperCase(); s.toLowerCase(); s.indexOf("l"); s.contains("He");
Math Class
s.equals("Hello"); s.equalsIgnoreCase("hello"); s.substring(0, 3); // "Hel" s.replace("H", "J");
Math.max(5, 10); Math.min(5, 10); Math.sqrt(16); Math.pow(2, 3); Math.abs(-10); Math.random(); // [0.0, 1.0)