In this section we will learn how to write and execute a simple Java program.
To write a Java program you can use any text editor like notepad, notepad++ on windows, gedit on linux.etc..
You can also use popular IDE, in order to write and execute your java programs.
Like :- BlueJ,NetBeans, Eclipse etc...
To compile your Java source code, you need a Java compiler, and to run an Java interpreter.
You will get these in JDK. So, before proceeding make sure you have installed and configured
the JDK in your system.
Programming in Java: We break the process of programming in Java into 3 steps:
Create the source code, using a text editor and save the file with extension .java.
For example: MyFirstProgram.java or Hello.java etc..
Compile the source file by typing ...
"javac SourceFileName"
in the terminal window (command prompt). javac MyFirstProgram.java
After successful compilation it will generate a class file (bytecode) with extension .class.
Name of this bytecode will be same as your class-name in your source code with extension .class.
This .class file is meant for jvm.
Execute (or run) it by typing
"java classFileName"
in the terminal window (command prompt).
e.g. java MyFirstProgram
NOTE: Don't write extension .class at the time of execution.
Open the text editor.
Type the following code and save the file with name "HelloWorld.java"
You can save your file at any location in your system, for this example file is saved at Desktop.
public class HelloWorld
{
public static void main(String [] args)
{
System.out.println("Hello World");
}
}
Explanation:
Let's understand the code and meaning of class, public, static, void, main , String, and System.out.println().
Source code create by programmer.
Source file contains high level language code.
Source code may contain one or more class declaration.
Source code cannot have more than one public class.
Source file must be save with .java extension e.g. FileName.java.
If source code contains a public class then the source file name must be same as public class name.
package declaration; import statements; class ClassName { //class members }
Compiler generates byte code from source code.
Byte code contains intermediate code.
Only JVM can understand byte code.
Compiler generates one byte code per class.
Byte code saves with .class extension e.g. ClassName.class.