บทนำ: ก่อนเขียนโปรแกรมจริง
เมื่อเริ่มเขียนโปรแกรม Java ต้องเข้าใจ ภาษาของ Java คือ ไวยากรณ์ (Syntax) ที่ Java ใช้ เพื่อสื่อสารกับคอมพิวเตอร์ได้ถูกต้อง
ส่วนนี้จะเรียนรู้พื้นฐาน:
- ตัวแปร (Variables) – ที่เก็บข้อมูล
- ชนิดข้อมูล (Data Types) – ประเภทของข้อมูล
- Operator – สัญลักษณ์ทำการต่างๆ
- Input/Output – รับข้อมูลและแสดงผล
- บทนำ: ก่อนเขียนโปรแกรมจริง
- ตัวแปร (Variables): กล่องเก็บข้อมูล
- ตัวแปรคืออะไร?
- การประกาศตัวแปร (Variable Declaration)
- การกำหนดค่าให้ตัวแปร (Assignment)
- การประกาศและกำหนดค่าพร้อมกัน (Initialization)
- Naming Convention: ตั้งชื่อตัวแปรให้ถูกต้อง
- ชนิดข้อมูล (Data Types)
- ชนิดข้อมูล: การจำแนกข้อมูล
- Primitive Data Types: ชนิดพื้นฐาน
- 1. Integer Types: เก็บจำนวนเต็ม
- 2. Floating-Point Types: เก็บจำนวนทศนิยม
- 3. Character Type: เก็บตัวอักษร
- 4. Boolean Type: เก็บค่าจริง-เท็จ
- Reference Data Types: สั้นๆ
- Operator: สัญลักษณ์การทำงาน
- Operator คืออะไร?
- 1. Arithmetic Operators: คณิตศาสตร์
- 2. Assignment Operators: กำหนดค่า
- 3. Comparison Operators: เปรียบเทียบ
- 4. Logical Operators: ตรรกะ
- 5. Increment/Decrement Operators: เพิ่มลด
- 6. Ternary Operator: เงื่อนไข 3 ส่วน
- Input/Output: รับและแสดงข้อมูล
- Output: แสดงข้อมูล
- 1. System.out.print()
- 2. System.out.println()
- 3. System.out.printf()
- ตัวอย่างการแสดงผลทั้งหมด
- Input: รับข้อมูล
- Scanner: อ่านข้อมูลจาก User
- ตัวอย่าง: โปรแกรมรับข้อมูลและแสดงผล
- ตัวอย่าง: โปรแกรมคำนวณเกรด
- Escape Sequences: ตัวเลขพิเศษ
- สรุป: Syntax, Variables, Data Types, Operators, I/O
- ตัวอย่างการใช้ทั้งหมดรวมกัน
ตัวแปร (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 กลุ่ม ชนิดข้อมูล:
- Primitive Data Types – ชนิดข้อมูลพื้นฐาน
- Reference Data Types – ชนิดข้อมูลอ้างอิง (ต่อไปจะเรียน)
Primitive Data Types: ชนิดพื้นฐาน
1. Integer Types: เก็บจำนวนเต็ม
| ชนิด | ขนาด | ช่วง | ตัวอย่าง |
|---|---|---|---|
byte | 1 byte (8 bits) | -128 ถึง 127 | byte age = 25; |
short | 2 bytes (16 bits) | -32,768 ถึง 32,767 | short year = 2025; |
int | 4 bytes (32 bits) | -2,147,483,648 ถึง 2,147,483,647 | int population = 70000000; |
long | 8 bytes (64 bits) | ±9.22 × 10^18 | long 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: เก็บจำนวนทศนิยม
| ชนิด | ขนาด | ช่วง | ตัวอย่าง |
|---|---|---|---|
float | 4 bytes (32 bits) | ±3.40 × 10^38 | float price = 99.99f; |
double | 8 bytes (64 bits) | ±1.80 × 10^308 | double 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: เก็บตัวอักษร
| ชนิด | ขนาด | เก็บ | ตัวอย่าง |
|---|---|---|---|
char | 2 bytes (16 bits) | 1 ตัวอักษร Unicode | char 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: เก็บค่าจริง-เท็จ
| ชนิด | ขนาด | ค่าที่ได้ | ตัวอย่าง |
|---|---|---|---|
boolean | 1 bit | true หรือ false | boolean 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 + 5 | 15 |
- | ลบ | 10 – 5 | 5 |
* | คูณ | 10 * 5 | 50 |
/ | หาร | 10 / 5 | 2 |
% | mod (เศษ) | 10 % 3 | 1 |
ตัวอย่าง:
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 = 5 | x = 5 |
+= | บวกแล้วกำหนด | x += 3 | x = x + 3 |
-= | ลบแล้วกำหนด | x -= 3 | x = x – 3 |
*= | คูณแล้วกำหนด | x *= 3 | x = x * 3 |
/= | หารแล้วกำหนด | x /= 3 | x = x / 3 |
%= | mod แล้วกำหนด | x %= 3 | x = 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 == 5 | true |
!= | ไม่เท่ากับ | 5 != 3 | true |
> | มากกว่า | 5 > 3 | true |
< | น้อยกว่า | 5 < 3 | false |
>= | มากกว่าหรือเท่ากับ | 5 >= 5 | true |
<= | น้อยกว่าหรือเท่ากับ | 5 <= 3 | false |
ตัวอย่าง:
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 && false | false |
|| | OR (หรือ) | true || false | true |
! | NOT (ไม่) | !true | false |
ตัวอย่าง:
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:
| A | B | A && B | A || B | !A |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
5. Increment/Decrement Operators: เพิ่มลด
| Operator | ความหมาย | ตัวอย่าง | เท่ากับ |
|---|---|---|---|
++ | เพิ่มขึ้น 1 | x++ หรือ ++x | x = x + 1 |
-- | ลดลง 1 | x– หรือ –x | x = 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 ส่วน
| Operator | Syntax | ตัวอย่าง |
|---|---|---|
?: | condition ? valueIfTrue : valueIfFalse | age >= 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() | อ่าน boolean | boolean 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 | รับข้อมูลจาก user | Scanner input.nextInt() |
| Output | แสดงข้อมูลที่ screen | System.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
