Knowee
Questions
Features
Study Tools

What's the output of the following code?public static void main(String[] args) { int[] vals = {4, 3, 2, 1}; for (int v : vals) { System.out.println(indexOf(vals, v)); }}public static int indexOf(int[] all, int element) { for (int i = 0; i < all.length; i++) { if (all[i] == element) return i; } return -1;}

Question

What's the output of the following code?public static void main(String[] args) { int[] vals = {4, 3, 2, 1}; for (int v : vals) { System.out.println(indexOf(vals, v)); }}public static int indexOf(int[] all, int element) { for (int i = 0; i < all.length; i++) { if (all[i] == element) return i; } return -1;}

🧐 Not the exact question you are looking for?Go ask a question

Solution

The output of the code will be:

0 1 2 3

Explanation:

The main method initializes an array of integers, vals, with the elements 4, 3, 2, 1. It then iterates over each element in the array, calling the indexOf method with the array and the current element as arguments.

The indexOf method takes an array and an element as arguments. It iterates over the array, and if it finds the element in the array, it returns the index of the element. If it doesn't find the element, it returns -1.

In this case, the elements 4, 3, 2, 1 are all in the array at indices 0, 1, 2, 3 respectively. So, the output of the code is the indices of these elements, which are 0, 1, 2, 3.

This problem has been solved

Similar Questions

What is output of the following code: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] + " "); }

What does the following piece of code do?for (int i = 0; i < arr.length-1; i++){ for (int j = i+1; j < arr.length; j++) { if( (arr[i].equals(arr[j])) && (i != j) ) { System.out.println(arr[i]); } }}

What is the output of the following Java code:Code:class hacker{ public static void main(String[] arg) { int[] a = { 128, 132, 98, 116, 100 }; int x = func(a); System.out.println(x); } public static int func(int[] no) { int b = no[0]; for (int i: no) { if (i > b) b = i; } return b; }}

What is the output of the following program?  public class Test {   public static void main(String[] args) {     int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};      for (int row = 0; row < values.length; row++) {       System.out.print(myMethod(values[row]) + " ");     }   }    public static int myMethod (int[] list) {     int v = list[0];     for (int i = 1; i < list.length; i++)       if (v < list[i])         v = list[i];     return v;   } } Group of answer choices3 331 15 65 3333 5

What is the output of the following code :class MyClass {public static void main(String[] args) {int i=1,j=1;for (;i<3;i++){for(;j<4;j++);j++;System.out.print(i + j+" ");}}

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.