Search code examples
javaparametersreturn-valuestatic-methodsnon-static

I have 2 examples of static and non static calling. Is my understanding of the operation correct?


So how I am understanding static and non static calling:

If you are calling methods, passing values and returning values without creating a new object of the Class, use static.

If you are calling methods, passing values and returning values after creating a new object of the class, don't use static.

I created two snippets of code. One is commented out but you will see in the class AreaCalculator, that the static reference coincides with the commented out methods being called in the main file.

My question on top of this in what instance would it be beneficial to be calling static or non static? If I created a bunch of non static types and primitives, then I would be able to utilize them under new objects without affecting the original value of those initializations in the class right?

The opposite would be if they were static variables, the values would be modified in the class(Since no object exists) when manipulating the data when work is performed setting them?

Code Below:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    //-----------------------------------------
    //Runs a For loop to get input, store in array, display results
    //ForLoopInputArray.looping();
    //-----------------------------------------


    //-----------------------------------------

    //Learning to return values when passing parameters
    // Area/Perimeter Calculator Methods

    Scanner apinput = new Scanner (System.in);
    AreaCalculator areatest = new AreaCalculator();

    //Using a static method
    //System.out.println("Enter a number to calculate the area: ");
    //System.out.println(AreaCalculator.area(apinput.nextDouble()));
    //System.out.println("Enter a number to calculate the Perimeter: ");
    //System.out.println(AreaCalculator.perimeter(apinput.nextDouble()));

    //using an object to perform the same task
    System.out.println("Enter a number to calculate the area: ");
    System.out.println(areatest.area(apinput.nextDouble()));
    System.out.println("Enter a number to calculate the Perimeter: ");
    System.out.println(areatest.perimeter(apinput.nextDouble()));

    //-----------------------------------------


}

}


public class AreaCalculator {

 /*static*/ double area (double areainput) {
    return Math.PI * (Math.pow(areainput, 2));

}

 /*static*/ double perimeter (double perimeterinput) {
    return Math.PI * (perimeterinput * 2);
} 

}


Solution

  • Non static methods are the ones that you call over an instance, for example, when you create a new AreaCalculator(). Static methods are the ones that you can invoke without having any reference of AreaCalculator(). This could help you a little bit more: What is the difference between a static method and a non-static method?