Fusionist Fusionist - 4 months ago 9
Java Question

Static method error in java

I was just doing a normal java program using methods with parameters to add 2 numbers.

This was my code

class Hello {

public void addition(int m,int n){
System.out.println(m+n);
}


public static void main (String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter the two integers to be added");

int c,d;

c= in.nextInt();
d= in.nextInt();

addition(c,d);

in.close();


}
}


So this code gave me error and eclipse recommended me to make my method static and then the code worked.I knew static method are only initialized only once and is used when we use inheritance and multiple classes.

My question is why do i need to make my method static in this case ?
The same format code works in c++.Why not in java ?

Answer

The same format code works in c++.Why not in java ? well, just because java and C++ are totally different languages...

In java uou just can't call the instance method from an static content...

make the method static too or create an instance of the class and use it

example:

public static void addition(int m, int n) {
    System.out.println(m + n);
}

or even better:

public   void addition(int m, int n) {
System.out.println(m + n);
}

public static void main(String[] args) {
Hello  h = new Hello():
Scanner in = new Scanner(System.in);
System.out.println("Enter the two integers to be added");
int c, d;
c = in.nextInt();
d = in.nextInt();
h.addition(c, d);
in.close();
}
Comments