0

Works fine if creating like this:

byte [] d = {1,2};
String ss = new String( d );

But fails if creating like this:

String ss = new String( {1,2} );

or even this:

String ss = new String( {(byte)1,(byte)2});

What is the problem?

1
  • 2
    What does the compiler say? Commented Oct 25, 2013 at 12:28

2 Answers 2

3

String ss = new String( new byte[]{1,2} );

String ss = new String( {1,2} ); doesn't work because arrays cannot be initialized by simply doing a {} block. It requires the new someThing[] in front of it.

Sign up to request clarification or add additional context in comments.

2 Comments

Mind that it's a good practice to identify the encoding being used, e.g. new String(new byte[]{1, 2}, "UTF-8") - otherwise this command is platform specific, using the default charset of the platform
@Rene Well that's correct in that it works. But the question was, why the OP's code fails. And the reason for that is incorrect syntax. You may have mentioned that.
0
String ss = new String (array of bytes);
 we can pass here array of bytes but in
String ss = new String( {1,2} ); {1 , 2} this is not an array and 
String ss = new String( {(byte)1,(byte)2}); {(byte)1,(byte)2} this is also not an array 

So we can simply use 
String ss = new String( new byte[]{1,2} );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.