Java Syntax เบื้องต้น, ตัวแปร, ชนิดข้อมูล, Operator, I/O

บทนำ: ก่อนเขียนโปรแกรมจริง

เมื่อเริ่มเขียนโปรแกรม Java ต้องเข้าใจ ภาษาของ Java คือ ไวยากรณ์ (Syntax) ที่ Java ใช้ เพื่อสื่อสารกับคอมพิวเตอร์ได้ถูกต้อง

ส่วนนี้จะเรียนรู้พื้นฐาน:

  • ตัวแปร (Variables) – ที่เก็บข้อมูล
  • ชนิดข้อมูล (Data Types) – ประเภทของข้อมูล
  • Operator – สัญลักษณ์ทำการต่างๆ
  • Input/Output – รับข้อมูลและแสดงผล
ยาวไปอยากเลือกอ่าน
  1. บทนำ: ก่อนเขียนโปรแกรมจริง
  2. ตัวแปร (Variables): กล่องเก็บข้อมูล
  3. ตัวแปรคืออะไร?
  4. การประกาศตัวแปร (Variable Declaration)
  5. การกำหนดค่าให้ตัวแปร (Assignment)
  6. การประกาศและกำหนดค่าพร้อมกัน (Initialization)
  7. Naming Convention: ตั้งชื่อตัวแปรให้ถูกต้อง
  8. ชนิดข้อมูล (Data Types)
  9. ชนิดข้อมูล: การจำแนกข้อมูล
  10. Primitive Data Types: ชนิดพื้นฐาน
  11. 1. Integer Types: เก็บจำนวนเต็ม
  12. 2. Floating-Point Types: เก็บจำนวนทศนิยม
  13. 3. Character Type: เก็บตัวอักษร
  14. 4. Boolean Type: เก็บค่าจริง-เท็จ
  15. Reference Data Types: สั้นๆ
  16. Operator: สัญลักษณ์การทำงาน
  17. Operator คืออะไร?
  18. 1. Arithmetic Operators: คณิตศาสตร์
  19. 2. Assignment Operators: กำหนดค่า
  20. 3. Comparison Operators: เปรียบเทียบ
  21. 4. Logical Operators: ตรรกะ
  22. 5. Increment/Decrement Operators: เพิ่มลด
  23. 6. Ternary Operator: เงื่อนไข 3 ส่วน
  24. Input/Output: รับและแสดงข้อมูล
  25. Output: แสดงข้อมูล
  26. 1. System.out.print()
  27. 2. System.out.println()
  28. 3. System.out.printf()
  29. ตัวอย่างการแสดงผลทั้งหมด
  30. Input: รับข้อมูล
  31. Scanner: อ่านข้อมูลจาก User
  32. ตัวอย่าง: โปรแกรมรับข้อมูลและแสดงผล
  33. ตัวอย่าง: โปรแกรมคำนวณเกรด
  34. Escape Sequences: ตัวเลขพิเศษ
  35. สรุป: Syntax, Variables, Data Types, Operators, I/O
  36. ตัวอย่างการใช้ทั้งหมดรวมกัน

ตัวแปร (Variables): กล่องเก็บข้อมูล

ตัวแปรคืออะไร?

ตัวแปร คือ ชื่อที่ตั้งให้กับหน่วยความจำ เพื่อ เก็บข้อมูล ในโปรแกรม

คิดง่ายๆ ตัวแปร = กล่องที่มีป้ายกำกับ ใช้เก็บสิ่งของ (ข้อมูล)

textตัวแปร: age
┌─────────────┐
│    25       │  ← ค่า (value)
└─────────────┘
  age (ชื่อ)

ตัวแปร: name
┌──────────────┐
│   "John"     │  ← ค่า (value)
└──────────────┘
  name (ชื่อ)

การประกาศตัวแปร (Variable Declaration)

Syntax:

java[data type] [variable name];

ตัวอย่าง:

javaint age;           // ประกาศตัวแปร age ชนิด int
String name;       // ประกาศตัวแปร name ชนิด String
double salary;     // ประกาศตัวแปร salary ชนิด double
boolean isActive;  // ประกาศตัวแปร isActive ชนิด boolean

