Jump to content

Help with Java classes

Here is the code: 

 

 

public class Test{

public static void main(String [] arguments){
System.out.println(max(1.0, 2));
}

public static double max(int num1, double num2){
System.out.println("max(int, double) is invoked");

if(num1 > num 2){
return num1;
}else{
return num 2;
}


public static double max(double num1, int num2){
System.out.println("max(double, int) is invoked");

if(num1 > num 2){
return num1;
}else{
return num 2;
}


I was confused as to what is going on because I haven't worked with methods other than main.

Here are my answers for this question:

 

 

 

A. The program cannot compile because you cannot have the print statement in a non-void method.

B. The program cannot compile because the compiler cannot determine which max method should be invoked.

C. The program runs and prints "max(int , double)" followed by 2.0

D. The program runs and prints "max(double, int)" followed by 2.0

E. The program runs and prints "max(int, double) is invoked" followed by a 2.0

 

 

 

I don't even understand what is happening in the code, please help because I am eager to learn. This isn't just to get an answer.

EDIT: I am not allowed to use an IDE

Link to comment
Share on other sites

Link to post
Share on other sites

-Snip-

It will run and print

 

max(double, int) is invoked

2

 

What it is doing is printing the value that max is returning which in this case is 2.

 

(This what's called Object oriented programming)

There are two "max's" because even though they have the same name the order of the arguments are different, so they are different methods and therefore the program decides based on the values you pass to it which one is the correct one to use. (Note: No arguments is called a default constructor and runs if nothing else will. You can also makes the same named method ad say have 3 arguments in it.)

 

*Also, you can have the print and it will work BTW. Hope this helps some.

"Her tsundere ratio is 8:2. So don't think you could see her dere side so easily."


Planing to make you debut here on the forums? Read Me First!


unofficial LTT Anime Club Heaven Society

Link to comment
Share on other sites

Link to post
Share on other sites

If you have been given a question that has an overload in it you should already know what methods are and how to use them. Getting told the answer/pointed in the right direction wont give you a full understanding of what's happening. Also, learning about methods wont take long; here's a video - 

.
Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×