Array as parameters

Hope you already gone thru basic of arrays.
An array can be sent as parameter to a constructor or a method. Also an array can be returned by a method.
Below example shows the same.


class Student{
	int marks[];
	
	Student(int m[])
	{
		marks = m;
	}
	
	private int getTotal(){
		int sum = 0;
		for(int i=0;i

Below is an example showing a method returning an array.

public class StudentProgram {
	public static void main(String arg[])
	{
		int gmp[] = getArray();
		
		for(int item:gmp)
		{
			System.out.println(item);
		}
	}
	
	
	private static int[] getArray()
	{
		int smp[] = {45,64,53,26};
		
		return smp;
	}
}

You may also like to read:
array example
how to sort an array in java

Array example in Java

Hope you had already gone thru Arrays in Java to get basic understanding of arrays.

Now, let us solve a simple problem using Arrays.
Arrays Problem: Write a class which has Constructor, taking marks of students as parameters. Expose methods to return max marks, min marks, avg marks, number of students scored more than 60, number of students scored less than 60.

class Student{
	private int marks[];
	
	public Student(int marks[])
	{
		this.marks=marks;
	}
	
	public int getMaxMarks()
	{
		int max = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] > max)
			{
				max = marks[i];
			}
		}
		
		return max;
	}
	
	public int getMinMarks()
	{
		int min = 999;
		
		for(int i=0;i < marks.length;i++)
		{
			if(marks[i] < min)
			{
				min = marks[i];
			}
		}
		
		return min;		
	}
	
	public int getAverageMarks()
	{
		int avg = 0;
		
		for(int i=0;i < marks.length;i++)
		{
			avg+=marks[i];
		}
		
		avg /= marks.length;
		
		return avg;
	}
}

public class Cond{
public static void main(String args[])
{
	int st_marks[] = {36,94,83,42,35,86,65,91};
	
	Student obj = new Student(st_marks);
	
	System.out.println("Max Marks:"+obj.getMaxMarks());
	
	System.out.println("Min Marks:"+obj.getMinMarks());
	
	System.out.println("Avg Marks:"+obj.getAverageMarks());
}
}

Note: Finding number of students scored less than 60 and more than 60 is left out, for you to work on.

Hint: To get number of students less than 60, use for loop, and in each iteration increment counter, if the mark of a student is less than 60, and return the counter value. Similarly find number of students scored greater than 60.

You may also like to read:
How to write a class in Java
Loops examples
What is purpose of Constructor