1. 976-140 Object-Oriented Programming
344-202 Introduction to Object-Oriented Programming
การโปรแกรมเชิงวัตถุ
2. Java Fundamentals
Faculty of Technology and Environment
Prince of Songkla University, Phuket Campus
2/2551
2. Contents
keywords, reserved words
Identifiers and variables
Primitive data types
Literals
Type conversion
Constants
Object-Oriented Programming 2/2551 2
29. Implicit type conversion
Implicit type conversion เป็นการแปลงชนิดข้อมูลที่จาวาทาให้อัตโนมัติ
การแปลงข้อมูลจะแปลงจากชนิดข้อมูลที่มีความสาคัญต่ากว่าเป็น
ความสาคัญสูงกว่า เพื่อไม่ให้สูญเสียค่าทีแท้จริงของข้อมูล
่
เช่น int a = 5; short b=10;
a+b-7 จะได้ผลลัพธ์ที่เป็น int คือ 8
• b ถูกแปลงเป็น int, 7 เป็น literal มองเป็น int
ถ้า float a = 5f; int b = 10;
หาค่าและชนิดข้อมูลของผลลัพธ์จาก a+b-7
Object-Oriented Programming 2/2551 29
30. Explicit type conversion หรือ Type Casting
Casting การแปลงข้อมูลที่โปรแกรมเมอร์ต้องระบุชนิดข้อมูลที่ต้องการเอง
Type casting syntax ระบุชนิดข้อมูลที่ตองการแปลงในวงเล็บ
้
(<data type>) <expression>;
ตัวอย่าง
short x = (short) 88778; //23242
y = (float) x / 3;
k = a + (double) (x + y * z)
Object-Oriented Programming 2/2551 30
31. Ex. Integral type demo. What the output is?
Object-Oriented Programming 2/2551 31
32. Constant หรือ ค่าคงที่
ค่าคงที่ คือตัวแปรที่เมื่อทาการกาหนดค่าแล้วจะมีค่าเป็นค่านั้นไปตลอด
การทางานของโปรแกรม โดยไม่สามารถเปลี่ยนแปลงได้อีก
การประกาศค่าคงที่ ให้ระบุคาว่า final ไว้หน้าชนิดข้อมูล
final <data type> <constant_name> = <value>;
เช่น
final double PI = 3.1416;
ปกตินิยมตั้งชื่อค่าคงที่ด้วยตัวอักษรตัวใหญ่ทั้งหมด
Object-Oriented Programming 2/2551 32
33. Constant หรือ ค่าคงที่
ตัวอย่างการประกาศค่าคงที่
Result
area = 78.54
Object-Oriented Programming 2/2551 33