Skip to Main Content

Array

871234May 22 2015 — edited May 22 2015

Hi Java Experts,

I am preparing to attend a basic java test, the examiner given provided sample questions and answers to practice the test, one of them is

1. Write a function that accepts an array of non-negative integers and returns the second largest integer in the array. Return -1 if there is no second largest.

The signature of the function is

int f(int[ ] a)


Examples:

if the input array isreturn
{1, 2, 3, 4}3
{{4, 1, 2, 3}}3
{1, 1, 2, 2}1
{1, 1}-1
{1}-1
{}-1

In the signature what I understood is, I should write my function with the given signature,

the return type is "int"

method name is "f"

parameter is "a" right ?

Could anybody help me to understand the answer for further insights ? writing my doubts beside the particular line in the code

public static void main()  // In the answer why they didn't use the class ? In main method why they didn't use parameters ?(String[] args)

{

a1(new int[]{1, 2, 3, 4}); // what is "a1" here is it array name ? this line initializing the array ?

a1(new int[]{4, 1, 2, 3});

a1(new int[]{1, 1, 2, 2});

a1(new int[]{1, 1});

a1(new int[]{1});

a1(new int[]{});

static int a1(int[] a) // what is "a" here parameter ? and "a1" is method name ? why they used the array name and method name same ?

{

int max1 = -1;

int max2 = -1;

for (int i=0; i<a.length; i++)

{

if (a[i] > max1)

{

max2 = max1; max1 = a[i];

}

else if (a[i] != max1 && a[i] > max2)

max2 = a[i];

}

  return max2;

}

Please help me,

Thanks.

Comments
Post Details
Added on May 22 2015
4 comments
912 views