การกำหนดค่าให้ตัวแปร (Assignment)

Syntax:

javavariable_name = value;

ตัวอย่าง:

javaage = 25;              // กำหนดค่า 25 ให้ age
name = "John";         // กำหนดค่า "John" ให้ name
salary = 30000.50;     // กำหนดค่า 30000.50 ให้ salary
isActive = true;       // กำหนดค่า true ให้ isActive

การประกาศและกำหนดค่าพร้อมกัน (Initialization)

javaint age = 25;
String name = "John";
double salary = 30000.50;
boolean isActive = true;

Naming Convention: ตั้งชื่อตัวแปรให้ถูกต้อง

Java มีกฎการตั้งชื่อตัวแปร:

ต้องปฏิบัติตาม:

  • ชื่อเริ่มด้วยตัวอักษร (a-z, A-Z) หรือ underscore (_)
  • ไม่มีช่องว่าง
  • ไม่ใช้ reserved words (คำสงวน เช่น int, class, public)
  • Case-sensitive (age ≠ Age ≠ AGE)

ตัวอย่างชื่อตัวแปรที่ถูกต้อง:

javaint age;
String firstName;
double _price;
boolean is_active;
long maxValue;

ตัวอย่างชื่อตัวแปรที่ไม่ถูกต้อง:

javaint 1age;           // ❌ เริ่มด้วยตัวเลข
String first-name;  // ❌ มีเครื่องหมาย -
double my price;    // ❌ มีช่องว่าง
int class;          // ❌ ใช้ reserved word

Convention นิยม: camelCase

ในสมาชิกฝ่าย Java ใช้ camelCase สำหรับตัวแปร:

  • ตัวแรกเป็นอักษรเล็ก
  • ตัวแรกของคำถัดไปเป็นอักษรใหญ่
javaint studentAge;           // ✓ Good
String firstNameOfStudent; // ✓ Good
double accountBalance;     // ✓ Good
boolean isValidEmail;      // ✓ Good

ชนิดข้อมูล (Data Types)

ชนิดข้อมูล: การจำแนกข้อมูล

Data Type บอกว่า ตัวแปรจะเก็บข้อมูลชนิดไหน และ ใช้หน่วยความจำเท่าไหร่

Java มี 2 กลุ่ม ชนิดข้อมูล:

  1. Primitive Data Types – ชนิดข้อมูลพื้นฐาน
  2. Reference Data Types – ชนิดข้อมูลอ้างอิง (ต่อไปจะเรียน)

Primitive Data Types: ชนิดพื้นฐาน

1. Integer Types: เก็บจำนวนเต็ม

ชนิดขนาดช่วงตัวอย่าง
byte1 byte (8 bits)-128 ถึง 127byte age = 25;
short2 bytes (16 bits)-32,768 ถึง 32,767short year = 2025;
int4 bytes (32 bits)-2,147,483,648 ถึง 2,147,483,647int population = 70000000;
long8 bytes (64 bits)±9.22 × 10^18long largeNumber = 9223372036854775807L;

ตัวอย่าง:

javapublic class IntegerDemo {
    public static void main(String[] args) {
        byte smallAge = 25;           // ขนาดเล็ก
        short productQuantity = 5000;
        int population = 70000000;
        long astronomicalDistance = 9223372036854775807L;  // ต้อง L ในตัวเลข
        
        System.out.println("Byte: " + smallAge);
        System.out.println("Short: " + productQuantity);
        System.out.println("Int: " + population);
        System.out.println("Long: " + astronomicalDistance);
    }
}

Output:

textByte: 25
Short: 5000
Int: 70000000
Long: 9223372036854775807

เลือกชนิดไหน?

  • ใช้ int เป็นค่าเริ่มต้น (ใช้มากที่สุด)
  • ใช้ long ถ้าตัวเลขใหญ่มาก
  • ใช้ byte หรือ short เมื่อต้องประหยัด memory (หลัก)

2. Floating-Point Types: เก็บจำนวนทศนิยม

ชนิดขนาดช่วงตัวอย่าง
float4 bytes (32 bits)±3.40 × 10^38float price = 99.99f;
double8 bytes (64 bits)±1.80 × 10^308double pi = 3.14159;

ตัวอย่าง:

javapublic class FloatingPointDemo {
    public static void main(String[] args) {
        float price = 99.99f;           // ต้อง f ในตัวเลข
        double pi = 3.14159;
        double salary = 25500.75;
        
        System.out.println("Price: " + price);
        System.out.println("Pi: " + pi);
        System.out.println("Salary: " + salary);
        
        // การคำนวณ
        double area = pi * 5 * 5;  // πr²
        System.out.println("Area of circle (r=5): " + area);
    }
}

Output:

textPrice: 99.99
Pi: 3.14159
Salary: 25500.75
Area of circle (r=5): 78.53975

เลือกชนิดไหน?

  • ใช้ double เป็นค่าเริ่มต้น (ทำให้ accuracy สูง)
  • ใช้ float เมื่อต้องประหยัด memory (หลัก)

3. Character Type: เก็บตัวอักษร

ชนิดขนาดเก็บตัวอย่าง
char2 bytes (16 bits)1 ตัวอักษร Unicodechar initial = 'J';

ตัวอย่าง:

javapublic class CharacterDemo {
    public static void main(String[] args) {
        char initial = 'J';
        char grade = 'A';
        char symbol = '@';
        char thaiChar = 'ก';
        
        System.out.println("Initial: " + initial);
        System.out.println("Grade: " + grade);
        System.out.println("Symbol: " + symbol);
        System.out.println("Thai Character: " + thaiChar);
        
        // char เป็นจำนวนเต็มที่อ้างอิงถึง Unicode
        System.out.println("ASCII code of 'A': " + (int)grade);  // 65
    }
}

Output:

textInitial: J
Grade: A
Symbol: @
Thai Character: ก
ASCII code of 'A': 65

ข้อสำคัญ:

  • ใช้ single quotes 'A' ไม่ใช่ double quotes
  • char เก็บ Unicode ได้ เช่น อักษรไทย, อักษรจีน

4. Boolean Type: เก็บค่าจริง-เท็จ

ชนิดขนาดค่าที่ได้ตัวอย่าง
boolean1 bittrue หรือ falseboolean isActive = true;

ตัวอย่าง:

javapublic class BooleanDemo {
    public static void main(String[] args) {
        boolean isActive = true;
        boolean isValid = false;
        boolean hasEmail = true;
        
        System.out.println("Is Active: " + isActive);
        System.out.println("Is Valid: " + isValid);
        System.out.println("Has Email: " + hasEmail);
        
        // ใช้ใน condition (ต่อไปจะเรียน if)
        if (isActive) {
            System.out.println("User is active in system");
        }
    }
}

Output:

textIs Active: true
Is Valid: false
Has Email: true
User is active in system

Reference Data Types: สั้นๆ

Reference Data Types คือชนิดข้อมูลที่อ้างอิงถึง objects (จะเรียนรายละเอียดต่อไป)

ตัวอย่าง:

javaString name = "John";           // String object
ArrayList<Integer> numbers;     // List object
Student student;                // Custom class object

Operator: สัญลักษณ์การทำงาน

Operator คืออะไร?

Operator คือ สัญลักษณ์ ที่ใช้ ทำการกับข้อมูล เช่น บวก ลบ คูณ หาร เปรียบเทียบ


1. Arithmetic Operators: คณิตศาสตร์

Operatorความหมายตัวอย่างผลลัพธ์
+บวก10 + 515
-ลบ10 – 55
*คูณ10 * 550
/หาร10 / 52
%mod (เศษ)10 % 31

ตัวอย่าง:

javapublic class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;
        
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println();
        
        System.out.println("Addition: " + (a + b));      // 13
        System.out.println("Subtraction: " + (a - b));   // 7
        System.out.println("Multiplication: " + (a * b)); // 30
        System.out.println("Division: " + (a / b));      // 3
        System.out.println("Modulo: " + (a % b));        // 1
    }
}

Output:

texta = 10
b = 3

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulo: 1

