看了一些文章包括官方文档说法,都是说java的char类型是双字节长的,可是下边的测试结果怎么解释?我的JVM编译环境是UTF-8.
https://www.cnblogs.com/softidea/p/10271219.html
package generic.primitivetype;
import org.junit.Test;
/**
* @Author: Tom
* @Date: 2021年1月7日 下午4:17:23
* @Version: 1.0
* @Description:
*/
public class CharOfChineseTest {
/**
*
* @Description: Test the actual byte size used by char type
* @param
* @return
* @throws
*/
@Test
public void test01() {
String test2 = "hello";
char[] charArray2 = test2.toCharArray();
byte[] bytes2 = test2.getBytes();
System.out.println(test2.length());
System.out.println(charArray2.length);
System.out.println(bytes2.length);
//output:
//5
//5
//5
}
@Test
public void test02() {
String test = "今天天气很好";
char[] charArray = test.toCharArray();
byte[] bytes = test.getBytes();
System.out.println(test.length());
System.out.println(charArray.length);
System.out.println(bytes.length);
//output:
//6
//6
//18
}
@Test
public void test03() {
char[] test = {'今','天','天','气','很','好'};
System.out.println(test.length);
String string = new String(test);
byte[] bytes = string.getBytes();
System.out.println(string.length());
System.out.println(bytes.length);
//output:
//UTF-8
//6
//6
//18
}
}