Get the App
SLTechnology News&Howtos  ›  Development  › 

How many bytes are occupied by char [] and String types in Java

Shulou Source: shulou.com Published: 2022-06-03 18:51:15 10月02日 Update

This article introduces the relevant knowledge of "how many bytes are occupied by char [] and String types in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In C language

1. How many bytes does this a take in char a [10] = {"China"}?

Answer: it takes up 10 bytes.

Parsing: the above code assigns a value to a

A [0] ='C', a [1] ='h', a [2] ='i', a [3] ='n', a [4] ='a', a [5] ='\ 0century] a [6] =''\ 0century force a [7] ='\ 0century law a [8] ='\ 0century month a [9] ='\ 0'

So, it takes up 10 bytes.

2. If you only refer to "China"?

A: a total of 6 bytes. China occupies 5 bytes and ends with'\ 0', accounting for 1 byte.

In the Java language

1. String s = "China"; how many bytes?

Answer: it takes up 5 bytes.

System.out.println (Charset.defaultCharset ()); / / get ide default encoding type String s = new String ("China" .getBytes ()); byte [] b = s.getBytes (); System.out.println ("" + b.length)

With the above code, you can output "China" with a byte length of 5.

2. String s = "China"; how many bytes?

A: in the case of Chinese characters, you need to consider coding.

(1) when GBK coding (ide default), each Chinese character occupies 2 bytes, then China occupies 4 bytes.

(2) when UTF-8 coding, each Chinese character occupies 3 bytes, then China occupies 6 bytes.

3. Transcoding problem: will the byte footprint become larger when GBK is converted to UTF-8? And the other way around?

/ / get UTF-8 code System.out.println (Charset.defaultCharset ()); String sporttry {s = new String ("China" .getBytes (), "GBK"); byte [] b = s.getBytes (); System.out.println ("" + b.length);} catch (UnsupportedEncodingException e) {e.printStackTrace ();}

As the above code is: UTF-8 to GBK encoding format, s length from 6 bytes to 9 bytes.

S content change: China-> trickle 

Because the current encoding is UTF-8, it becomes 3 words after transcoding, occupying 9 bytes. However, the opposite goes like this:

China (gbk)? (utf-8)

The length of s has changed from 4 bytes to 4 bytes, although the length has not changed, but the text has changed. Here? Occupies 1 byte.

That's all for "how many bytes are occupied by char [] and String types in Java". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Bytes coding China UTF-8 length type code content situation Chinese characters in turn text more knowledge language output practical successful learning next dilemma Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MariaDB MySQL Apple Microsoft