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..
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));
Change this line:
String two = sample[1].toString(); <==== i have problem with this
To this:
String two = String.valueOf(sample[1]);
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());
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
Another solution can be-
String two = sample[1]+"";//concatenate with empty String
System.out.println(two);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.