การคำนวณทศนิยม:

javadouble x = 10.0;
double y = 3.0;

System.out.println("Division: " + (x / y));  // 3.3333...
System.out.println("Modulo: " + (x % y));   // 1.0

2. Assignment Operators: กำหนดค่า

Operatorความหมายตัวอย่างเท่ากับ
=กำหนดค่าx = 5x = 5
+=บวกแล้วกำหนดx += 3x = x + 3
-=ลบแล้วกำหนดx -= 3x = x – 3
*=คูณแล้วกำหนดx *= 3x = x * 3
/=หารแล้วกำหนดx /= 3x = x / 3
%=mod แล้วกำหนดx %= 3x = x % 3

ตัวอย่าง:

javapublic class AssignmentDemo {
    public static void main(String[] args) {
        int x = 10;
        
        System.out.println("Initial x: " + x);  // 10
        
        x += 5;
        System.out.println("After x += 5: " + x);  // 15
        
        x -= 3;
        System.out.println("After x -= 3: " + x);  // 12
        
        x *= 2;
        System.out.println("After x *= 2: " + x);  // 24
        
        x /= 4;
        System.out.println("After x /= 4: " + x);  // 6
    }
}

Output:

textInitial x: 10
After x += 5: 15
After x -= 3: 12
After x *= 2: 24
After x /= 4: 6

3. Comparison Operators: เปรียบเทียบ

Operatorความหมายตัวอย่างผลลัพธ์
==เท่ากับ5 == 5true
!=ไม่เท่ากับ5 != 3true
>มากกว่า5 > 3true
<น้อยกว่า5 < 3false
>=มากกว่าหรือเท่ากับ5 >= 5true
<=น้อยกว่าหรือเท่ากับ5 <= 3false

ตัวอย่าง:

javapublic class ComparisonDemo {
    public static void main(String[] args) {
        int a = 5;
        int b = 3;
        
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println();
        
        System.out.println("a == b: " + (a == b));  // false
        System.out.println("a != b: " + (a != b));  // true
        System.out.println("a > b: " + (a > b));    // true
        System.out.println("a < b: " + (a < b));    // false
        System.out.println("a >= b: " + (a >= b));  // true
        System.out.println("a <= b: " + (a <= b));  // false
    }
}

Output:

texta = 5
b = 3

a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false

4. Logical Operators: ตรรกะ

Operatorความหมายตัวอย่างผลลัพธ์
&&AND (และ)true && falsefalse
||OR (หรือ)true || falsetrue
!NOT (ไม่)!truefalse

ตัวอย่าง:

javapublic class LogicalDemo {
    public static void main(String[] args) {
        int age = 25;
        double salary = 30000;
        
        // AND (&&) - ต้องเป็นจริงทั้งคู่
        boolean canApply = (age >= 18) && (salary >= 20000);
        System.out.println("Can apply for loan: " + canApply);  // true
        
        // OR (||) - ต้องเป็นจริงอย่างน้อยตัวเดียว
        boolean hasRequirement = (age < 18) || (salary >= 25000);
        System.out.println("Has requirement: " + hasRequirement);  // true
        
        // NOT (!) - กลับค่าจริง-เท็จ
        boolean isNotEligible = !(age >= 18);
        System.out.println("Is not eligible: " + isNotEligible);  // false
    }
}

Output:

textCan apply for loan: true
Has requirement: true
Is not eligible: false

Truth Table:

ABA && BA || B!A
TTTTF
TFFTF
FTFTT
FFFFT

5. Increment/Decrement Operators: เพิ่มลด

Operatorความหมายตัวอย่างเท่ากับ
++เพิ่มขึ้น 1x++ หรือ ++xx = x + 1
--ลดลง 1x– หรือ –xx = x – 1

ตัวอย่าง:

javapublic class IncrementDemo {
    public static void main(String[] args) {
        int x = 5;
        
        System.out.println("Initial x: " + x);  // 5
        
        x++;
        System.out.println("After x++: " + x);  // 6
        
        ++x;
        System.out.println("After ++x: " + x);  // 7
        
        x--;
        System.out.println("After x--: " + x);  // 6
        
        --x;
        System.out.println("After --x: " + x);  // 5
    }
}

