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.
Related
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 :))
public class Sonnet29 implements Poem {
private String[] poem;
public Sonnet29() {
poem = { "foo", "bar" , "baz"};
}
#Override
public void recite() {
//...
}
}
Line poem = { "foo", "bar" , "baz"}; is giving compilation error.
Any specific reason why this is not allowed?
How do I initialize a String array with array constants?
EDIT: Thank you folks for your answers. Now I'm clear what is allowed and what is NOT.
But can I ask you why this is NOT allowed?
String[] pets;
pets = {"cat", "dog"};
After googling a bit, I found this link, where in, it is told that coding like this leaves the compiler in ambiguity - whether the pets should be array of Strings or array of Objects. However from the declaration, it can very well figure out that it is a String array, right???
This will do what you're looking for:
public Sonnet29() {
poem = new String[] { "foo", "bar", "baz" };
}
Initialization lists are only allowed when creating a new instance of the array.
From the Java language specification:
An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values
In short, this is legal code:
private int[] values1 = new int[]{1,2,3,4};
private int[] values2 = {1,2,3,4}; // short form is allowed only (!) here
private String[][] map1 = new String[][]{{"1","one"},{"2","two"}};
private String[][] map2 = {{"1","one"},{"2","two"}}; // short form
List<String> list = Arrays.asList(new String[]{"cat","dog","mouse"});
and this is illegal:
private int[] values = new int[4];
values = {1,2,3,4}; // not an array initializer -> compile error
List<String> list = Arrays.asList({"cat","dog","mouse"}); // 'short' form not allowed
{"cat", "dog"}
Is not an array, it is an array initializer.
new String[]{"cat", "dog"}
This can be seen as an array 'constructor' with two arguments. The short form is just there to reduce RSI.
They could have given real meaning to {"cat", "dog"}, so you could say things like
{"cat", "dog"}.length
But why should they make the compiler even harder to write, without adding anything useful? (ZoogieZork answer can be used easily)
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"});
I have a query about strings.
I'm declaring my string array as:
private static String[] name;
I'm then trying to add a string to it:
name[0] = temp // Where temp as another string
I am getting a nullpointer error with the above code. Am I initialising my string array correctly?
Looks like you've missed to write
name = new String[CAPACITY];
somewhere
If you want to add dynamically elements to an Array of Strings I would recommend you to do
private static ArrayList<String> name = new ArrayList<String>();
and then use below to add Strings:
name.add(temp);
If you know the size that it will have, then you can create an array like this:
private static String[] name = new String[10]; //if it's going to have 10 elements (typo corrected)
The problem is you have not initialized your string array.
You can declare and initialize it this way:
private static String[] name = new String[4]; Where '4' is the size of your array.
or:
private static String[] name = {temp, temp2, temp3}; Where the temps are each individual item in the array.
At the point
private static String[] name;
in your code, 'name' is still null.
for an array of Strings you have to declare the (constant) number of strings you want to store.
int n = 10;
private static String[] name = new String[n];
You then cannot ever write more than n strings to your array.
If you want to have the number of strings dynamically, you have to use a Vector<String> or an ArrayList<String>. Both objects use the myStrings.add(String string)-method to add a string and you can access strings by calling myStrings.get(int position).
I am new to Java and for the time created an array of objects in Java.
I have a class A for example -
A[] arr = new A[4];
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.
To be able to manipulate/access the objects I had to do this:
A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
arr[i] = new A();
}
Is this correct or am I doing something wrong? If this is correct its really odd.
EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.
This is correct.
A[] a = new A[4];
...creates 4 A references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod() without allocating a1 like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )
Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -
Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.
Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.
Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.
Declaring Arrays In Java
This is how we declare a one-dimensional array in Java –
int[] array;
int array[];
Oracle recommends that you use the former syntax for declaring arrays.
Here are some other examples of legal declarations –
// One Dimensional Arrays
int[] intArray; // Good
double[] doubleArray;
// One Dimensional Arrays
byte byteArray[]; // Ugly!
long longArray[];
// Two Dimensional Arrays
int[][] int2DArray; // Good
double[][] double2DArray;
// Two Dimensional Arrays
byte[] byte2DArray[]; // Ugly
long[] long2DArray[];
And these are some examples of illegal declarations –
int[5] intArray; // Don't mention size!
double{} doubleArray; // Square Brackets please!
Instantiation
This is how we “instantiate”, or allocate memory for an array –
int[] array = new int[5];
When the JVM encounters the new keyword, it understands that it must allocate memory for something. And by specifying int[5], we mean that we want an array of ints, of size 5.
So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of type int[]
Initialization
Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.
All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –
int[] arr = {1, 2, 3, 4, 5};
Here, we don’t mention the size, because JVM can see that we are giving 5 values.
So, until we instantiate the references remain null. I hope my answer has helped you..! :)
Source - Arrays in Java
You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:
A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
limit(4) sets amount of elements which stream will generate
toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.
For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.
Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:
public class MainClass
{
public static void main(String args[])
{
System.out.println("Hello, World!");
//step1 : first create array of 10 elements that holds object addresses.
Emp[] employees = new Emp[10];
//step2 : now create objects in a loop.
for(int i=0; i<employees.length; i++){
employees[i] = new Emp(i+1);//this will call constructor.
}
}
}
class Emp{
int eno;
public Emp(int no){
eno = no;
System.out.println("emp constructor called..eno is.."+eno);
}
}
The genaral form to declare a new array in java is as follows:
type arrayName[] = new type[numberOfElements];
Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).
Lets initialize an array to store the salaries of all employees in a small company of 5 people:
int salaries[] = new int[5];
The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.
Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:
int salaries[] = {50000, 75340, 110500, 98270, 39400};
Or to do it at a later point like this:
salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;
More visual example of array creation:
To learn more about Arrays, check out the guide.
Yes it is correct in Java there are several steps to make an array of objects:
Declaring and then Instantiating (Create memory to store '4' objects):
A[ ] arr = new A[4];
Initializing the Objects (In this case you can Initialize 4 objects of class A)
arr[0] = new A();
arr[1] = new A();
arr[2] = new A();
arr[3] = new A();
or
for( int i=0; i<4; i++ )
arr[i] = new A();
Now you can start calling existing methods from the objects you just made etc.
For example:
int x = arr[1].getNumber();
or
arr[1].setNumber(x);
For generic class it is necessary to create a wrapper class.
For Example:
Set<String>[] sets = new HashSet<>[10]
results in: "Cannot create a generic array"
Use instead:
class SetOfS{public Set<String> set = new HashSet<>();}
SetOfS[] sets = new SetOfS[10];
Suppose the class A is such:
class A{
int rollno;
int DOB;
}
and you want to create an array of the objects for the class A. So you do like this,
A[] arr = new A[4]; //Statement 1
for (int i = 0; i < 4; i++) {
arr[i] = new A(); //Statement 2
}
which is absolutely correct.
Here A is the class and in Statement 1 Class A is a datatype of the array. When this statement gets executed because of the new keyword an object is created and dynamically memory is allocated to it which will be equal to the space required for the 4 blocks of datatype A i.e, ( for one block in the array space required is 8 bytes (4+4), I am assuming int takes 4 bytes of space. therefore total space allocated is 4*4 bytes for the array ).
Then the reference of the object is given to the arr variable. Here important point to note is that Statement 1 has nothing to do with creating an object for class A ,no object is created for this class it is only used as a datatype which gives the size of the class A required for the memory allocation of the array.
Then when for loop is run and Statement 2 is executed JVM now allocates the memory for the Class A (i.e creates an object) and gives its reference to the arr[i]. Every time the loop is called an object is created and the reference of it is given to arr[i].
Thus, arr[0] which holds a space of 8 bytes is given the reference of the object of the Class A and everytime loop is run new object is created and reference is given to that object so that it can now access the data in that object .