Reputation: 503
public class launcher{
public static void main(String[] args){
javax.swing.JOptionPane.showMessageDialog(null,"HelloWorld");
}
}
public class launcher{
public static void main(String[] args){
System.out.println("HelloWorld");
}
}
public class launcher{
public static void main(String[] args){
int a = java.util.Random.nextInt(10);
}
}
import java.util.Random;
public class launcher{
public static void main(String[] args){
Random rr = new Random();
int num = rr.nextInt(10);
}
}
Code1 and Code2 work well without "import java.swing.JOptionPane" or "import System.out.println"
But, Code3 doesn't work well.
Should I use like Code4?
Upvotes: 0
Views: 186
Reputation: 10955
Your problem in "Code3" doesn't have anything to do with importing Random
or using its fully qualified name.
Your problem is that nextInt()
is not a static method. "Code4" works because you create an instance of Random
and run the nextInt()
method on it, not because you've imported the class.
All that importing a class really does is save you from having to write out the package every time you want to use it. It doesn't change the way you can invoke methods on that class.
"Code3" would work if you re-wrote it like this:
public class launcher{
public static void main(String[] args){
java.util.Random rr = new java.util.Random();
int a = rr.nextInt(10);
}
}
Upvotes: 6