Java Quickstart
In Java, every application begins
with a class name, and that class must match the filename.
Let's create our first Java file,
called MyFirstJavaProgram.java, which can be done in any text editor (like
Notepad).
The file should contain a
"Hello World" message, which is written with the following code:
MyFirstJavaProgram.java
Let's start.....
/* This is my first java program.
*/
public
static
void
main(String[] args
)
{out
.println(“Hello World”);
}Don't worry if you don't
understand the code above - we will discuss it in detail in later chapters. For
now, focus on how to
run the code above.
Save the code in Notepad as
"MyFirstJavaProgram.java". Open Command Prompt (cmd.exe), navigate to
the directory where you saved your file, and type "javac
MyFirstJavaProgram.java":
C:\Users\Your Name>javac MyFirstJavaProgram.java
This will compile your code. If
there are no errors in the code, the command prompt will take you to the next
line. Now, type "java MyFirstJavaProgram" to run the file:
C:\Users\Your Name>java
MyFirstJavaProgram
The output should read:
Hello
World
Congratulations! You have written and executed your first Java program.
In the previous chapter, we
created a Java file called MyFirstJavaProgram.java, and we used the following
code to print "Hello World" to the screen:
MyFirstJavaProgram.java
public
class
MyFirstJavaProgram
{
public
static
void
main(String[] args
)
{
System.out
.println(“Hello World”);
}
}
Example
explained
Every line of code that runs in Java
must be inside a class. In our example, we named the class MyFirstJavaProgram. A
class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyFirstJavaProgram" and
"myfirstjavaprogram" has different meaning.
The name of the java file must match the
class name. When saving the file, save it using the class name and add
".java" to the end of the filename.The output should be:
Hello
World
The
main Method
The main() method is
required and you will see it in every Java program:
public
static
void
main(String[] args
)
Any code inside the main()
method will be executed. You don't have to understand the keywords before and
after main. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every
Java program has a class name which must match the filename, and that every
program must contain the main() method.
System.out.println()
Inside the main() method, we
can use the println() method to print a line of text to the screen:
public
static
void
main(String[] args
)
{
System.out.println(“Hello World”);
}
{}
marks the beginning and the end of a block of code.2) Each code statement must end with a semicolon.
No comments:
Post a Comment