Java: Print String
Simple Java Example
Here's our first program, printing a string.
/* this is comment. */ // also comment public class PrintMe { public static void main(String[] args) { System.out.println("yes"); } }
- Save it to a file and name it
PrintMe.java
. - Then compile it by running
javac PrintMe.java
. This will create a file namedPrintMe.class
. It is the compiled code. - To run the program, type
java PrintMe
in the terminal. Then it should print the string.
Some Syntax Details
Note the keyword class
in the code. A Class is like a boxed set of functions and data.
The “PrintMe” 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: Object Oriented Programing (OOP) Jargons and Complexities .
General Structure of Java Code
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 package. // When a source file does not declare a package, it is said be a “unnamed” package package abc.def.sounds; // load packages you need import java.awt.Cursor; // a bunch of class definitions class MyClass1 { // code } class MyClass2 { // code } // more classes // The main class. // The file name must be the same as this class name public class MyMainClass { public static void main(String[] args) { //body } }
Class Name synced to File Name
For now, remember the following:
There must be one public class definition in the file that has the same name as the file name.
For example, if your file name is XYZ.java
, then one of your class must be named “XYZ”.