2) How to create an Array?
An Array is declared similar to how a variable is declared, but you need to add [] after the type.
Example: int [] intArray;
We can declare Java array as a field, static field, a local variable, or parameter, like any other variable. An array is a collection of variables of that type. Here are a few more Java array declaration examples:
Same is the case for other programming languages.
10) Can we declare array size as a negative number?
No. We cannot declare the negative integer as an array size.
If we declare, there will be no compile-time error.
However, we will get NegativeArraySizeException at run time.
24) Can we use Generics with the array?
No, we cannot use Generic with an array.
28) “int a[] = new int[3]{1, 2, 3}” – This a legal way of defining the arrays?
No. We should not declare the size of the array when we are providing the array elements.
6) What is the default value of Array?
Any new Array is always initialized with a default value as follows
8) How to compare Two Arrays?
If 2 arrays are of the sam size & data type then comparison can be done using “Arrays.equal ()”
7) How to print element of Array?
Here is code to print element of the array.
Output is: [25, 30, 50, 10, 5]
40) How to do the intersection of two sorted arrays?
Ans: Logic: print the element if the element is present or available in both the arrays.
32) What will be the output of below code?
Ans: Output will be Garbage value.
myArr is an array variable, myArr is pointing to an array if it is integers.
Printing myArr will print garbage value. It is not same as printing myArr[0].
4) Can we change the size of an array at run time?
No we cannot change the array size. Though there are similar data types available which allow a change in size.
37) How to find the duplicate in an array?
Here is a String[] with values
If myNames contains that value then it will return true otherwise false.
Here is two methods isExists() and contains()
both the methods return true if the value is available otherwise false.
First Method
It is converting an array to ArrayList.
After that it will test if an array contains any value then it will return true otherwise false.
Second Method
This method loop through an array and use equal() method to search element.
This actually performs a linear search over an array in Java. It will return true if an array has provided value.
16) int a[] = new int[3]{1, 2, 3} – is it a right way to declare arrays in java?
No. We should not mention the size of the array when we are providing the array elements.
5) Can you declare an array without assigning the size of an array?
No we cannot declare an array without assigning size.
If we declare an array without size, it will throw compile time error
Example: marks = new int []; //COMPILER ERROR