0

I have variable int array like this

int[] sample = new int[];
sample[0] = 1;
sample[1] = 2;

String two = sample[1].toString(); <==== i have problem with this

System.out.println(two);

how to resolve them? i cannot to show value of int[1] as string..

1
  • 4
    you mean sample[1] instead of int[1], right? Commented Mar 30, 2016 at 3:21

5 Answers 5

8

You cannot do

int i = 2;
String two = i.toString();  // or sample[1].toString();

As int is a primitive type, not an object. As you're working with the int[] sample array, notice that while sample is an object, sample[1] is just an int, so the primitive type again.

Instead, you should do

int i = 2;
String two = String.valueOf(i); // or String.valueOf(sample[1]);

But if your problem is just printing the value to System.out, it has a println(int x) method, so you can simply do

int i = 2;
System.out.println(i);  // or System.out.println(sample[1]);

Now, if you want to print the complete representation of your array, do

System.out.println(Arrays.toString(sample));
Sign up to request clarification or add additional context in comments.

Comments

0

Change this line:

String two = sample[1].toString(); <==== i have problem with this

To this:

String two = String.valueOf(sample[1]);

Comments

0

There is an alternate way to what @ericbn has proposed. You can create Integer object from your int primitive type and then use toString method to get the String value of it:

Integer I = new Integer(i);
System.out.println(I.toString());

4 Comments

Not the best practice though, as it creates an intermediate wrapper object.
And you should always use Integer.valueOf instead.
@chrylis where do you mean?
Don't use new Integer.
0

You can also try it with String.valueOf() of instead toString(). The program can be edited as,

int[] sample = new int[];
int[0] = 1;
int[1] = 2;

String two = String.valueOf(int[1]);
System.out.println(two);

I hope this will help you.

You can also refer following link int to string conversion

Comments

-1

Another solution can be-

String two = sample[1]+"";//concatenate with empty String
System.out.println(two);

1 Comment

Another bad practice!

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.