how to declare an array globally but to set its values later? - java

i want to make use of an array thorughout my program but the values inside of the array would be set after going into a void. I know i can set the values by arr[0] but i have to set somewhat 10 names, as that will be very tedious i was looking for a better solution.
class sample{
String[] names=new String[10];
void main(){
names={"ram","shyam","raj","mohan","raja","adam","ramela","ramwala","ramesh","manu"};
}
}
This is what i tryed out but it give me an error saying that names={"ram"....}; is not a statement.
Help would be appreciated

You can use
names= new String[]{"ram","shyam","raj","mohan","raja","adam","ramela","ramwala","ramesh","manu"};
Array initialiser syntax can only be used at the time of variable declaration so later you have to use new keyword to initialise an array.
From Docs
An array initializer may be specified in a declaration (§8.3, §9.3,
§14.4), or as part of an array creation expression (§15.10), to create
an array and provide some initial values.

You cannot use the {...} literal declaration for arrays after they have been declared or instantiated. You will need to either assign those values during name declaration or loop through the array and assign values for each index.
String[] names = new String[10]{“ram”,...};

Related

What type of syntax is the Java "new Type[]{...}" array literal initialization?

What grabbed my attention, which I cannot explain to myself, is a thought about this well known code:
String[] str = new String[]{"a","b","c"};
Is new String[] a cast? If it is, why do we use new and no brackets? We would cast as in:
float i = (float) 3;
It also seem not to be a constructor, because then we would use it like a function call (e.g new String[](...)).
So what kind of syntax is it, and do we have more of that kind in Java?
This syntax is an example of an 10.6. Array Initializer as part of an 15.10.1. Array Creation Expression.
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
new String[]
is an array creation expression and
{"a","b","c"}
is an array initializer.
Since there are no dimension expression in your array creation expression (i.e. nothing inside the square brackets), there must be an array initializer:
If there are no dimension expressions, then there must be an array initializer.
A newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.
It's called an Array Initializer, and its sole purpose, as the name suggests, is to initialize arrays.
The syntax is related to the array initializer:
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
Basically you not only create the array, but also initialize all its fields in the same instruction.
It is not a cast.
Note that the code:
String[] str = new String[]{"a","b","c"};
is a single command to create and initialize the array but it is also possible to use a less verbose version:
String[] str = {"a","b","c"};
Arrays can be created in multiple ways like below, and you are using the second one which is called the Array Initializer where you create the array while also initializing it.
int[] abc = new int[3]; // This means an array of integers with size 3 is created.
int[] def = new int[]{1,2,3}; // This means an array of integers with size 3 is created and also initialized with the values 1, 2 and 3.
In the second statement, I am creating an array of integers with the elements as 1, 2 and 3 where the size is implicitly 3.
So, in your case String[] str = new String[]{"a","b","c"}; , this statement is creating an array of String values with elements "a", "b" and "c" with the implicit size of the array being 3 due to the 3 elements which it is initialized with.

Can we create an object without parentheses?

According to this site the syntax for creating a Java object is:
<JavaType> <variable> = new <JavaObject>();
Though you don't use any parantheses when creating an Array object and instead type brackets which contains the length of each dimension.
Example:
String[][] stringMatrix = new String[5][10];
What I am wondering is if this syntax is specifically and only for creating an Array object or I can make a custom class whose objects are created in a different way then usual
new <JavaObject>();
statement.
new keyword is used to allocate memory for the specific type, which is followed by new keyword.
MyClass obj = new MyClass();
Above line will create an object (allocate memory) for MyClass and initialize member variable by invoking default constructor.
But, below line of code will only allocate memory and initialize each element of array with default value null.
MyClass[][] objMatrix = new MyClass[5][10];
So, we are just declaring an array of size 5x10(allocating memory), but each element in array need some object reference (since, currently they have null reference). So, for that reason, you need to initialize each objMatrix array element by creating object of MyClass and assigning them to each element.
objMatrix[0][0] = new MyClass();
It is specifically for creating arrays. You're stuck with parentheses for your classes.
You can not create a custom class that changes the way the new operator works. However, there are some special cases where an object can be created without the usual new operator.
E.g.
String[] array = { "foo", "bar", "baz" };
Integer value = 42;
demonstrating that you can create arrays without the new keyword in a variable initializer, use String objects using literals and autobox primitive values to their object counterpart without the usual new syntax, but of course, this is not possible with custom types.
Another possibility to create objects without the new operator is deserializing them, which also works for custom types if they are Serializable.
Starting with Java 8, you can use constructor references if you have an appropriate context, e.g.
BigDecimal[] array = new BigDecimal[20];
Arrays.setAll(array, BigDecimal::new);
System.out.println(Arrays.toString(array));
Here, BigDecimal::new is a reference to a constructor of BigDecimal and it is implied from the context, i.e. Arrays.setAll that the function must be able to consume an int value, as the setAll method will evaluate it for every array element, passing the array index, so we initialize the array with ascending numbers in this example.
Another example would be
BigDecimal[] array = Stream.of("1.23", "4.56", "7.89")
.map(BigDecimal::new)
.toArray(BigDecimal[]::new);
System.out.println(Arrays.toString(array));
where it is implied from the context that the constructor used in the .map(BigDecimal::new) step must consume a String, as it will be evaluated for every stream element, ending up at a different constructor than in the first example.
BigDecimal is an ordinary class and these examples would work with a custom class as well, if it has matching constructors.

