0

I am intermediate Python programmer now learning Java. I'm trying to learn the basics but I keep getting the error:

java: cannot find symbol
  symbol:   method SumOfTwoNumbers(int,int)
  location: class Main

Here's my code

public class Main {

    public static void main(String[] args) {
        SumOfTwoNumbers c = new SumOfTwoNumbers(3, 2);
    }

}
public class SumOfTwoNumbers {
    public static int sum(int a, int b) {
        return a + b;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
coderoftheday
  • 1,987
  • 4
  • 7
  • 21

2 Answers2

2

You're creating a class named SumOfTwoNumbers with a static method named sum that returns an integer, so you must do

final int result = SumOfTwoNumbers.sum(3, 2);

If you want to create an instance, you need to change your SumOfTwoNumbers class:

public class SumOfTwoNumbers {
    // Remove the `static` keyword here
    public int sum(int a, int b) {
        return a + b;
    }
}

Then call it like this:

SumOfTwoNumbers c = new SumOfTwoNumbers();
final int result = c.sum(3, 2);
enzo
  • 9,861
  • 3
  • 15
  • 38
  • whats the keyword 'final' for and why has 'static' been removed – coderoftheday Jul 31 '21 at 03:14
  • 1
    `final` keyword makes sure that the variable cannot be modified. `static` keyword ensures that the `static` method is compiled and stored in the memory before the main program is run, which wasn't required in this case. If you don't know what those keywords do, it's often better not to fiddle with them until it's required to do so. – tsamridh86 Jul 31 '21 at 03:16
  • 1
    @SamridhTuladhar `static` means what the method can be called directly without having an object required to run "on" (keyword `this`). When the method does not have any reference to `this` (explicit or indirectly), you can make this method `static`. It has nothing to do with on how and when the method is compiled and stored in memory. – Progman Aug 21 '21 at 09:56
0

You create a SumOfTwoNumbers class and put as inputs to the constructor (2,3), but you don't actually have a constructor in your code, you have a method. If you want the program to run the sum when calling the class, you would have to do something like this.

public class SumOfTwoNumbers {
    public SumOfTwoNumbers(int a, int b) {
        System.out.println(a+b);
    }

}

What I think you want to do is call it separately, so you can just do this. Keep in mind you need to remove the static in the method signature for this to work.

int sum = new SumOfTwoNumbers().sum(1,2);
Alex Mehta
  • 64
  • 1
  • 9