Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

calling a static method from main?

 
Sam Cooper
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had come across this in a mock exam.
public class Test{
public static void main(String[] args){
int[] a = {1};
Test t = new Test();
t.increment(a);
System.out.println(a[a.length - 1]);
}
void increment(int[] i){
i[i.length - 1]++;
}
}
My initial guess is that you can call a non static method from a static (main), so this should result in a compile tim error. But the answer that was given to be
Complies and runs printing out 2.
Could some on please let me know whats going on here
SAM
 
Sam Cooper
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I MEAN
My initial guess is that you CANNOT call a non static method from a static (main), so this should result in a compile time error. But the answer that was given to be
Complies and runs printing out 2.
Could some on please let me know whats going on here
SAM
 
Holmes Wong
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sam Cooper:
I had come across this in a mock exam.
public class Test{
public static void main(String[] args){
int[] a = {1};
Test t = new Test();
t.increment(a);
System.out.println(a[a.length - 1]);
}
void increment(int[] i){
i[i.length - 1]++;
}
}
My initial guess is that you can call a non static method from a static (main), so this should result in a compile tim error. But the answer that was given to be
Complies and runs printing out 2.
Could some on please let me know whats going on here
SAM


Here is the rule: you cannot call a non-static method from a static method, but you can use a reference to call a non-static method. Say, if you do:
increment(a); //illegal
Test t = new Test();
t.increment(a); //legal
 
Sam Cooper
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Holmes:
Makes sense, Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic