wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Legal java program? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Legal java program?" Watch "Legal java program?" New topic
Author

Legal java program?

Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi all,
Is this a legal Java program?
package pkg;
import java.awt.*;
It compiles fine but doesn't run (complains of missing main method). Does the code snippet constitute a legal Java program? What is a legal Java program? Is it a .java file which compiles or must it compile and as well as run? Thanks again.
Gaia.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi!
It all depends on what you call a program. If you mean one that will execute, then it must have a top-level class and a properly formed main method to run.
For example:
package pkg;
import java.awt.*; //package and import not necessary
public class MyClass{
public static void main(String args[]){
System.out.println("Hello world!");
}
}
is a valid java program if defined in a file named MyClass.java. It can be run after compiling by using the java MyClass command from the command line. Output will be Hello world!
Does that help?

------------------
Brian Hoff
Sun Certified Programmer for the Java� 2 Platform
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Hi Brian,
Yes, it does. Actually, the confusion came up when I attempted this question:
Question:
Which of the following are legal Java programs. Select all the correct answer.
A. // The comments come before the package
package pkg;
import java.awt.*;
class C{}
B. package pkg;
import java.awt.*;
class C{}
C. package pkg1;
package pkg2;
import java.awt.*;
class C{}
D. package pkg;
import java.awt.*;
E. import java.awt.*;
class C{}
F. import java.awt.*;
package pkg;
class C {}
Would u agree with the given answer: A, B, D, E
I don't quite agree with D.
Thanks again.
Gaia.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hi! Actually D is legal. You can have an empty file and it will still be a legal java file. You only need a main method for an application. A applet does not need a main method. It's the browser that deals with this it's own way. That's why you can compile a program without a main method , but you cannot run it by typeing java yourprog
// Mathias
Gaia Nathan
Ranch Hand

Joined: Aug 01, 2001
Posts: 62
Ohhh...i see. Thanks Mathias, Brian.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Legal java program?
 
Similar Threads
Need help getting started with Head First Java
Variable declaration in a loop
run the java program by ant task
Run project java with javac
package statement