Question:
How many bytes in memory a string occupy in Java language?
T K
2009-01-09 10:09:29 UTC
I am reposting this question.
How many bytes in memory a string occupy in Java language?
Suppose i write:
String name="Bill Gates";
So, how much memory it requires? Whether it can store a UNICODE character in the string. How internally it is implemented, using a 1 byte char array or 2 byte unicode char array? I read somewhere that Java's char data type is 16 bit wide.

Thanks!!!
Three answers:
Neeraj Yadav♄
2009-01-09 11:22:41 UTC
In java every char takes 16 bits representation i.e. 2 bytes in order to sustain unicode for internationalization.







Although in other lang,

Here is an example of a null-terminated string stored in a 10-byte buffer, along with its ASCII representation:

F R A N K NUL k e f w

46 52 41 4E 4B 00 6B 66 66 77



A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool.Afetr using the string object returns to the pool in the pool there is no rool of gc.and object in the string pool is immutable.



Use intern() in order to avoid tht



hope this helps

Cheers:)
anonymous
2009-01-09 10:23:40 UTC
You are correct. Java uses 2 byte unicode. There are plans to transition to 4 byte one day.
TBRMInsanity
2009-01-09 10:16:02 UTC
It depends on your computer actually. A string can be almost any length, but it is best to keep it under 256 characters. Each character in a string takes up 2 bytes (will have a value from 00 to FF). The CHAR data type technically doesn't use the first bit of its 2 byte code and as such only 14 bits of the 16 bits allocated have information.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...