0

What are the total number of bytes needed to store this in java?

String str = "1234"

navneet
  • 1
  • 1
  • That depends on what character encoding you use. If it's UTF-8, it would be 4 bytes with those specific characters, but it could be more with different characters. ASCII: 4 bytes, UTF-16: 8 bytes. – Jesper May 20 '22 at 07:03
  • It also depends on the Java version, how much of the `String` representation you are considering, etc, etc. (For example, a `String` object typically consists of 2 objects ... both of which have an object header. But the size and type of the array is version dependent.) – Stephen C May 20 '22 at 07:07
  • 1
    @Jesper Java doesn't use UTF-8 to store strings in memory. They are stored in either UTF-16 or ISO-8859-1 (starting from Java 9). – Olivier May 20 '22 at 07:09
  • 2
    @Olivier But it is not clear what navneet means with "store". Does he mean "store in memory" or "store in a file"? – Jesper May 20 '22 at 07:10
  • 1
    @Jesper If it was "stored in file", the question would not be related to Java. – Olivier May 20 '22 at 07:11
  • 2
    Yes ... but you can store a "string" in memory in lots of ways in Java. `String` is only one possibility. – Stephen C May 20 '22 at 07:12
  • 2
    See also https://stackoverflow.com/questions/31206851/how-much-memory-does-a-string-use-in-java-8. – CoolMind May 20 '22 at 07:14

0 Answers0