Why `Integer[100] arr;` is invalid, while `Ineger[] arr;` is valid?

I was trying to allocate an Integer array for 100 items, why this declaration isn't valid in Java?
Integer[100] intArr1; ----- (1)
Whereas this is valid:
Integer[] intArr; ----- (2)
As (2) is valid, how much memory does it occupy? Can anyone help to explain a bit.
There are some questions in SO which resemble my question, however they are not the same, and I did look in SO before asking this question.
The first one isn't valid because that's not proper Java syntax.
The second one occupies 0 memory, as you haven't created an array. Only a reference to an array, with the reference being null.
You need a new Integer[100] there to actually create the array object.
You are mixing two different things.
One thing is the type of variable. In your case, you want to say "the type of variable intArr is array of Integers", which is this code Integer[] intArr;
In variable, which type is array of Integers you can put any array of Integers you like, no matter the size, therefore you cannot pre-defined it.
The second thing is assign to a variable.
Integer[] intArr = new Integer[10];
To initialise an array with 100 items you write:
Integer intArr1[] = new Integer[100];
Your second line of code just declares a variable, there is no size declared.
When you declare an array, you don't give it a length. You only give it a length when you initialise it.
This is just a declaration:
int[] myArray;
If you want to initialize it with an array of length 100, you do this:
myArray = new int[100];
An uninitialised array is null by default, or inaccessible if it is in a local scope.

Why final is not applicable to array in Java? [duplicate]

This question already has answers here:
Why won't declaring an array final make it immutable in Java?
(6 answers)
Why can I edit the contents of a final array in Java?
(9 answers)
Closed 9 years ago.
I tried using final keyword to array but still i can change the values, why arrays are not supporting final.
Thanks in advance
Because final applies to the array reference, not the contents.
You can modify the array content, but you can't say, reinstantiate the array.
Arrays in java are reference types. When you declare an array final, you are declaring the array object reference itself final, not the elements the array contains. So while you cannot alter the array reference, you can still alter individual elements in the array.
To get the effect you want, you'll have to use Collections.unmodifiableList or something similar.
Consider these
final int a[]={11,2};
int b[]={};
a=b;// this will compile wrong
a[1]=1;//this will compile fine
Because if you are declaring final array then it means that the array reference can not be changed but you can obviously change the content
Arrays are supported, but it's no different for any other reference variables: you can change the state of the variable, but you can't change the object that the variable refers to, here the array object. For arrays, the state are the item references.
final int[] test = new int[3];
test = new int[2]; //Error here
(final applies to the reference, not the object data)
If you need an immutable data structure, List (you can use ArrayList if desired) is where you'll want to go. If you really need it to be an array, you'll need to create your own data structure with only getter methods.
final in Java affects the variable, it has nothing to do with the object you are assigning to it.
final String[] myArray = { "hi", "there" };
myArray = anotherArray; // Error, you can't do that. myArray is final
myArray[0] = "over"; // perfectly fine, final has nothing to do with it

Difference between Arrays and 3 dots (Varargs) in java

Need to figure out what is the difference between ... and arrays in JAVA, also an array list.
It seems we can use both as unlimited, but ... is rarely used.
Really appreciate any help you can.
The three dots can only be used in a method argument, and are called 'varargs'. It means you can pass in an array of parameters without explicitly creating the array.
private void method(String[] args) {} is called like method(new String[]{"first", "second"});
private void method(String... args) {} is called like method("first", "second");
An array is a fixed length collection of objects. e.g. new int[5];
An ArrayList is a variable length collection of objects. e.g. new ArrayList<Integer>();
The ... in variadic functions is a part of a method signature denoting an array of parameters. e.g. public void printLines(String... lines)
In other words, method(String...) means passing a variable number of parameters to the method.

Categories

Resources