Output:

textInitial x: 5
After x++: 6
After ++x: 7
After x--: 6
After --x: 5

ความแตกต่าง Pre-increment vs Post-increment:

javaint a = 5;
int b = a++;    // b = 5, a = 6 (post-increment)

int c = 5;
int d = ++c;    // d = 6, c = 6 (pre-increment)

6. Ternary Operator: เงื่อนไข 3 ส่วน

OperatorSyntaxตัวอย่าง
?:condition ? valueIfTrue : valueIfFalseage >= 18 ? “Adult” : “Minor”

ตัวอย่าง:

javapublic class TernaryDemo {
    public static void main(String[] args) {
        int age = 25;
        String status = (age >= 18) ? "Adult" : "Minor";
        System.out.println("Status: " + status);  // Adult
        
        double score = 75;
        String grade = (score >= 80) ? "A" : 
                      (score >= 70) ? "B" : 
                      (score >= 60) ? "C" : "F";
        System.out.println("Grade: " + grade);  // B
    }
}

Output:

textStatus: Adult
Grade: B

Input/Output: รับและแสดงข้อมูล

Output: แสดงข้อมูล

1. System.out.print()

เขียนข้อมูล โดยไม่ขึ้นบรรทัดใหม่

javaSystem.out.print("Hello");
System.out.print(" World");
// Output: Hello World

2. System.out.println()

**เขียนข้อมูล แล้ว ขึ้นบรรทัดใหม่

javaSystem.out.println("Hello");
System.out.println("World");
// Output:
// Hello
// World

3. System.out.printf()

**เขียนข้อมูล พร้อม format ที่กำหนด

javaint age = 25;
String name = "John";
double gpa = 3.75;

// Format specifiers:
// %d = integer
// %s = string
// %f = floating point
// %.2f = floating point with 2 decimals

System.out.printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
// Output: Name: John, Age: 25, GPA: 3.75

ตัวอย่างการแสดงผลทั้งหมด

javapublic class OutputDemo {
    public static void main(String[] args) {
        // print() - ไม่ขึ้นบรรทัดใหม่
        System.out.print("This ");
        System.out.print("is ");
        System.out.print("one line");
        System.out.println();  // ขึ้นบรรทัดใหม่
        
        // println() - ขึ้นบรรทัดใหม่อัตโนมัติ
        System.out.println("Line 1");
        System.out.println("Line 2");
        System.out.println("Line 3");
        
        // printf() - format output
        int score = 95;
        double percentage = 95.5;
        System.out.printf("Score: %d, Percentage: %.1f%%\n", score, percentage);
        
        // String concatenation
        String greeting = "Hello, " + "World!";
        System.out.println(greeting);
    }
}

Output:

textThis is one line
Line 1
Line 2
Line 3
Score: 95, Percentage: 95.5%
Hello, World!

Input: รับข้อมูล

Scanner: อ่านข้อมูลจาก User

Import:

javaimport java.util.Scanner;

สร้าง Scanner:

javaScanner input = new Scanner(System.in);

Method สำหรับอ่านข้อมูล:

Methodประเภทตัวอย่าง
nextInt()อ่านจำนวนเต็มint age = input.nextInt();
nextDouble()อ่านทศนิยมdouble salary = input.nextDouble();
nextLine()อ่าน String (บรรทัดทั้งหมด)String name = input.nextLine();
next()อ่าน String (จนถึงช่องว่าง)String word = input.next();
nextBoolean()อ่าน booleanboolean isActive = input.nextBoolean();

ตัวอย่าง: โปรแกรมรับข้อมูลและแสดงผล

javaimport java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        // รับชื่อ
        System.out.print("Enter your name: ");
        String name = input.nextLine();
        
        // รับอายุ
        System.out.print("Enter your age: ");
        int age = input.nextInt();
        
        // รับ GPA
        System.out.print("Enter your GPA: ");
        double gpa = input.nextDouble();
        
        // แสดงผล
        System.out.println("\n=== Student Information ===");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
        
        // ปิด Scanner
        input.close();
    }
}

