I am new to Java. I simply want to make an array of int
s and an array of String
s.
I tried the following:
int() myArrayOfInts == new int(23);
String() myArrayOfStrings == new String(4);
I am not sure why it won't work.
I am new to Java. I simply want to make an array of int
s and an array of String
s.
I tried the following:
int() myArrayOfInts == new int(23);
String() myArrayOfStrings == new String(4);
I am not sure why it won't work.
Very close. Just wrong brackets.
It's simply int[] myArrayOfInts = new int[23];
, for strings it is String[] myArrayOfStrings = new String[4];
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.
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"}
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