Java complete the main method what is the print of the main method? Explain. pub
ID: 3938961 • Letter: J
Question
Java
complete the main method
what is the print of the main method? Explain.
public class Number
{
private int m = 0;
public void setNumber(int newM)
{
m = newM;
}
public int getNumber()
{
return m;
}
public static int increment(int x)
{
x = x+1;
}
public static int increment(int[] x)
{
for (int i =0; i< x.length;i++)
{
x[i]++;
}
}
public static void main(String[] args)
{
int[] ages = new int[20]
// initialize the ages with random numbers between 17 and 20
for (int i = 0; i < 20; i++)
{
ages [i] = 17 + (int)(Math.random() *20)
}
// invoke the static increment method with parameter ages
// invoke the static increment method with parameter ages[3]
// printout ages[3]
}
Explanation / Answer
public class Number
{
private int m = 0;
public void setNumber(int newM)
{
m = newM;
}
public int getNumber()
{
return m;
}
public static void increment(int x)
{
x = x+1;
}
public static void increment(int[] x)
{
for (int i =0; i< x.length;i++)
{
x[i]++;
}
}
public static void main(String[] args)
{
int[] ages = new int[20];
// initialize the ages with random numbers between 17 and 20
for (int i = 0; i < 20; i++)
{
ages [i] = 17 + (int)(Math.random() *20);
}
System.out.println("printing ages before any increase: ");
for(int i=0; i<20; i++)
System.out.print(ages[i]+" ");
System.out.println();
// invoke the static increment method with parameter ages
increment(ages);
// printing after incrementing all age
System.out.println(" After increasing all ages: ");
for(int i=0; i<20; i++)
System.out.print(ages[i]+" ");
System.out.println();
// invoke the static increment method with parameter ages[3]
increment(ages[3]);
// printout ages[3]
System.out.println(" After calling increase ages[3]: ");
System.out.println(ages[3]);
}
}
/*
Sample run:
printing ages before any increase:
30 31 20 25 19 24 34 28 29 18 35 19 26 30 30 20 25 35 26 30
After increasing all ages:
31 32 21 26 20 25 35 29 30 19 36 20 27 31 31 21 26 36 27 31
After calling increase ages[3]:
26
In first increase call: increase(ages[]) : the reference of ages array is passed to method, so if we
change in any object of ages[] array, if can be also notified in main method
But in call: increase(age) : value of age[3] is passed, so any change in increase method does not
reflect outside the increase method
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.