static and main methods
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)?
A: All Java programs start executing from the main method. Somewhere in the code, there needs to be a method with the following header, the syntax for the main method:
public static void main(String[] args){
//code to start things up!
}
Q: That's quite a header. What does it mean?
A: You don't need to worry about it much, and IDE's will often create it for you. But the method is public
so it can be called from outside the class, static
since no Object exists yet, and void
since it can't return anything. It's called main
because it needs to be called something specific. The parameters are for optional command line arguments, but you can ignore that for now.
example code
The following is some simple code for a Car Object that demonstrates the use of regular, static, and main
methods. In real programs the main method usually contains just enough code to start the program, but it can also be used to test things out.
public class Car {
private int speed; //miles per hour
public Car() {
speed = 0;
}
//regular methods
public void accelerate(int amount) {
speed = speed + amount;
}
public int getSpeed() {
return speed;
}
//static method
public static double estimatedTimeArrival(double steadySpeed, double miles){
return miles / steadySpeed;
}
//main method - the code will start executing from here
public static void main(String[] args) {
Car car1 = new Car();
car1.accelerate(10);
int speed = car1.getSpeed();
double hours = estimatedTimeArrival(speed, 30);
System.out.println("At our current rate, we'll arrive in " + hours + " hours.");
}
}
This code will output the following:
At our current rate, we'll arrive in 3.0 hours.
Since the above code was within the same class as estimatedTimeArrival
, it was able to invoke it directly. Code in other classes would have used the following code:
double hours = Car.estimatedTimeArrival(speed, 30);
On Learneroo
Many of the challenges on Learneroo involve simple methods that return a value. Therefore these methods are often static
so that no new Object needs to be created to invoke them. The code starts from an included main
method which usually Scans in input from a Scanner. You now understand all of the code needed to solve these challenges from scratch!
Challenge
Create a program that returns the sum of two integers. You need to create a main method and a Scanner to get the input as integers. You can refer back to the original challenge, but make sure you understand all the code that is used!
Input Format
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.
Output Format
Print each sum on its own line. (You can view sample Input/Output by clicking on "Raw I/O" below.)
Challenge
Create a program that scans in two integers and returns their sum.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Learneroo
Nov 5, 8:11 PMA user asked why doesn't this code work? It just prints out 7.
Learneroo
Nov 5, 8:12 PMLook 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.
Kami
Mar 8, 4:04 AMMy 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;