This site compiles Java using Java 8 language rules. These standalone examples put their entry method, main, inside a class. Helper classes and method-only answers do not need their own main. System.out.println(...) prints a line; System.out.print(...) prints with no new line.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.println("I am learning Java.");
}
}
public class Main {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println(a / b); // 3 (integer division)
System.out.println(a % b); // 1
double x = 7.0 / 2; // 3.5 (one side is double)
System.out.println(x);
}
}
public class Main {
public static void main(String[] args) {
String s = "Hello";
System.out.println(s.length()); // 5
System.out.println(s.toUpperCase()); // HELLO
System.out.println(Math.max(3, 9)); // 9
System.out.println(Integer.parseInt("42") + 1); // 43
}
}
Math.random() คืนค่า random double จาก 0.0 ไปจนถึง (แต่ไม่รวม) 1.0. ขยายสเกลและ cast เพื่อได้จำนวนเต็ม — นี่คือ AP idiom:
public class Main {
public static void main(String[] args) {
// a random whole number from 1 to 6 (a dice roll)
int roll = (int) (Math.random() * 6) + 1;
System.out.println(roll >= 1 && roll <= 6); // true
}
}
public class Main {
public static void main(String[] args) {
double pi = 3.99;
System.out.println((int) pi); // 3
int total = 7, n = 2;
System.out.println((double) total / n); // 3.5
}
}
if รัน block เมื่อเงื่อนไขเป็นจริง; else if และ else เพิ่มกรณีอื่นๆ. เงื่อนไขอยู่ใน ( ), block อยู่ใน { }.
public class Main {
public static void main(String[] args) {
int score = 72;
if (score >= 80) {
System.out.println("A");
} else if (score >= 60) {
System.out.println("B");
} else {
System.out.println("fail");
}
}
}
public class Main {
public static void main(String[] args) {
int age = 16;
boolean member = true;
System.out.println(age >= 18 && member); // false
String a = "hi";
System.out.println(a.equals("hi")); // true
}
}
3.3
สวิตช์
switch เลือกจากหลายค่าที่กำหนดไว้. แต่ละ case ลงท้ายด้วย break; default เป็นค่าสำรอง.
public class Main {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.println("Mon"); break;
case 3: System.out.println("Wed"); break;
default: System.out.println("other");
}
}
}
ข้อผิดพลาดที่พบบ่อย
เงื่อนไขต้องเป็น boolean; if (x = 5) ไม่ compile (ใช้ ==).
แต่ละ switch case ต้องมี break;, ถ้าไม่มี control จะไหลไป case ถัดไป.
while ลูปจะซ้ำwhileเงื่อนไขเป็นจริง เปลี่ยนแปลงบางอย่างภายในหรือมันจะวนลูปตลอดไป
public class Main {
public static void main(String[] args) {
int n = 1;
while (n <= 3) {
System.out.println(n);
n++;
}
}
}
while ตรวจสอบเงื่อนไขก่อนแต่ละรอบของบอดี้
4.2
ลูป for
A for loop บรรจุการเริ่มต้น, เงื่อนไข, และขั้นตอนในบรรทัดเดียว. ดีที่สุดเมื่อคุณทราบจำนวนรอบ.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}
System.out.println(); // 0 1 2 3 4
}
}
public class Main {
public static void main(String[] args) {
int total = 0;
for (int i = 1; i <= 5; i++) {
total += i;
}
System.out.println(total); // 15
}
}
4.4
Nested loops
Loop Within a loop คือ nested loop. Inner loop รันเต็มรูปแบบในแต่ละรอบของ outer loop.
public class Main {
public static void main(String[] args) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
System.out.print("*");
}
System.out.println();
}
}
}
ข้อผิดพลาดที่พบบ่อย
for (int i = 0; i < n; i++) รัน n ครั้ง (0 ถึง n - 1); การใช้ <= จะรันเพิ่มอีกหนึ่งครั้ง.
อย่าใส่เครื่องหมายกึ่งทวิภาคต่อท้าย for (...) หรือ while (...) — มันจะทำให้เกิด empty loop.
ประกาศตัวนับใน header ของ for เพื่อให้ scope สิ้นสุดพร้อม loop.
public class Main {
public static void main(String[] args) {
String s = "Python";
System.out.println(s.length()); // 6
System.out.println(s.charAt(0)); // P
System.out.println(s.substring(0, 3)); // Pyt
System.out.println(s.toUpperCase()); // PYTHON
}
}
Methods ที่คุณจะใช้ทุกวัน:
Method
ความหมาย
ตัวอย่าง → ผลลัพธ์
.length()
จำนวน字符
"Hi".length() → 2
.charAt(i)
ตัวอักษรเดียว
"Hi".charAt(0) → H
.substring(a, b)
ส่วน, หยุดก่อน b
"Python".substring(0, 3) → Pyt
.substring(a)
จาก a ไปจนจบ
"Python".substring(3) → hon
.indexOf(x)
ตำแหน่งแรก, -1 ถ้าไม่มี
"banana".indexOf("na") → 2
.equals(s)
ข้อความเดียวกัน?
"hi".equals("hi") → true
.compareTo(s)
ลำดับ: ลบ / 0 / บวก
"apple".compareTo("banana") → ลบ
compareTo เรียงลำดับ String ตามลำดับพจนานุกรม — การสอบ AP ใช้วิธีการนี้ในการเรียงลำดับคำถาม:
public class Main {
public static void main(String[] args) {
String a = "apple", b = "banana";
System.out.println(a.compareTo(b) < 0); // true (apple comes first)
System.out.println(a.compareTo("apple")); // 0 (equal)
}
}
public class Main {
public static void main(String[] args) {
String word = "banana";
int count = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') count++;
}
System.out.println(count); // 3
}
}
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(" ");
}
System.out.println(sb.toString().trim()); // 1 2 3 4 5
}
}
ข้อผิดพลาดที่พบบ่อย
Strings are immutable: s.toUpperCase() return a new String, ดังนั้นเก็บผลลัพธ์.
อ่าน character ด้วย s.charAt(i); ความยาวคือ s.length() (method, with ()).
การสร้าง String ด้วย += ใน big loop ช้า; ใช้ StringBuilder.
ใช้ลูปวนผ่านอาร์เรย์เพื่อหาค่าสูงสุด, ผลรวม, จำนวน หรือค้นหา ค่า for (int x : a) (for-each loop) จะอ่านค่าแต่ละตัวตามลำดับ
public class Main {
public static void main(String[] args) {
int[] a = {3, 9, 2, 7};
int max = a[0], total = 0;
for (int x : a) {
if (x > max) max = x;
total += x;
}
System.out.println(max + " " + total); // 9 21
}
}
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
for (int n : new int[]{4, 7, 4, 9, 4}) nums.add(n);
// Remove every 4 — loop backwards so removals don't skip items.
for (int i = nums.size() - 1; i >= 0; i--) {
if (nums.get(i) == 4) nums.remove(i);
}
System.out.println(nums); // [7, 9]
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex", 3);
System.out.println(d.describe()); // Rex is 3 years old
d.haveBirthday();
System.out.println(d.describe()); // Rex is 4 years old
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) { // constructor
this.name = name;
this.age = age;
}
public String describe() {
return name + " is " + age + " years old";
}
public void haveBirthday() {
age++;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Counter.made()); // 0
new Counter();
new Counter();
System.out.println(Counter.made()); // 2
}
}
class Counter {
private static int count = 0; // shared by ALL Counter objects
public Counter() { count++; }
public static int made() { // called on the class: Counter.made()
return count;
}
}
Fields store state; constructor builds; methods act
public class Main {
public static void main(String[] args) {
Account a = new Account(100);
a.deposit(50);
a.deposit(-999); // rejected by the guard
System.out.println(a.getBalance()); // 150
}
}
class Account {
private int balance; // hidden from outside
public Account(int start) {
balance = start;
}
public void deposit(int amount) {
if (amount > 0) balance += amount; // this guard checks the deposit amount
}
public int getBalance() { // accessor (getter)
return balance;
}
}
ข้อผิดพลาดที่พบบ่อย
Constructor มีชื่อคลาสและไม่มีการ return type (แม้แต่ void ก็ไม่มี)
public class Main {
public static void main(String[] args) {
Cat c = new Cat("Milo");
c.eat(); // Milo is eating (inherited from Animal)
c.speak(); // Meow (Cat's own method)
}
}
class Animal {
protected String name;
public Animal(String name) { this.name = name; }
public void eat() { System.out.println(name + " is eating"); }
}
class Cat extends Animal {
public Cat(String name) { super(name); } // call Animal's constructor
public void speak() { System.out.println("Meow"); }
}
Cat และ Dog สืบทอด Animal: พวกมันสืบทอดสมาชิกจาก Animal และเพิ่มสมาชิกของตัวเอง
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Square(3) };
for (Shape s : shapes) {
System.out.println(s); // each calls its own toString
}
}
}
class Shape {
public String toString() { return "a shape"; }
}
class Circle extends Shape {
private int r;
public Circle(int r) { this.r = r; }
public String toString() { return "Circle r=" + r; } // override
}
class Square extends Shape {
private int side;
public Square(int side) { this.side = side; }
public String toString() { return "Square side=" + side; } // override
}
Recursion คือเมธอดที่เรียกตัวเอง ทุก recursion ต้องการ base case (จุดหยุด) และ recursive call ที่เข้าใกล้มัน หากไม่มี base case จะไม่หยุดและ crash ด้วย stack overflow
public class Main {
public static void main(String[] args) {
System.out.println(factorial(5)); // 120
}
public static int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive call: n * (n-1)!
}
}
public class Main {
public static void main(String[] args) {
System.out.println(reverse("PYTHON")); // NOHTYP
}
static String reverse(String s) {
if (s.length() <= 1) return s; // base case
return reverse(s.substring(1)) + s.charAt(0);
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1, 7, 3};
mergeSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a)); // [1, 2, 3, 5, 7, 9]
}
static void mergeSort(int[] a, int lo, int hi) {
if (lo >= hi) return; // base case: one element
int mid = (lo + hi) / 2;
mergeSort(a, lo, mid); // sort the left half
mergeSort(a, mid + 1, hi); // sort the right half
merge(a, lo, mid, hi); // merge the two halves
}
static void merge(int[] a, int lo, int mid, int hi) {
int[] tmp = new int[hi - lo + 1];
int i = lo, j = mid + 1, k = 0;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else tmp[k++] = a[j++];
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = 0; k < tmp.length; k++) a[lo + k] = tmp[k];
}
}
public class Main {
public static void main(String[] args) {
int[] a = {2, 5, 8, 12, 16, 23}; // sorted, so binary search works
System.out.println(linear(a, 12)); // 3
System.out.println(binary(a, 12)); // 3
System.out.println(binary(a, 9)); // -1 (not found)
}
static int linear(int[] a, int target) {
for (int i = 0; i < a.length; i++)
if (a[i] == target) return i;
return -1;
}
static int binary(int[] a, int target) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1, 7};
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++)
if (a[j] < a[min]) min = j;
int t = a[min]; a[min] = a[i]; a[i] = t; // swap into place
}
System.out.println(Arrays.toString(a)); // [1, 2, 5, 7, 9]
}
}
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1, 7};
for (int i = 1; i < a.length; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) { // shift bigger values right
a[j + 1] = a[j];
j--;
}
a[j + 1] = key; // drop key into the gap
}
System.out.println(Arrays.toString(a)); // [1, 2, 5, 7, 9]
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Real file: Scanner in = new Scanner(new File("scores.txt"));
String data = "Alice 80\nBob 95\nCara 72";
Scanner in = new Scanner(data);
int total = 0, count = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
String[] parts = line.split(" "); // break the line on the space
total += Integer.parseInt(parts[1]);
count++;
}
System.out.println("average = " + (total / count)); // average = 82
}
}
Scanner reads lines while hasNextLine is true
12.2
ประเภทคำถาม FRQ ของ AP
การสอบ AP CS A มีคำถามแบบตอบเอง (free-response) สี่ข้อ แต่ละข้อมีรูปแบบคงที่ดังนี้:
ทักษะที่ใช้คือสิ่งเดิมเสมอ: อ่านสเปก, เขียน method ตามที่ระบุไว้พอดี, Return type ที่ถูกต้อง
public class Main {
public static void main(String[] args) {
// Q1 style: implement a method to a spec, then it is tested.
System.out.println(countEven(new int[]{4, 7, 10, 3, 6})); // 3
}
/** Returns how many values in arr are even. */
public static int countEven(int[] arr) {
int count = 0;
for (int x : arr)
if (x % 2 == 0) count++;
return count;
}
}