In Java chars are 2 bytes long, But when I write a string to a file using a bytebuffer the filechannel position increments by the number of chars. I read that the Filechannel.position() method returns the number of bytes from the beginning of the file to the current position so shoudnt it increment by 2*numberof chars?.
Not quite. In Java, the char
type is twice the bit width of the byte
type, but that only means chars can be two bytes long. It depends on your String's character encoding, but with UTF-8 encoding (the default), chars are encoded as only one byte for chars between 0 and 127, but multiple bytes for chars over this range (when the high bit is set, it means the next byte is also part of the current char)
For Strings made of only 0-127 characters (ie "normal text"), byte length will equal char length.
If your String contains characters outside the range 0-127, byte length will be greater than the number of characters.