Difference between byte and char array?

T

The DUDE

In terms of comparing to characters would there by a reason to use
a byte or a char?

byte[] s = string.getBytes(); // Or: char[] s = string.toCharArray();

int length = s.length;
byte b = 0; // or char b

for (int i = 0; i < length; i++) {
b = s;

if ((b >= 'a') && (b <= 'z')) {
// do something
}
}
 
P

pete kirkham

The said:
In terms of comparing to characters would there by a reason to use
a byte or a char?

If you want to compare character values, use char.
If you want to compare the binary values of the UTF-8 encoding of the
characters, use byte. One character may be encoded by several bytes.

toCharArray is generally faster than toByteArray, but often slower than
charAt. Benchmark for your typical string length before making this
'optimization' (see
http://forum.java.sun.com/thread.jsp?forum=31&thread=441649).


Pete
 
?

=?ISO-8859-1?Q?Daniel_Sj=F6blom?=

The said:
In terms of comparing to characters would there by a reason to use
a byte or a char?

byte[] s = string.getBytes(); // Or: char[] s = string.toCharArray();

int length = s.length;
byte b = 0; // or char b

for (int i = 0; i < length; i++) {
b = s;

if ((b >= 'a') && (b <= 'z')) {
// do something
}
}


Use char over byte whenever possible. Better performance, easier to
understand. However, in this particular case I would use neither
toCharArray() nor getBytes(). Use charAt(i) instead, and use the
CharSequence interface over String. This way you can compare
StringBuffers, CharBuffers, Strings and any other classes implementing
CharSequence with a single method.
 
B

Brad BARCLAY

The said:
In terms of comparing to characters would there by a reason to use
a byte or a char?

byte[] s = string.getBytes(); // Or: char[] s = string.toCharArray();

Stick with chars as much as possible. They ar ethe proper Java
mechanism for representing character data.

The only time you should use bytes to represent character data is when
you're dealing with hardware subsystems or other applications that
expect character data to be represented by bytes. For example, if
you're writing an application that uses the Java Communications API to
write data to a serial port, you'll want to use bytes (unless the device
you're connecting to can handle Java chars, which is only generally
going to be the case if the other end is also a Java application). Or
if you're writing textual data to a file on an OS that assumes 8-bit
characters.

Otherwise, you can get into all sorts of nasty encoding issues that are
completely avoidable if you stick with chars.

Brad BARCLAY
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top