Java Double byteValue()方法及示例

来源:这里教程网 时间:2026-02-17 20:52:49 作者:

Java Double byteValue()方法及示例

java.lang.Double.byteValue() 是Java中的一个内置方法,它将Double的值作为一个字节返回(通过转换为一个字节)。基本上它用于缩小Double类型到字节值的原始转换。

语法

public byte byteValue()

参数: 该函数不接受任何参数。

返回值: 该方法返回由该对象转换为字节类型的双倍值。

举例说明

Input : 12Output : 12Input : 1023Output : -1

以下程序说明了java.lang.Double.byteValue()函数的使用。

程序1 :

// Program to illustrate the Double.byteValue() methodimport java.lang.*;  public class GFG {      public static void main(String[] args)    {          Double value = 1023d;          // Returns the value of Double as a byte        byte byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);          // Another example        value = 12d;        byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);    }}

输出。

Byte Value of num = -1Byte Value of num = 12

程序2: 演示一个负数的字节值。

// Java code to illustrate java.lang.Double.byteValue() methodimport java.lang.*;  public class GFG {      public static void main(String[] args)    {          Double value = -1023d;          // Returns the value of Double as a byte        byte byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);          // Another example        value = -12d;        byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);    }}

输出。

Byte Value of num = 1Byte Value of num = -12

程序3: 当参数中传递了一个十进制值时。

// Program to illustrate java.lang.Double.byteValue() method  import java.lang.*;  public class GFG {      public static void main(String[] args)    {          Double value = 11.24;          // Returns the value of Double as a byte        byte byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);          // Another example        value = 6.0;        byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);    }}

输出。

Byte Value of num = 11Byte Value of num = 6

程序4: 当一个字符串值被作为参数传递时。

// Code to illustrate Double.byteValue()import java.lang.*;  public class GFG {      public static void main(String[] args)    {          Double value = "45";          // Returns the value of Double as a byte        byte byteValue = value.byteValue();        System.out.println("Byte Value of num = " + byteValue);    }}

编译错误

prog.java:9: error: incompatible types: String cannot be converted to Double        Double value = "45";                       ^1 error

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#byteValue-

相关推荐