-1
import java.util.Scanner;

public class Info {

    
    public static void main(String[] args){

        Scanner input = new Scanner(System.in); 
        int n1,n2;
        
        System.out.print("Enter n1: ");
        n1 = input.nextInt();
        
        System.out.print("Enter n2: ");
        n2 = input.nextInt();
        
        System.out.println(sumTotal(n1,n2));
        
    }
    
    public static int sumTotal(int n1sum, int n2sum) { // *why static includes here*
        return n1sum+n2sum;
        
    }
}

I don't understand why do I need to put static in here?

Some other codes with return statement doesn't need static, like this one. So why?

public class FirstProgram {

    public static void main(String[] args)
    {   
        Scanner userInput = new Scanner(System.in); // for scanning
    
        int age;
        
        System.out.println("Enter your age");
        age = userInput.nextInt(); 

        var a = new FirstProgram(); 
        a.userAge(age); 
                        
    }
    
    public int userAge(int age1) 
    {                            
        if ( age1 < 18 )                                          
        {
            System.out.println("You are a YOUNG!");
        }
        
        else if (age1 > 18 && age1 <=25)
        {
            System.out.println("Young adult! ");
        }

        else
        {
            System.out.println("Wise!");

        }
        return age1;    
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Elly
  • 15
  • 7

1 Answers1

1

I don't understand why do I need to put static in here.

Java does not allow calling non-static method from a static method directly.

Some other codes with return statement doesn't need static, like this one. so whyy?

This is how (i.e. using the instance of the class) Java allows you to call a non-static method from a static method.

Learn more about static keyword here.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110