-3

Do we any lib or method which will tell us the size of string value in bytes , am checking for size not length .

can anyone help me on this

.getBytes().length gives the length of the string not size , for example

String s = "Apple"

s.getBytes().length returns 5 , i think this length not size

Bravo
  • 8,589
  • 14
  • 48
  • 85
  • there is a method .getBytes() this will return the size in bytes – AMA Mar 17 '20 at 05:07
  • https://stackoverflow.com/q/16270994/438992 etc. I just searched for "java length of string in bytes". – Dave Newton Mar 17 '20 at 05:07
  • 5
    Does this answer your question? [Bytes of a string in Java](https://stackoverflow.com/questions/4385623/bytes-of-a-string-in-java) – GaganSailor Mar 17 '20 at 05:08
  • 1
    [`.getBytes("UTF-8").length`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#getBytes-java.lang.String-) (or `"UTF-16"`, etc) – Elliott Frisch Mar 17 '20 at 05:08

1 Answers1

0

There is a method called getBytes() string.getBytes().length will give number of bytes used by the string to store the value. In normal circumstances each character can take 2 bytes each to store a unicode value.

    final String string = "Hello World";

    final byte[] utf8Bytes = string.getBytes("UTF-8");
    System.out.println(utf8Bytes.length); 
Bindu
  • 29
  • 4