wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes calling a static method from main? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "calling a static method from main?" Watch "calling a static method from main?" New topic
Author

calling a static method from main?

Sam Cooper
Greenhorn

Joined: Feb 21, 2002
Posts: 14
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

Joined: Feb 21, 2002
Posts: 14
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

Joined: Feb 18, 2002
Posts: 163
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

Joined: Feb 21, 2002
Posts: 14
Holmes:
Makes sense, Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: calling a static method from main?
 
Similar Threads
Array Vs VarArgs
Formal and Actual parameter.
right & left shifts
Why varags method called first
Overloading Ambiguously