Java字符串转字节程序
假设你有一个名为"str"的字符串。现在,你的任务是编写一个Java程序将给定的字符串转换为字节。
字符串是Java中一个类,它在双引号内存储字符序列,而字节是包装类,属于java.lang包,它包装了字节数据类型的数值。
示例场景
Input: String str = "65"; Output: res = 65
使用Byte.valueOf()方法
Java Byte类的valueOf()方法用于将给定的字符串转换为其对应的Byte对象。它接受单个数字字符串作为参数值,并将其作为Byte对象返回。
示例
下面的Java程序演示了如何将给定的字符串转换为字节。
public class Demo {
public static void main(String[] args) {
String str = "65";
System.out.println("Given String is: " + str);
// checking type before converting
System.out.println("Type before converting: " + ((Object)str).getClass().getSimpleName());
// converting to byte using Byte.valueOf()
byte res = Byte.valueOf(str);
System.out.println("String after converting to Byte: " + res);
// checking type after converting
System.out.println("Type after converting: " + ((Object)res).getClass().getSimpleName());
}
}
运行此代码将生成以下结果:
Given String is: 65 Type before converting: String String after converting to Byte: 65 Type after converting: Byte
使用Byte.parseByte()方法
Java Byte类的parseByte()方法将指定的字符串参数解析为带符号的十进制字节。
示例
在这个Java程序中,我们传递一个带符号的数字字符串,并使用parseByte()方法将其转换为字节。
public class Demo {
public static void main(String[] args) {
String str = "-127";
System.out.println("Given String is: " + str);
// checking type before converting
System.out.println("Type before converting: " + ((Object)str).getClass().getSimpleName());
// converting to byte using Byte.parseByte()
byte res = Byte.parseByte(str);
System.out.println("String after converting to Byte: " + res);
// checking type after converting
System.out.println("Type after converting: " + ((Object)res).getClass().getSimpleName());
}
}
上述代码的输出为:
Given String is: -127 Type before converting: String String after converting to Byte: -127 Type after converting: Byte
处理字符串转字节时的错误
Byte.parseByte()和Byte.valueOf()方法都期望一个字符串,该字符串表示字节数据类型范围内的值,即-128到127之间的数字。因此,你需要传递其范围内的数字字符串,否则可能会遇到NumberFormatException异常。
示例
现在,让我们看看实际演示:
public class Demo {
public static void main(String[] args) {
// string value is greater than Byte range
String str = "130";
System.out.println("Given String is: " + str);
// converting to byte
byte res = Byte.valueOf(str);
System.out.println("String after converting toByte: " + res);
}
}
执行此代码时,将显示以下错误消息:
Given String is: 130 Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"130" Radix:10 at java.base/java.lang.Byte.parseByte(Byte.java:195) at java.base/java.lang.Byte.valueOf(Byte.java:249) at java.base/java.lang.Byte.valueOf(Byte.java:275) at Demo.main(Demo.java:7)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP