+ 1

How to know the number of bytes in a string?

Ex-Hello world What would be the number of bytes in it?

28th Oct 2021, 3:01 PM
Atul
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
28th Oct 2021, 3:06 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 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)
28th Oct 2021, 3:16 PM
Jayakrishna 🇮🇳
+ 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"
28th Oct 2021, 4:22 PM
zemiak
0
But why it store 2 bytes? Any internal workings of it?
28th Oct 2021, 3:35 PM
Atul
0
Thank you all. This concepts are a bit complex for me . Are these things covered in sl course?
28th Oct 2021, 5:45 PM
Atul
28th Oct 2021, 5:52 PM
Atul [Inactive]
0
Please answer me??
30th Oct 2021, 6:29 PM
Atul
0
Why you all are downvoting my answer just tell me the reason why for 2 bytes ? Any internal workings of it
31st Oct 2021, 4:55 AM
Atul
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..
31st Oct 2021, 3:22 PM
Jayakrishna 🇮🇳