Char in Java takes up several bytes

Source: Internet
Author: User

1: "Byte" is byte, "bit" is bit;

2:1 byte = 8 bit;

Char is 2 bytes in Java. Java uses a unicode,2 byte (16-bit) to represent one character.

The example code is as follows:

public class Test {public


	static void Main (string[] args) {
		String str= ' Medium ';
		char x = ' Medium ';
		Byte[] Bytes=null;
		Byte[] Bytes1=null;
		try {
			bytes = str.getbytes ("Utf-8");
			Bytes1 = Chartobyte (x);
		} catch (Unsupportedencodingexception e) {
			//TODO auto-generated catch block
			e.printstacktrace ();
		}
		System.out.println ("bytes Size:" +bytes.length);
		System.out.println ("Bytes1 size:" +bytes1.length);
	}
	public static byte[] Chartobyte (char c) { 
        byte[] b = new byte[2]; 
        B[0] = (byte) (C & 0xff00) >> 8); 
        B[1] = (byte) (C & 0xFF); 
        return b; 
    }
}

Run Result:

Bytes Size: 3
Bytes1 Size: 2

  

Java is used to represent characters in Unicode, and Unicode for the Chinese character "medium" is 2 bytes.

The String.getbytes (encoding) method is to get a byte array representation of the specified encoding,

Typically, the gbk/gb2312 is 2 bytes, and the Utf-8 is 3 bytes .

If encoding is not specified, the system default encoding is taken.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.