What happens if you keep a method name same as the class name and the method has a return type?

Problem Set To ensure that you understand all the material in this lecture, please solve the the announced problems after you read the lecture.

If you get stumped on any problem, go back and read the relevant part of the lecture. If you still have questions, please get help from the Instructor, a CA, or any other student.

  1. Write a statement that calls any of the "result-returning" methods (maybe just display the returned result on the console) and hand simulate its execution with a call frame.

  2. Java allows methods to have no parameters; such methods are defined and called by specifying their name followed and an empty argument list: e.g., f(). Use your knowledge of the semantics of the return statement to explain what happens for the following method and its calls. Don't get confused by what you think it does (or want it to do): follow the rules. int f() { return 1; return 2; } What is displayed by System.out.print("1st f = " + f() + " 2nd f = " + f());

  3. Write a method named characteristic, which returns 1 if its parameter is true and 0 if its parameter is false.

  4. Write a method named abs, which returns the absolute value of its int parameter (it always returns the non-negative magnitude of its parameter; don't call the Math.abs method).

  5. Write a method named signum, which returns -1 if its double parameter is negative, 0 if its parameter is zero, and +1 if its parameter is positive.

  6. Write a method named constrain. Calling constrain(1,5,10) returns 5 because this middle value is between the first and third values. Calling constrain(1,-5,10) returns 1 because this middle value is smaller than the first value, so the method returns the first value. Calling constrain(1,15,10) returns 10 because this middle value is larger than the third value, so the method returns the third value. Thus, this method returns the middle value, but it is constrained to lie between the first and third values inclusize.

  7. Write a method named forChar. We could call the method as forChar("Enter an Upper-Case Letter", 'A', 'Z') which always returns a char whose ASCII value is between 'A' and 'Z'; or we could call the method as forChar("Enter a Digit", '0', '9') which always returns a char whose ASCII value is between '0' and '9'.

  8. Why can't we write a simple method named makeChange, which is supplied the amount of change to vend, and returns the number of quarters, dimes, nickels, and pennies needed to vend the required change. How do you think we can write a method to solve such a problem?

  9. Write a method named majority, which returns the most frequently occuring value of its three boolean parameters: no matter the values, at two of three (and possibly three of three) will have the same value. For example, the call majority(true,false,false) returns false, while the call majority(true,true,true) returns true.

  10. Write a method named median, which returns the middle value of its three arguments. For example, the call median(3,2,5) returns 3 because it is between 2 and 5.

  11. Assume that we declare char roman; and store in it a character that is a roman numeral. Write a method that returns the int equivalent of the Roman numeral: I is 1, V is 5, X is 10, L is 50, C is 100, D is 500, M is 1000; if it stores any other character, return -1.

  12. Write a method named isPrime, which returns whether or not its parameter is a prime number. A prime number has only 1 and itself as divisors: neither 0 nor 1 are considered prime; 2 is the smallest prime number, then 3, 5, 7, 11, etc. Hint: Use a for loop to check for possible divisors, along with the % operator.

  13. Write a method named harmonic, which takes one int parameter and returns a double value representing the harmonic series of that order. harmonic(n) is defined as 1 + 1/2 + 1/3 + ... 1/n. So harmonic(2) returns 1.5; and harmonic(4) returns 2.083333.

  14. Write a method named fw, which returns the number of characters needed to print its integer parameter. For example, fw(5) returns 1; fw(-5) returns 2; fw(453) returns 3; and fw(-243) returns 4. Hint: the number of digits in a number is related to how many times you can divide it by 10 and still have a non-zero value; treat negative numbers specially.

  15. Write a method named block that has an int height and width parameter, and a char parameter. This method returns a String which when printed displays a rectangle of that the specified height and width, consisting of the specified character. Calling System.out.println(block(5,20,'*')); would print. ******************** ******************** ******************** ******************** ******************** Remember that catenating an escape sequence character ('\n') in a String causes a carriage return when that character is printed.

  16. Suppose our program consists of the the methods main, a, b, c, d, and e. Also suppose main calls a, b, d, and e, a calls c, b calls a, c calls nothing else, d calls a, and e calls d and c.
    • Find two "natural orders" in which to write these methods in a file
    • Find two "reverse natural orders" in which to write these methods in a file

  17. For all the sample methods in this lecture, identify the ones in which it makes sense to throw IllegalArgumentExceptions and describe under what conditions. Note that sometimes individual parameters will store reasonable values, but pairs of parameters will have values that are incompatible.

  18. As we saw in this lecture, we can specify that a parameter variable is final. For example, we can rewrite factorial as public static int factorial (final int n) { int answer = 1; for (int i=2; i<=n; i++) answer *= i; return answer; } What does final mean when added before a parameter? Does the factorial method still work correctly if its parameter is specified final? If it didn't, would we find out at compile-time or at run-time? Which methods in this lecture can have their parameters(s) declared to be final? Which cannot? Can any of the local variables in these methods be declared final?

  19. Define a class with the following characteristics: its name is Utility and it is in the cs200 package. It contains two static methods, both named factorial: the first takes an int parameter and returns an int result; the second takes a BigInteger parameter and returns a BigInteger result. Important whatever classes are necessary to write the bodies of these methods successfully.

  20. Explain why when defining a class, we never need to write an import declaration for the Math class.

  21. I predict that half the students in class will make the following mistake when they write one of their first few constructors. Can you spot the mistake (compare it to the correctly written constructor in this lecture)? What actually happens if we write this code? Will Java detect/report the error? If so, with what message? If not, what will Java do when it executes this code? public SimpleDiceEnsemble () { int numberOfDice = 2; int sidesPerDie = 6; int rollCount = 0; } If we wrote each of these like this.numberOfDice, would it help?

  22. Explain how to simplify the following declarations and constructor. I have used the style of always writing this. to access instance variables. private int a; private int b; private int c; public C (int a) { this.a = a; this.b = 10; this.c = 0; }

  23. Examine the code for the SimpleDiceEnsemble class.
    • Assume that we decide to roll the dice automatically, at the time when the ensemble is constructed, to initialize them. How could we modify the constructor to perform this task? What changes (if any) could we make the method headers and bodies?
    • Assume that we want users of this class to be able to retrieve the minimum and maximum number of pips showing after each roll. What extra instance variables should we declare? What new methods should we write and what changes to old methods should we make?

  24. Write a class named RangeTally. Each instance of this class stores four fields: the lower legal value, the upper legal value, the sum of all the int values in this range that it is has seen (via the tally method), and the total number of values that has seen (whether they were in range or not). Its constructor should initialize these fields appropriately; its accessor, getTally, should return the sum of all values seen which were in range; its accessor, getCount, should return a count of all of values that it has seen (whether they were in range or not); its mutator, tally, is passed an int parameter that is conditionally tallied into the sum; it should change all fields as appropriate For example, if we declare RangeTally t = new RangeTally(1,10); and execute the statements t.tally(5); t.tally(8); t.tally(15); and then System.out.println(t.getTally()+":"+t.getCount()); Java prints 13:3 -the last value is counted, but not summed, because it is not in the range 1 to 10, specified in the constructor.

Can we have a method name same as class name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.

Can we have same method name with different return type?

No, you cannot overload a method based on different return type but same argument type and number in java. same name.

Can you have two methods with the same name?

Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading. Method overloading is achieved by either: changing the number of arguments.

When a method uses a class name as its return type?

When a method uses a class name as its return type, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.