Here's our first program, printing a string.
/* this is comment. */ // also comment class PrintMeApp { public static void main(String[] args) { System.out.println("O toiler through the glooms of night in peril and in pain!"); } }
Save it to a file and name it 〔PrintMeApp.java〕. Then compile it by running javac PrintMeApp.java. That will create a file named 〔PrintMeApp.class〕. It is the compiled code. To run the program, type java PrintMeApp in the terminal. Then it should print the string.
Note the keyword class in the code. A Class is like a boxed set of functions and data.
The “PrintMeApp” is the class's name. The public specifies that the class can be called by other classes/functions.
The static means that this class can be called without having to create an instance of it first.
The main is a function of this class. Functions defined inside a class is called the class's “method”. “main” is the primary method of any program. That is, there is one “main” method in any java program.
The main(String[] args) declares that the “main” method takes a argument of string type.
Do not worry about these details. We'll cover them each later. If you are not clear about the general concepts of Object Oriented Programing, you should now read: What are OOP's Jargons & Complexities?.
In general, ALL java source code have the following structure:
/* comment */ // Declaring this file to be a package. // All java source code belongs to some package. // Only trivial, testing code does not declare a packge. // When a source file does not declare a package, it is said be a “unnamed” package package mary.games.sounds; // load packages you need import java.awt.Cursor; import … … // a bunch of class definitions class MyClass1 { … } class MyClass2 { … } … // more classes // The main class. // The file name must be the same as this class name class MyMainClass { public static void main(String[] args) { //body… } }
Note that one of the class's name must be the same as the file name, else it won't compile. For example, if your file name is 〔MyMainClass.java〕, then one of your class must be named “MyMainClass”.
For now, you don't need to understand exactly how package works, or how exactly those keywords like “public”, “static”, “void”, “main” … means. We'll cover them in this tutorial. For now, just remember that all java source code have the above structure, and one of the class must have the same name as the file's name.
Note: the above example is meant to give a general outline of the form of a source file. It omits some details. For example, you can also have one or more “interface” definitions in a source file, similar to the class definitions above. Many class definitions will contain variables and methods and constructors. Also, a source file usually do not have the “main” method.
blog comments powered by Disqus