In this post we will see what are the basic rules, the components and the structure of Java programs. Based on what we have learned in Tutorial Java – #1 Prerequisites, it is supposed that you know that:
-
Java source files are text files with .java extension;
-
using command prompt and a compiler, javac.exe, the source files are syntax checked and compiled into bytecode, .class files;
-
the bytecode is executed by a Java Virtual Machine – JVM, java.exe
-
for developing Java applications you can use only the JDK (Java Development Kit) and the command prompt or an IDE (Integrated Development Kit) like NetBeans or Eclipse
Basic rules for writing Java source code
-
one line comments are defined by //
-
multiple lines comments are defined between /* and */
-
the end delimiter for a instruction is ; (semicolon); you can write two or more instructions per line, but separated by ;
-
commented instructions are ignored;
-
instructions can be associated in blocks of code that are defined between { and }; by default a method or a class has associated a single block of code;
-
Java language is case sensitive, vb as variable is different than Vb or VB;
/*
* define a function that adds two numbers
* input: a and b
* return: a+b
*/
int add(int a, int b)
{ //start of the function block
int A = a; //local variable A
// is different than a
int B = b; int S = 0;
//int C = 0; //commented instruction
return S=A+B;
} //end of the function block
Basic structure of a Java source code
Let’s look again to the HelloWorld application, defined by the HelloWorld.java file:
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World Java!");
}
}
The Java source code, files with .java extension, is structured based on strict rules:
-
EVERYTHING is defined inside a class (more on classes in next posts) that represent structures that contain data or/and methods; a Java application is a collection of one or more classes;
-
You CAN NOT define GLOBAL variables or methods outside a class (like you did in C/C++);
-
Any executable Java application has an entry point, meaning it requires a main (main represent also the name) function; the entry point of an application defines the first instruction to be executed; without this rule, if you define more than a method, the JVM doesn’t know where to begin the application’;
-
the main method must be define as public (more on access types in next posts);
-
a class has a body (that contains attributes and/or methods) defined between { and };
-
The class that contains the main function has the same name (at case level) with the file; HelloWorld class is in the HelloWorld.java file; otherwise, if you change the class name you get:
java.lang.NoClassDefFoundError: HelloWorld
Exception in thread "main"
On short, the simplest Java Application is described as: