How do you initialized an array in java first, and then set values to them by using their indexes? So for example, you make an array in java, and then you want the value of the number 75 index of the array to be set to "seventy five", can you do something like array[75] = "seventy five"?;
String[] array;
array[0] = "zero";
array[1] = "one";
array[2] = "two";
When I tried the codes below it says unknown class array. What am I doing wrong?
String[] array = new String[10];
array[0] = "zero";
First, you'll need to point the array reference to an actual array object.
For example,
String[] array = new String[3];
You can initialize the contents like you're doing.
Or you can initialize them in the array creation expression:
String[] array = new String[] { "zero", "one", "two" };
You can also the array initializer by itself in the declaration:
String[] array = { "zero", "one", "two" };
First, it is recommended not to initialize an array like
String[] a;
Because its actually not an array and you could get Null Pointer Exeption.
I think you'll just have to initialize the array from scratch.
String[] array = new String[] { "zero", "one", "two", "three", "four" };
I am not familiar with android studio but your problem is not in array declarations your jvm is not recognizing String class.
Related
Let's say I have in Java 8 the following objects defined:
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Now I want to create an array containing these two string arrays. How do I write this?
I tried:
String[][] = {emptyArr, filledArr, moreFilledArr};
This doesn't work. Then I tried:
(String[])[] = {emptyArr, filledArr, moreFilledArr};
With the brackets in the second version I want to indicate that the array is one of string arrays and not a two-dimensional array. Still no success.
What's the correct way to do it? Is there one? Or do I have to resort to ImmutableList to create an immutable data-structure here.
You have forgotten to give the variable a name? Both of these work.
String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
I recommend you to go through the basic Java syntax specification and tutorials. Start with The Java Tutorials by Oracle Corp, free of cost.
these two are right too
String[][] array = {emptyArr, filledArr, moreFilledArr};
String[][] array = new String[][] {emptyArr, filledArr, moreFilledArr};
please do check these too
Docs for Array in Java Have a Look for more clarification
tutorial of array with java docs
,
I had to add this as a comment but I couldn't, I want to extend with more resources mentioned above , Thanks
We can also achieve it by initialising and assigning to a single dimensional array of type Object. Something like below.
String[] filledArr = new String[] {"Hallo"};
String[] moreFilledArr = new String[] {"Hallo", "duda"};
String[] emptyArr = new String[] {};
Object[] newArr = {filledArr, moreFilledArr, emptyArr};
If you want to print the values inside this newArr, then you shall use the below code.
for (int i=0;i< newArr.length; i++){
Arrays.stream(((String[]) newArr[i])).forEach(System.out::println);
}
I'm quite new to Java, and I'm not sure about is it possible to do something like below and how to do it with code.
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String[] b = new String[]{ //I want to put a's element in here assume I don't know what's the length of a };
Any idea of what I can put inside the braces after the constructor to initialize the string array b.
p.s. I'm not allowed to use string array a directly and must use constructor to declare string array b. I'm not allowed to use ArrayList.
Thanks!
The most concise way would be:
String[] b = Arrays.copyOf(a, a.length);
Use array copy to do the task.
Its prototype is:-
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
String[] a = {"a", "b", "c", ...}; //unknown amount of elements
String []b=new String[a.length];
System.arraycopy(a,0,b,0,a.length);
Below is a sample of code I am using to add to an array. Basically if I understand correctly currently I am copying an Array into a List, then adding to the list and copying back to an array. It seems like there should be a better way to do this.
List<String> stringList = new ArrayList<String>(Arrays.asList(npMAROther.getOtherArray()));
stringList.add(other);
npMAROther.setOtherArray(stringList.toArray(new String[0]));
I just edited my question for a bit more clarity. The for loop previously seen wasn't exactly needed in regards to my original question. I am simply looking for a more efficient way to add to an array.
If this is something that is done frequently, consider using a list. However...
You can easily add a single element to the end of an array like this.
final String[] source = { "A", "B", "C" };
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = "D";
for(final String s : destination) {
System.out.println(s);
}
You can also make it a method.
public static String[] addToArray(final String[] source, final String element) {
final String[] destination = new String[source.length + 1];
System.arraycopy(source, 0, destination, 0, source.length);
destination[source.length] = element;
return destination;
}
Supposing you want to use an array, not a list and that all the array elements are filled, you would copy the array in an array that has the size of the original array plus the string list size, then append the list elements at the end of the array:
String[] array = npMAROther.getOtherArray();
List<String> listElementsToAppend = marOther.getOtherListList();
int nextElementIndex = array.length;
// Increase array capacity
array = Arrays.copyOf(array, array.length + listElementsToAppend.size());
// Append list elements to the array
for (String other : listElementsToAppend) {
array[nextElementIndex++] = other;
}
There are many ways to combine arrays in O(N) time. You could do something more readable than your code, for instance :
String[] arr1 = {"1", "2"}, arr2 = {"3", "4"};
ArrayList<String> concat = new ArrayList<>(); // empty
Collections.addAll(concat, arr1);
Collections.addAll(concat, arr2);
// concat contains {"1", "2", "3", "4"}
Let's say we defined an array with 20 elements. is there any way we can add some objects to the array, without any specific order of course and not just once like String[] t= {"one", "two", ..., "twenty"} ?
String[] t = new String[20];
//I know this won't work
//but something like this:
//t = {"one", "two", "three"}
//and later, add some more
//t = {"four"} ...
There are several ways to initialize the elements in an Array,
String[] t = new String[20];
t[0] = "zero";
t[1] = "one";
You can also use System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) to copy from one to another (if that's what you mean). Here concatenate Array(s) a and b to a new Array c.
String[] a = {"Hello"};
String[] b = {"World"};
String[] c = new String[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
System.out.println(Arrays.toString(c));
Output is
[Hello, World]
You cannot change the size of the array, but you can assign elements at specific positions.
t[3] = "four";
Re-ordering and remembering where the array is supposed to end may or may not become cumbersome.
For more flexible "arrays", people like to use java.util.ArrayList.
You can assign values like this
t[10] = "ten";
t[11] = "eleven";
It is better to use ArrayList so there is no need of initializing the size first and it is dynamic too.
Unfortunately, that's not exactly how java arrays work. To instantiate and initialize an array use the syntax...
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
or,
String[] t = {"One", "Two"};
If you want more control over the array the I'd recommend using an ArrayList object instead where you can add, remove, change, sort the items in the array. For example,
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
t.remove(0);
ArrayList is a good option for ArrayList supports dynamic arrays that can grow as needed.
With arrays you can add elements by specifying the specific position you want to add
like adding in position 4 we can do something like array[3] = "four"
but for more control arraylist is recommended
Unfortunately, Array should be used in below way only
String[] t = new String[20];
t[0] = "One";
t[1] = "Two";
...
t[19] = "Twenty";
You can try using arrayList: You need not even specify how many elements are expected while initializing.
ArrayList t = new ArrayList();
t.add("One");
t.add("Two");
...
t.add("Twenty");
I am fresher in java ,i have a doubt in java
that is
String array= new String[]{};
what is the use of { } here ?
what is the difference between String array=new String[]; and String array=new String[]{};
when I am writing String array=new String[10]{}; got error why?
Help me I am confused.
{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings
String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};
while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings
String[] array = new String[10];
...But...
String array = new String[10]{}; //The line you mentioned above
Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.
Additionally
The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.
String array=new String[]; and String array=new String[]{}; both are invalid statement in java.
It will gives you an error that you are trying to assign String array to String datatype.
More specifically error is like this Type mismatch: cannot convert from String[] to String
You have a choice, when you create an object array (as opposed to an array of primitives).
One option is to specify a size for the array, in which case it will just contain lots of nulls.
String[] array = new String[10]; // Array of size 10, filled with nulls.
The other option is to specify what will be in the array.
String[] array = new String[] {"Larry", "Curly", "Moe"}; // Array of size 3, filled with stooges.
But you can't mix the two syntaxes. Pick one or the other.
TL;DR
An array variable has to be typed T[]
(note that T can be an arry type itself -> multidimensional arrays)
The length of the array must be determined either by:
giving it an explicit size
(can be int constant or int expression, see n below)
initializing all the values inside the array
(length is implicitly calculated from given elements)
Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.
Replies
1. String[] array= new String[]{}; what is the use of { } here ?
It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.
2. what is the diff between String array=new String[]; and String array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing String array=new String[10]{}; got error why ?
(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}.
Just make up your mind and use one of those - Java thinks.
help me i am confused
Examples
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Try this one.
String[] array1= new String[]{};
System.out.println(array1.length);
String[] array2= new String[0];
System.out.println(array2.length);
Note: there is no byte code difference between new String[]{}; and new String[0];
new String[]{} is array initialization with values.
new String[0]; is array declaration(only allocating memory)
new String[10]{}; is not allowed because new String[10]{ may be here 100 values};
String array[]=new String[]; and String array[]=new String[]{};
No difference,these are just different ways of declaring array
String array=new String[10]{}; got error why ?
This is because you can not declare the size of the array in this format.
right way is
String array[]=new String[]{"a","b"};
1.THE USE OF {}:
It initialize the array with the values { }
2.The difference between String array=new String[]; and String array=new String[]{};
String array=new String[]; and String array=new String[]{}; both are
invalid statement in java.
It will gives you an error that you are trying to assign String array
to String datatype. More specifically error is like this Type
mismatch: cannot convert from String[] to String
3.String array=new String[10]{}; got error why?
Wrong because you are defining an array of length 10 ([10]), then
defining an array of length String[10]{} 0
Theory above is well explained.
A PRACTICAL USE: Declare an array on the spot for a method parameter.
MyResult result = myMethod(new String[]{"value1", "value2"});