Ask Your Question
0

Can I add a default Parameter for a Method in Java like int calculate(int x, int y=2)?

asked 2023-04-06 15:08:35 +0000

qstack gravatar image

updated 2023-04-06 16:19:53 +0000

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-04-06 15:09:06 +0000

qstack gravatar image

In Java, you cannot define default parameter values for method parameters like you can in some other programming languages. However, there are a few different approaches you can take to achieve similar functionality.

One approach is to overload the method. For example, you could define two versions of the calculate() method, one with one parameter and one with two parameters:

public int calculate(int x) {
    return calculate(x, 2);
}

public int calculate(int x, int y) {
    // your calculation logic here
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

1 follower

Stats

Asked: 2023-04-06 15:08:35 +0000

Seen: 28 times

Last updated: Apr 06 '23