Output (ถ้า user กรอก: John, 25, 3.75):

textEnter your name: John
Enter your age: 25
Enter your GPA: 3.75

=== Student Information ===
Name: John
Age: 25
GPA: 3.75

ตัวอย่าง: โปรแกรมคำนวณเกรด

javaimport java.util.Scanner;

public class GradeCalculator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        // รับคะแนน
        System.out.print("Enter your score: ");
        int score = input.nextInt();
        
        // คำนวณเกรด
        String grade;
        if (score >= 80) {
            grade = "A";
        } else if (score >= 70) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else {
            grade = "F";
        }
        
        // แสดงผล
        System.out.printf("Your score: %d\n", score);
        System.out.printf("Your grade: %s\n", grade);
        
        input.close();
    }
}

Output (ถ้า user กรอก 85):

textEnter your score: 85
Your score: 85
Your grade: A

Escape Sequences: ตัวเลขพิเศษ

Escape Sequenceความหมายตัวอย่าง
\nขึ้นบรรทัดใหม่"Hello\nWorld"
\tแท็บ (ย่อระยะ)"Hello\tWorld"
\"Double quote"He said \"Hi\""
\'Single quote'\' (หรือ "'")
\\Backslash"C:\\Users\\File"

ตัวอย่าง:

javapublic class EscapeSequenceDemo {
    public static void main(String[] args) {
        System.out.println("Line 1\nLine 2");  // ขึ้นบรรทัดใหม่
        System.out.println("Name\tAge");       // แท็บ
        System.out.println("He said \"Hello\"");  // Double quote
        System.out.println("Path: C:\\Users\\John");  // Backslash
    }
}

Output:

textLine 1
Line 2
Name	Age
He said "Hello"
Path: C:\Users\John

สรุป: Syntax, Variables, Data Types, Operators, I/O

หัวข้อคำอธิบายตัวอย่าง
Variableกล่องเก็บข้อมูลint age = 25;
Data Typeประเภทของข้อมูลint, double, String, boolean
Operatorสัญลักษณ์การทำงาน+, -, *, /, %, &&, ||, >
Inputรับข้อมูลจาก userScanner input.nextInt()
Outputแสดงข้อมูลที่ screenSystem.out.println()

ตัวอย่างการใช้ทั้งหมดรวมกัน

javaimport java.util.Scanner;

public class StudentInfoSystem {
    public static void main(String[] args) {
        // สร้าง Scanner
        Scanner input = new Scanner(System.in);
        
        // รับข้อมูล
        System.out.println("=== Student Information System ===\n");
        
        System.out.print("Enter student ID: ");
        String studentId = input.nextLine();
        
        System.out.print("Enter full name: ");
        String name = input.nextLine();
        
        System.out.print("Enter age: ");
        int age = input.nextInt();
        
        System.out.print("Enter GPA: ");
        double gpa = input.nextDouble();
        
        System.out.print("Is student active? (true/false): ");
        boolean isActive = input.nextBoolean();
        
        // คำนวณ
        String status = isActive ? "Active" : "Inactive";
        String gradeLevel = (gpa >= 3.5) ? "Excellent" : 
                           (gpa >= 3.0) ? "Very Good" : 
                           (gpa >= 2.5) ? "Good" : "Fair";
        
        // แสดงผล
        System.out.println("\n=== Student Profile ===");
        System.out.printf("ID: %s\n", studentId);
        System.out.printf("Name: %s\n", name);
        System.out.printf("Age: %d years old\n", age);
        System.out.printf("GPA: %.2f\n", gpa);
        System.out.printf("Status: %s\n", status);
        System.out.printf("Grade Level: %s\n", gradeLevel);
        
        // ปิด Scanner
        input.close();
    }
}

Output (ตัวอย่าง):

text=== Student Information System ===

Enter student ID: 6501001
Enter full name: John Doe
Enter age: 20
Enter GPA: 3.85
Is student active? (true/false): true

=== Student Profile ===
ID: 6501001
Name: John Doe
Age: 20 years old
GPA: 3.85
Status: Active
Grade Level: Excellent