Define a class to overload the method print() as follows: void print() - To print the given format using nested loops. @#@#@ @#@#@ @#@#@ @#@#@ @#@#@ double print(double a, double b) - To display the sum of numbers between a and b with difference of 0.5. e.g. if a = 1.0, b = 4.0 output is: 1.0 + 1.5 + 2.0 + 2.5 + .......... + 4.0 int print(char ch1, char ch2) - compare the two characters and return the ASCII code of the largest character.
Topic: Method overloading — three versions of print()
Answer
class Overload { void print() { for(int i = 1; i <= 5; i++) { for(int j = 1; j <= 5; j++) { if(j % 2 == 1) System.out.print("@"); else System.out.print("#"); } System.out.println(); } }
double print(double a, double b) { double sum = 0.0; for(double i = a; i <= b; i += 0.5) sum = sum + i; return sum; }
int print(char ch1, char ch2) { if(ch1 > ch2) return (int)ch1; else return (int)ch2; }
public static void main(String args[]) { Overload ob = new Overload(); ob.print(); System.out.println("Sum = " + ob.print(1.0, 4.0)); System.out.println("ASCII of larger character = " + ob.print('A', 'k')); } }
Three methods share the name print() but differ in their parameter lists — that is method overloading, and the compiler picks the right one from the arguments you pass.
First method (the pattern): five rows of five characters, so nested loops with the outer controlling rows and the inner controlling columns. The character alternates by COLUMN, not by row — every line reads the same @#@#@ — so the test is on j: odd column prints @, even prints #. System.out.println() at the end of the inner loop moves to the next row.
Second method: a for loop can use a double counter. Starting at a and stepping by 0.5 until b, adding each value. For 1.0 to 4.0 the terms are 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, giving 17.5.
Third method: characters compare directly with > because Java promotes each to its ASCII value. The cast (int) makes the returned code explicit. For 'A' (65) and 'k' (107) the answer is 107.
Remember that overloading is decided by the parameter list only — the differing return types here (void, double, int) neither help nor hinder.
ob Overload - object of the class, used to invoke the methods i, j int - loop variables for the rows and columns of the pattern a, b double - the limits of the range to be summed sum double - running total of the numbers in the range ch1, ch2 char - the two characters to be compared