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..

hk21_4
  • 59
  • 6
unknown
  • 1,460
  • 2
  • 12
  • 15

5 Answers5

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));
Community
  • 1
  • 1
ericbn
  • 10,163
  • 3
  • 47
  • 55
0

Change this line:

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

To this:

String two = String.valueOf(sample[1]);
Matt C
  • 4,470
  • 5
  • 26
  • 44
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());
Pooya
  • 6,083
  • 3
  • 23
  • 43
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

Community
  • 1
  • 1
Pratik Rawlekar
  • 327
  • 4
  • 14
-1

Another solution can be-

String two = sample[1]+"";//concatenate with empty String
System.out.println(two);
Rasel
  • 5,488
  • 3
  • 30
  • 39