-9

I am new to Java. I simply want to make an array of ints and an array of Strings.

I tried the following:

int() myArrayOfInts == new int(23);
String() myArrayOfStrings == new String(4);

I am not sure why it won't work.

M A
  • 65,721
  • 13
  • 123
  • 159
Mike Jones
  • 53
  • 2
  • 6

4 Answers4

1

Very close. Just wrong brackets. It's simply int[] myArrayOfInts = new int[23]; , for strings it is String[] myArrayOfStrings = new String[4];

Sagar Pudi
  • 4,040
  • 3
  • 30
  • 51
BlueShark
  • 100
  • 3
  • 5
  • 19
1

The correct syntax for creating arrays is the following:

int[] arrayOfInts = new int[23];
String[] arrayOfStrings = new String[4];

See this Java tutorials page for using arrays.

M A
  • 65,721
  • 13
  • 123
  • 159
1

Use [] instead of (). In java == is used for comparison so use = to assign any value.

Creating int array

  int[] myArrayOfInts = new int[3]; 
  int myArrayOfInts[] = new int[3]; //Legal but don`t use it, less readable
  int[] myArrayOfInts = {1,2,3};

Creating String Array

  String[] myArrayOfStrings = new String[2];
  String myArrayOfStrings[] = new String[2];//Legal but don`t use it, less readable
  String[] myArrayOfStrings = {"Hello","World"}
Anurag Anand
  • 490
  • 1
  • 7
  • 13
0

Also you can use ArrayList, and may have not static size of array

ArrayList<Integer> myArrayOfInts = new ArrayList<Integer>(0);
myArrayOfInts.add(5);
myArrayOfInts.add(6);

for (int a : myArrayOfInts) {
    System.out.println(a);
}

And for String:

ArrayList<String> myArrayOfStrings = new ArrayList<String>(0);
myArrayOfStrings.add("Hello");
myArrayOfStrings.add("World!");
 for (String b : myArrayOfStrings) {
    System.out.println(b);
}

Don't forgot to put import java.util.ArrayList; on the upper of file

Artik
  • 143
  • 4
  • 14