How to Write Your First Program with Java
Write your first Java program
To start programming with Java, you need to set up a working environment. Many programmers use Integrated Development Environments (IDEs), such as Eclipse and Netbeans, for Java programming. However, you can still write and compile Java programs without them.
Any program similar to Notepad is sufficient for programming with Java. Sometimes, conservative programmers still prefer to use text editors included in the terminal, such as vim and emacs. Sublime Text is a good text editor that can be installed on both Windows and Linux-based computers (Mac, Ubuntu, etc.). It is also the editor used in this tutorial.
Make sure that the Java Software Development Kit is installed. You will need it to compile the program.
On a computer using the Windows operating system, if the environment variables are incorrect, there may be a runtime error javac
. Please refer to the article on how to install Java Software Development Kit to avoid this error.
Hello World Program
First, we'll create a program that prints the text "Hello World." In a text editor, create a new file and save it as "ChaoThegioi.java". ChaoThegioi is your class name and this class name needs to match the file name.
Declare the main class and method. The main method public static void main(String[] args)
is the method that will be executed when the program runs. The declaration is the same in all Java programs.
public class ChaoThegioi { public static void main(String[] args) { } }
Write a command line that prints the text "Hello World."
System.out.println("Hello World.");
Let's look at the components of this command line:
System
command the system to do something.
out
tells the system that we're about to do something with the output.
println
stands for "print line" and with it we are asking the system to print a line in the output.
The surrounding parentheses ("Chào Thế giới.")
indicate that the method System.out.println()
takes one parameter, and in this case, it's a String"Chào Thế giới."
Note that in Java there are some rules that we must follow:
Always end lines with a semicolon.
Java distinguishes between uppercase and lowercase letters. Therefore, to avoid errors, you must write method names, variable names and class names in the correct upper or lower case form.
The individual code block of a given method or loop is enclosed in curly braces.
Merge. Your final Hello World program will look like this:
public class ChaoThegioi { public static void main(String[] args) { System.out.println("Hello World."); } }
Save the file and open a command prompt or terminal. Navigate to the folder where you saved ChaoThegioi.java and type javac ChaoThegioi.java
. This code will tell the Java compiler that you want to compile ChaoThegioi.java. If there is an error, the compiler will tell you where you made the mistake. If there were no errors, there would be no message from the compiler. Now, looking at the directory of ChaoThegioi.java, you will see ChaoThegioi.class. This is the file Java uses to run your program.
Run the program. Finally, we have to run the program! At the command prompt or terminal, type java ChaoThegioi
. This code tells Java that you want to run the ChaoThegioi class. The words "Hello World." will appear on your monitor screen.
Congratulations, you have written your first Java program!
Input and output
Now, we'll extend the Hello World program to take input from users. In this program, we have printed a string of characters so that the user can read it. However, the interactive part of the program is where the user will enter input information into it. Now, we will expand the program, ask the user to enter their name and then send them a personal greeting.
Import the Scanner class. In Java, we can access a number of built-in libraries. However, to use them, we need to enter them into the program. One of those libraries is java.util, which contains the Scanner object we need to get information from the user. To import the Scanner class, add the following line at the beginning of the program.
import java.util.Scanner;
This command line tells the program that we want to use the Scanner object available in the java.util package.
To access all objects in the java.util package, we just need to write it import java.util.*;
at the beginning of the program.
In the main method, create a new instance of the Scanner object. Java is an object-oriented programming language, so it represents concepts using objects. Scanner is an example of an object with fields and methods. To use the Scanner class, we must create a new Scanner object - we will be able to add fields and use its methods. To do so, we write:
Scanner userInputScanner = new Scanner(System.in);
userInputScanner
is the name of the Scanner object we just created. Note that this name is written in CamelCase (meaning the words are written next to each other, the first letter of each word is capitalized) – this is the variable naming convention in Java.
We use operators new
to create a new instance of an object. In this case, we created a new instance of the Scanner object by writing new Scanner(System.in)
.
The Scanner object receives parameters indicating what to scan. In this case, we enter it System.in
as a parameter. System.in
requires the program to scan for input from the system, which is the input that the user will type into the program.
Ask the user to enter information. You will have to ask the user to know when to type something into the control screen. This can be done using code snippets System.out.print
or System.out.println
.
System.out.print("What is your name?");
Have the Scanner object receive the next line the user types and store it as a variable. Scanner will always receive data entered by the user. The next line will tell the Scanner to receive the user's input and store it in a variable:
String userInputName = userInputScanner.nextLine();
In Java, the convention for using an object's methods is objectName.methodName(parameters)
. In userInputScanner.nextLine()
, we call the Scanner object by the name we gave it and then we call its method nextLine()
, which takes no parameters.
Note that we're storing the next line in a different object: a String object. We have named userInputName
this object.
Print a greeting to the user. Now that the user's name has been stored, we can print a greeting to send to them. Remember the code System.out.println("Chào Thế giới.");
we wrote in the main class? Any code we just wrote will come before that line of code. Now we can adjust that line of code to:
System.out.println("Hello " + userInputName + "!");
The way we combine "Hello", the user name and the "!" with "Xin chào " + userInputName + "!"
is called String concatenation.
Here, we have three strings of characters: "Hello", userInputName, and "!". In Java, Strings are immutable. So when we put these three strings together, we are essentially creating a new string of characters that contains the greeting.
Next, we will take this new string and enter it as a parameter System.out.println
.
Combine and save. We have the following program:
import java.util.Scanner; public class ChaoThegioi { public static void main(String[] args) { Scanner userInputScanner = new Scanner(System.in); System.out.print("What's your name?"); String userInputName = userInputScanner.nextLine(); System.out.println("Hello " + userInputName + "!"); } }
Compile and run. Go to command prompt or terminal and run with the command we used in the first run of ChaoThegioi.java. First, we must compile the program: javac ChaoThegioi.java
. Next, we can run it: java ChaoThegioi
.
You should read it
- How to Write Your First ebook
- Instructions on how to create Ebooks from Wattpad
- How to Transfer Books to Kindle
- How to write curves in Photoshop
- Learn about the Write Zero method
- Use more than 30,000 free eBooks for iPad
- Why write neat and organized HTML?
- How to enable / disable Disk Write Caching in Windows 10
- What is JD? What does JD mean?
- How to create an ebook using Pages application on iPhone and iPad
- 13 best free eBooks for Web Designer
- The best apps that support writing and writing notes on Android