In java an array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
Array -Java Programming MCQ Questions and Answers
Learn competitive java programming mcq questions and answers on Array with easy and logical explanations. Page-4 section-1
The syntax for declaring and creating an array variable in java is:
dataType[] arrayRefVar = new dataType[arraySize];
Thus, option (A) and option (C) is syntactically wrong as parentheses( ( ) ) is used instead of square brackets( [ ] ).
Option (D) is incorrect as the size of the array is missing.
public class Test{
public static void main(String[] args){
int[] a = new int[0];
System.out.print(a.length);
}
} Declare a public class named
Test.Step 2:
Define the
main method with the public and static modifiers and a parameter of type String array named args.Step 3:
Declare an array variable
a of type int[].Step 4:
Initialize the array
a with a size of 0 using the new keyword.Step 5:
Print the length of the array
a using the length property.Therefore, when you compile and run the code, the output will be:
0This output corresponds to the length of the array
a, which is 0.
public class Test{
public static void main(String[] args){
int[] x = new int[3];
System.out.println("x[0] is " + x[0]);
}
} Program is syntactically correct, so no error.
In java, if the array is not initialized at the time of declaration and creation then all the elements of the array are initialized to 0 by default.
public class Test{
public static void main(String args[]){
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for(int i = 1; i < myList.length; i++){
if(myList[i] > max){
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
}
} Line 7 : if(myList[i] > max) execute only on time when i =1;
when i = 1 then myList[i] = 5 and max = 1(so the statement is true and if block will be executed).
Then, max = myList[i] = 5 and indexOfMax = i = 1.
After that if statement always false. so indexOfMax value remain 1.
Therefore the value of indexOfMax is 1 at end of the for loop.
public class Test{
public static void main(String[] args){
int[] x = {120, 200, 016 };
for(int i = 0; i < x.length; i++)
System.out.print(x[i] + " ");
}
} 016 is an octal number. The prefix 0 indicates that a number is in octal.
public class Test{
public static void main(String[] args){
int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for(int i = 0; i < x.length; i++)
System.out.print(y[i] + " ");
}
} int[] arr = new int[5];
arr = new int[6]; public class Test{
public static void main(String[] args){
int[] a = new int[4];
a[1] = 1;
a = new int[2];
System.out.println("a[1] is " + a[1]);
}
} After executing the statement a = new int[2], a refers to int[2]. The default value for a[0] and a[1] is 0.