Hi,
I have a byte type variable and I need to create something like :
abc = new byte(String Values)
or even a
abc = new byte(byte[] Values)
There isn't a constructor that can do this. Can you please recomend the best
way to do this?
What type did you want abc to be ?
If abc is supposed to be an array of bytes representing the string:
byte [ ] abc = values.getBytes("UTF-8");
To copy a byte array called values into another, new byte array:
byte [ ] abc = new byte [values.length] ;
System.arraycopy(values,0,abc,0,values.length);
Assuming values is a String that you want to disect.
"UTF-8" represents an encoding that code from the 16-bit Unicode characters
in the String to an 8-bit byte sequence.
If you expect the String values to be a decimal representation of a value
between 0 and 255 (which can be represented in a single byte), then you can
use:
byte abc = Byte.parseByte(values);
And if you read such a value as bytes from an InputStream and want the same
result:
byte abc = Byte.parseByte(new String(values, "UTF-8"));
Here you also see the encoding representation of Unicode as bytes.
There are other encodings which work closer to the ASCII standard, where
each byte actually represents a single character.
Also, what is the differnece between a Byte and byte datatype.
Byte is a class that has been defined to give a programmer information
about the primitive byte datatype (such as Byte.MAXVALUE, which is 255) and
provide extra functionality with respect to the byte primitive.
You can also create an immutable Object that contains a byte value, so that
you can mix different primitives and any other objects in an array or Vecor
class:
Object [ ] anything = new Object [5] ;
anything[0] = new Byte(128);
anything[1] = new Integer(32767);
anything[2] = "Some string" ;
anything[3] = new Character('\\');
anything[4] = new java.awt.Frame("Hello World!");
anything[1] = 32767 ; would not work, since the array is not of the
primitive type int.
The Javadoc documentation of the JSDK is a very good reference to see what
the Byte, Integer and other primitive representing classes can do.
Many Thanks for your time,
- Bharat.
Cheers.