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"});
Related
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.
I thought that the String array length cannot be changed once we define the size.
But I am not sure why it is allowing me to change it here (for the piece of code)?
public class Test1 {
public static void main(String[] args) {
//size =3
String[] roleNameArray = { "a", "b", "c" };
// I also tried with
//String[] roleNameArray = new String[3];
//roleNameArray[0]="a";
//roleNameArray[1]="b";
//roleNameArray[2]="c";
System.out.println(roleNameArray.length);
roleNameArray = addMoreValues();
// size changed to 4
System.out.println(roleNameArray.length);
}
public static String[] addMoreValues() {
final String[] roleNameArra = new String[4];
roleNameArra[0] = "a";
roleNameArra[1] = "b";
roleNameArra[2] = "c";
roleNameArra[3] = "d";
return roleNameArra;
}
}
OUTPUT:- 3 4
Here the size=3 when we initialized the array "roleNameArray"
Then the size changes to 4 for "roleNameArra" being equated to "roleNameArray".
Questions:-
The size of String array has been changed in this case?
If not what happens in memory in this case of JAVA? (java
version used 1.8)
In the method addMoreValues you are creating a new array, which has nothing to do with the old array. Only because you fill the variable named roleNameArray with a reference to the new array you see the updated length. If you just call addMoreValues without updating the local variable (so without roleNameArray =), the old and unchanged array will be used.
That's because you created new array instance.
final String[] roleNameArra = new String[4];
And then you changed reference of old array to the new one (returned from function).
Maybe this ?
final String[] roleNameArra = new String[4];
You are not changing its size you are assigning it to a new one.
I recommend that you read more about java collections.
You haven't changed the length of the roleNameArray. In your method you created new array of size 4 and then returned the reference to it.
So now in roleNameArray you have array from your method, not from main.
What's difference between
String [] O = {};
and
String[] Ox = new String[3000];
How can I copy the strings from Ox to O?
O is empty array and Ox has 3000 length, to copy Ox to O you have to use copyOf() api of Arrays class.
O = Arrays.copyOf(Ox, Ox.length);
Arrays.copyOf() create change the O array length to 3000 and copy all contents.
public static void main(String[] args) {
String [] O = {};
String[] Ox = new String[3000];
O = Arrays.copyOf(Ox, Ox.length);
System.out.println("O array length : "+O.length); // I am just printing length
}
Output :
O array length : 3000
Internal implementation of copyOf() api of Arrays class.
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
Array is immutable so you can not assign 3000 size array to size 0 array, in implementation of copyOf() method java created new array char[] copy and using native method copy content of original array to copy array.
So, in you code you can not directly copy Ox array contents to O array for that you have to create array of size 3000 or use copyOf() api of Java.
In Java arrays are not mutable, thus you can not change the size of an array. Because you declare O as size 0 implicitly (the {} means its empty) it can not be filled.
You need to declare a new array of size 3000 (new String[3000]) and then use that
O is an empty array, so you can't copy anything to it.
With the following statement you declare a table O that is empty (size=0, no elements).
String[] o = {};
If instead you write:
String[] o = {"this", "is", "a", "test"};
you have initialized table O to have size=4 and contain the four string elements "this", "is", "a" and "test".
Finally, if you initialize your table in the following way:
String[] o = new String[4];
you have declared that your array has size=4, but all four elements are null. Of course, you can later change the values of your array (eg. o[3] = "test").
Now, if you want to copy the elements of one array to the other you can use the Arrays.copyOf(o, o.length); method, but in the following way :
String[] o = {"this", "is", "a", "test"};
String[] copy; // you don't have to (and shouldn't) initialize this variable to {}
copy = Arrays.copyOf(o, o.length);
There are a couple of differences here:
1) String [] O = {};
this means to create a new String[] called O which is initialized with the data set contained in {}. Since there is no data, O is "empty".
This means that O.length = 0, or put another way, this Array has no memory associated with it for storage purposes.
Since Arrays are immutable in java, you cannot do anything further with this array.
You could have done:
String[] O = {"bob","Cat","ralph"}
O.length // == 3
O[0] // bob
O[1] // Cat
O[2] // ralph
O[1] = "Sting"
O[1] // now set to Sting
O[4] = "Cause an Exception" // causes an index out of bounds exception
2) String[] O = new String[3000];
In this case you have created a new String[] with 3000 "spaces" or "indices" available. What this really means is that you can maintain references to 3000 String objects in this array.
So:
O.length; //3000 because that is the length of this array
O[0] // will return null since we have not stored anything here
O[0] = "My String"
O[0] // now equals "My String"
O[3001] // throws an index out of bounds exception
3) How can you copy between them:
In short you cannot in this case. Since array 1 (String[] O = {}) is empty and has a length of 0 any attempt to copy to or from this array will result in an exception.
Thanks to all - brings some new Information for me -
but
O = Arrays.copyOf(Ox, Ox.length);
from atish shimpi
helps to solve the Problem :))
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 trying to instantiate the String array cool with items from the file "cool.txt" and the same for the array warm except with the text file "warm.txt" the program works to an extent however many elements of the array are labeled as null like this
This is partially correct as they array has all the correct items; just millions of null's after
here is my code
int count2=0;
int count3=0;
String[] filename ={"Cool.txt","Warm.txt"};
String[] cool =new String[30];
String[] warm =new String [3000];
String[][] arrays = new String [][]{cool,warm};
BufferedReader fr;
try
{
for(int i=0; i<2; i++)
{
fr = new BufferedReader(new FileReader(filename[i]));
String line = fr.readLine();
while (line != null)
{
if (i<=0)
{arrays[i][count2]=line;
System.out.println("COOL");
count2++;}
if(i>=1)
{arrays[i][count3]=line;
System.out.println("WARM");
count3++;}
line = fr.readLine();
}
fr.close();
}
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
}
catch(Exception F){
System.out.println("NUL");
}
}
When you create an array of objects in Java, they are initialized to a default value. For integers, this is 0. For Objects, such as String, this is a null-reference. As your array is made to contain 30000 elements, it will have the elements from your file (about 5), and the rest will not be initialized (null).
If you wish to use a list of Objects that has a variable size, you can look up ArrayLists, or other types of Lists. If you were to replace the following lines:
String[] cool =new String[30];
String[] warm =new String [3000];
and
System.out.println(Arrays.asList(warm));
System.out.println(Arrays.asList(cool));
with
List<String> cool = new ArrayList<String>();
List<String> warm = new ArrayList<String>();
and
System.out.println(warm);
System.out.println(cool);
You would get the correct result.
You were already using lists in a way: the method call Arrays.asList converts the argument to an object of the type List.
At the end of the function you end up converting them to list objects. If you just use a List to start with you won't have "millions" of nulls. The reason why you get nulls is you can only allocate the array one time, so all slots are defaulted to null.