Hello, I'm a beginner at learning Java.
I made a method called "adder" I want to return the value of a+b, but there is a red line error in intc=adder. Why is this? What's the problem?
public class add {
public int adder(int a,int b){
return a+b;
}
public static void main(String[] args){
int c= adder(10,20);
}
}
If you look at the Java book, it will come out well about static.
The answer is that only static can be called in the static method.
The questioner called the instance method, add in the static method, so it should not. The instance method must be created with the new keyword and can only be invoked through that instance.
Please take a closer look at this when you gain experience in Java in the future, and make sure to learn the process of executing byte code in jvm.
public class add {
public int adder(int a,int b){
return a+b;
}
public static void main(String[] args){
add temp = new add();
int c= temp.adder(10,20);
}
}
© 2024 OneMinuteCode. All rights reserved.