General Syntax and a Simple Java Program
Java is based on C and C++ and much of its basic syntax is similar to those languages. This is why the transition from a language like C or C++ to Java is easier than the transition from a language like Fortran to Java. For example, every executable statement in a Java program is
Lines of code can be indented any way you like. You can start a line in the first column or the 20th if you
Braces ”{ } ”denote blocks of code in Java. You can define blocks of code
Before we go any further, let's look at a simple Java program that will contain many of the elements we discussed in the previous paragraphs. Example: A Simple Java Program
This is the simplest type of Java program. It consists of one class named
SimpleProgram
that defines one method called
main()
. Your programs will eventually have a lot more to them. You may import packages, extend the capabilities of existing classes, define constructors and
The program defines two blocks of code. The first encloses the definition of the
SimpleProgram
class. The second
Inside the
main()
method, two
public class SimpleProgram
{
public static void main(String args[]) {
double area, radius = 2.0;
area = Math.PI*radius*radius;
System.out.println("area of circle is " + area);
}
}
Output ” area of circle is 12.566370614359172 |
Comments
Every good computer program needs comments to help someone (even the developer) figure out what the code is doing. Java provides three types of comments. The first is the C-based multiline comment. The comment begins with the token
/*
and ends with the token
*/
. Everything between these
The second type of comment is a single line comment. The token // is placed at the beginning of the comment. This comment cannot span multiple lines. The third type is a documentation comment. The syntax is similar to a multiline comment except it begins with /** . There is a utility that comes with the Java SDK called javadoc . By default, this utility creates HTML files that describe Java source code. (The Sun Java doc pages were created using the javadoc utility.) Documentation comments are incorporated into the HTML files created by javadoc . Example: Using Comments
public class CommentDemo
{
public static void main(String args[]) {
// This is a single line comment
/* This is a comment
that can span more
than one line */
/** @author Grant Palmer */
}
}
This example shows the three types of comments in action. The
@author
syntax is one of the special
javadoc
tags that can be used with documentation comments. For more information on documentation comments and their associated tags,
|