+ 1
How to know the number of bytes in a string?
Ex-Hello world What would be the number of bytes in it?
9 Antworten
+ 2
Java strings are stored in UTF-16BE encoding, which use 2 bytes per character.
So you can simply use String.length() method.
length of string × 2 (byte)
Let, x = "Hello world"
Then its total bytes will be..
x.length()*2
+ 2
Depends on the charecter encoding scheme it using..
String s = "Hello World";
byte[] b = s.getBytes(); // default UTF-8 hoping";
//Utf-8 requires 1byte ,
//utf-16 requires 2bytes...
System.out.println(b.length); //output : 11 ( by utf-8)
+ 2
Atul with more bytes can be coded more characters in Unicode table eg Chinese characters
but it is not so trivial
UTF-8 can use 1 - 4 bytes and
UTF-16 can use 2 or 4 bytes
Java language developers (by JEP 400) want UTF-8 as default for Java 18
they explain
"In JDK 17 and earlier, the default charset is determined when the Java runtime starts. On macOS, it is UTF-8 except in the POSIX C locale. On other operating systems, it depends upon the user's locale and the default encoding"
0
But why it store 2 bytes? Any internal workings of it?
0
Thank you all. This concepts are a bit complex for me . Are these things covered in sl course?
0
https://stackoverflow.com/questions/4385623/bytes-of-a-string-in-java/4385653#:~:text=Java%20strings%20are%20physically%20stored,final%20byte%5B%5D%20utf16Bytes%3D%20string
Hope this helps you
0
Please answer me??
0
Why you all are downvoting my answer just tell me the reason why for 2 bytes ? Any internal workings of it
0
All its depends on encoding scheme its using on..
One byte is enough for English alphabet but java supports almost all charecters that exists in world's as already told Chinese characters.., so they need more bytes to support all.. java supports most encoding schemes externally..
Hope this link clears more..
https://www.geeksforgeeks.org/how-to-get-and-set-default-character-encoding-or-charset-in-java/amp/
Edit:
Atul
You can tag names if you are returning to answer after long time gap. Because may unsubscribe,may not see your answers..