This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Pourang, 1) s.length() will give you the number of bytes. Since characters are one byte (at least in ASCII), the number of characters is the same as the number of bytes. Another way is to get the bytes themselves and count them s.getBytes().length.
2) As Strings are immutable, you would need to have a 100 byte array with data on hand at string creation time and pass it to the constructor.
As Jeanne and Tony's answers make clear, it depends on what you want to do with the String.
In Java, the primitive char type is 2 bytes as they are Unicode values. As String uses a char to hold the characters, in memory the characters themselves take 2 * s.length() bytes. This doesn't count the overhead of the array itself or the String. This is just the block of bytes for the characters.
If you want to write a String to a file or send it over a Socket, you need to first convert it to bytes. By default, Java uses a modified form of UTF-8 to encode and decode char to byte. For standard ASCII characters (everything in my post), it maps the lower byte of the char directly to a byte.
For example (\u??? is a Unicode char constant and 0x?? is a byte constant, both in hexadecimal -- base 16 rather than base 10):The short of it is, if you want to create a String that will encode into 100 bytes, create a String of 100 ASCII characters.
Of course, if your goal is to send/write byte arrays, why not just create one and skip the String entirely? [ January 31, 2005: Message edited by: David Harkness ]