Byte ใน Java
บทความนี้เรามาทำความรู้จักกับ Byte ในภาษา Java กันครับ ว่าคืออะไร และใช้ยังไง
Byte เป็นตัวเลขในภาษา Java ที่เก็บและมีขนาดน้อยที่สุด มีเพียง 8 bit ซึ่งมีค่าอยู่ระหว่าง -128 ถึง 127
ตัวอย่างการใช้ Byte ในภาษา Java แบบง่าย ๆ ตามโค้ดด้านล่าง
package info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
byte b1 = 100;
byte b2 = 20;
System.out.println("b1 is : " + b1);
System.out.println("b1 is : " + b2);
}
}
Convert byte to String
มาดูตัวอย่างการแปลง byte เป็น String กันดูบ้าง ซึ่งก็มีหลาย ๆ วิธีด้วยกัน ดังตัวอย่างpackage info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
byte b = 65;
// Using the static toString method of the Byte class
String sol1 = Byte.toString(b);
// Using simple concatenation with an empty String
String sol2 = b + "";
// Creating a byte array and passing it to the String constructor
String sol3 = new String(new byte[] {b});
}
}
convert byte primitive type to Byte object
ต่อไปลองมาดูการแปลงค่าจาก byte primitive type ไปเป็น Byte Object ตามตัวอย่างโค้ดpackage info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
byte i = 10;
Byte bObj = new Byte(i);
}
}
การ Convert Byte ไปเป็น Primitive ที่เป็นชนิดตัวเลข
Byte จัดอยู่ในกลุ่มตัวเลข ดังนั้นเราสามารถแปลง Byte ไปเป็น Primitive Type ที่เป็นตัวเลขได้ ตามตัวอย่างโค้ดpackage info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
Byte bObj = new Byte("10");
// convert to byte
byte b = bObj.byteValue();
System.out.println(b);
// convert to short
short s = bObj.shortValue();
System.out.println(s);
// convert to int
int i = bObj.intValue();
System.out.println(i);
// convert to float
float f = bObj.floatValue();
System.out.println(f);
// convert to double
double d = bObj.doubleValue();
System.out.println(d);
// convert to long
long l = bObj.longValue();
System.out.println(l);
}
}
ตัวอย่าง Output ที่ได้
10
10
10
10.0
10.0
10
ไม่มีความคิดเห็น:
แสดงความคิดเห็น