static and main methods


Premium Content - Free Preview

Most methods in ordinary programs are instance methods, which are invoked on a specific instance of an Object. For example, in Code and Methods, we saw a method 'getStudentID()' to get a Student's ID, and in the previous project, we had methods like 'getContent()' that were called on specific Notes. However, there's also another type of method known as static methods (or class methods).

static methods

A static method cannot deal with the Object's instance variables, it can only deal with the parameters that it is passed (and with static variables). Some methods do not need to access instance variables, so they can be declared as static. For example, the challenge in Methods and Parameters was to create a method that returned the average of two integers. Since the average depends only on the two integer parameters, regardless of any other data, it makes sense to declare this method static.

A static method is declared with the keyword static. For example, this is a method that returns an average:

public static int average(int a, int b){
    return (a+b) / 2;
}

A static method of a class can be invoked from within that class just like any other method is. Static methods don't have extra powers, but it helps to declare them static to make your code clearer (and slightly faster). These methods can also be used by code outside of their class without requiring an instance of the class to be created. This is done by invoking the method on the class name instead of an Object name: ClassName.staticMethod();

If the average method was in a class called Numbers, we could call it inside that class as usual:

int average = average(4, 8);

And outside the Class, with the Class name:

int avg = Numbers.average(4, 8);

main

Q: You've ignored an important part in all of the code so far. Where does the code start from? In BlueJ, you can manually create Objects and invoke their methods, but what about programs in the real world (or on this website)?


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

  • A user asked why doesn't this code work? It just prints out 7.

    public static void main(String[] arguments) {
        Scanner sc = new Scanner(System.in);
        int sum = doStuff(sc.nextInt(), sc.nextInt());
        System.out.println(sum);
    }
    
  • Look at the input format carefully: "The first line of input will contain the number of test cases t. t lines will follow, with each line containing the 2 numbers to be summed." You need to first get the number of lines, and then call doStuff that number of times with the remaining input.

  • My code its like this and it just prints out 7. why input is 5 2 3?
    public static int doStuff(int a, int b){
    int sum=0;
    sum=a+b;
    return sum;

    cont...
Contact Us
Sign in or email us at [email protected]