Reputation: 1579
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..
Upvotes: 0
Views: 103
Reputation: 5734
Another solution can be-
String two = sample[1]+"";//concatenate with empty String
System.out.println(two);
Upvotes: -1
Reputation: 327
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
Upvotes: 0
Reputation: 6126
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());
Upvotes: 0
Reputation: 4555
Change this line:
String two = sample[1].toString(); <==== i have problem with this
To this:
String two = String.valueOf(sample[1]);
Upvotes: 0
Reputation: 10948
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));
Upvotes: 8