click below
click below
Normal Size Small Size show me how
Quiz 1
Java
| Question | Answer |
|---|---|
| What is the output of this code sequence: double [] a = {12.5, 48.3, 65.0}; System.out.println(a[1]); | 48.3 |
| What is the output of this code sequence: int [] a {12, 48, 65}; for (int i = 0; i < a.length; i++) { System.out.println(“a[“ +i+ “]=“ + a[i])}; } | < \n > a[0] = 12 < \n > a[1] = 48 < \n > a[2] = 65 |
| What does this method do? public static int foo(String [] a) { int b = 0; for (int i = 0; i < a.length; i++) { b++; } return b; } | This method, named foo, returns an integer for the number of elements in an array. For example, if I have an array: “ String [] a = new String [5]; ” When I call this method, then the output will be “5”. |
| You coded the following on line 26 of a program called Test.java: int a [6] = {2, 7, 8, 9, 11, 16}; // line 26 However, when you compile, you receive syntax errors. Why? Explain. | This is a syntax error because the programmer improperly declared an array by using an integer within the bracket while initializing the array, for example, int [6] = {2, 7, 8, 9, 11, 16};. Line 26 should read: int [ ] = {2, 7, 8, 9, 11, 16}; |
| public static int foo(String [][] a) { int b = 0; for (int i =0; i < a.length; i++) { b++; } return b; } | This method counts the number of rows in a 2D array (or multi-dimensional array). |
| Declare a 2D integer array with (3) rows and (4) columns. | int [][] array = new int [3][4]; |
| Declare a 2D ragged integer array named “myArray” with (4) rows. Store “10” and “20” in the first row, and store “25” “60” and “5” in the second row of myArray. | int [][] myArray = { {1, 2, 3, 4}, {10, 20}, {25, 60, 5}, {4} }; |
| In pseudocode, get the number of rows in “myArray” and get the size of each row: int [][] myArray = { {1, 2, 3, 4}, {10, 20}, {25, 60, 5}, {4} }; | PRINT “myArray.length” \nPRINT “myArray[0].length” \nPRINT “myArray[1].length” \nPRINT “myArray[2].length” \nPRINT “myArray[3].length” |
| Write java code for printing a 2D array. Assume any number of rows and columns. |