First, let's start simple. All methods that are not constructors require a return type. In other words,
public void number(){
i = 1;
}
would be more proper.
Second: the main
method traditionally has a signature of public static void main(String[] args)
.
Now, on to your question at hand. Let's consider a few cases. I will be breaking a few common coding conventions to get my point across.
Case 1
public void number(){
i = 1;
}
As your code stands now, you will have a compile-time error because i
is not ever declared. You could solve this by declaring this somewhere in the class. To access this variable, you will need an object of type Main
, which would make your class look like this:
public class Main {
int i;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
i = 1;
}
}
Case 2
Let's say you don't want to make i
a class variable. You just want it to be a value returned by the function. Your code would then look like this:
public class Main {
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
}
public int number(){ //the int here means we are returning an int
i = 1;
return i;
}
}
Case 3
Both of the previous cases will print out 1
as their output. But let's try something different.
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
myMain.number();
System.out.print(myMain.i);
}
public void number(){
int i = 1;
}
}
What do you think the output would be in this case? It's not 1
! In this case, our output is 0
. Why?
The statement int i = 1;
in number()
, it creates a new variable, also referred to as i
, in the scope of number()
. As soon as number()
finishes, that variable is wiped out. The original i
, declared right under public class Main
has not changed. Thus, when we print out myMain.i
, its value is 0.
Case 4
One more case, just for fun:
public class Main {
int i = 0;
public static void main(String[] args) {
Main myMain = new Main();
System.out.print(myMain.number());
System.out.print(myMain.i);
}
public int number(){
int i = 1;
return i;
}
}
What will the output of this be? It's 10
. Why you ask? Because the i
returned by number()
is the i
in the scope of number()
and has a value of 1. myMain
's i
, however, remains unchanged as in Case 3.