Java - Long decode() 方法



描述

Java Long decode() 方法将字符串解码为 Long。它接受十进制、十六进制和八进制数字。

声明

以下是 java.lang.Long.decode() 方法的声明

public static Long decode(String nm) throws NumberFormatException

参数

nm - 这是要解码的字符串。

返回值

此方法返回一个 Long 对象,该对象保存由 nm 表示的 long 值。

异常

NumberFormatException - 如果字符串不包含可解析的整数。

从包含十进制数字的字符串获取 Long 示例

以下示例演示了如何使用 Long decode() 方法从包含十进制数字的字符串获取 Long 对象。我们创建了一个 String 变量并为其分配一个包含十进制数字的字符串。然后使用 decode 方法,我们获取 Long 对象并打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
    
      String str = "50";
      /* returns an Long object holding the long value represented
         by string str */
      System.out.println("Number = " + Long.decode(str)); 
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Number = 50

从包含负十进制数字的字符串获取 Long 示例

以下示例演示了如何使用 Long decode() 方法从包含负十进制数字的字符串获取 Long 对象。我们创建了一个 String 变量并为其分配一个包含负十进制数字的字符串。然后使用 decode 方法,我们获取 Long 对象并打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
    
      String str = "-50";
      /* returns an Long object holding the long value represented
         by string str */
      System.out.println("Number = " + Long.decode(str)); 
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Number = -50

从包含八进制数字的字符串获取 Long 示例

以下示例演示了如何使用 Long decode() 方法从包含八进制数字的字符串获取 Long 对象。我们创建了一个 String 变量并为其分配一个包含八进制数字的字符串。然后使用 decode 方法,我们获取 Long 对象并打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {   
      String str = "0x3";
      /* returns an Long object holding the long value represented
         by string str */
      System.out.println("Number = " + Long.decode(str)); 
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Number = 3

从包含十六进制数字的字符串获取 Long 示例

以下示例演示了如何使用 Long decode() 方法从包含十六进制数字的字符串获取 Long 对象。我们创建了一个 String 变量并为其分配一个包含十六进制数字的字符串。然后使用 decode 方法,我们获取 Long 对象并打印它。

package com.tutorialspoint;
public class LongDemo {
   public static void main(String[] args) {
    
      String str = "0xff";
      /* returns an Long object holding the long value represented
         by string str */
      System.out.println("Number = " + Long.decode(str)); 
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Number = 255
java_lang_long.htm
广告

© . All rights reserved.