First Java Program
Explore the basics of Java programming by writing your first program that displays output and takes input from users. Understand how to use comments, variables, input methods like nextLine(), output commands like System.out.println(), and create simple interactive applications. Practice by creating a personalized greeting and a story program using multiple inputs.
Problem solving with Java
The basic tools for understanding the flow and the results of simple programs are
We can run a program as many times as we want, to try out different inputs of variables. We can also edit these programs to observe the result of a change in a value or logic for our learning.
In Java, we use nextLine() for input (to read a value from the user) and System.out.println() for print (to display a value on the screen as output).
Hello World
It’s time to write our first program in Java, which will simply display the message “Hello World!” on the screen.
This is the code widget that we’ll use to write our Java code. We may execute our Java program by clicking the “Run” button at the bottom of the widget:
Note: We can add non-executable text in a Java program by adding a double backslash sign (
//) at the start of the text. This type of text is called a comment. We use comments to include descriptions in the program.
Explanation
-
Line 1: This is a comment because it starts with
//(a double slash). It is only for the readers of this program. It describes the purpose and/or related matters of the program. -
Line 2–3: These are used as a requirement by the language. It is the start of the first block of code. Every starting brace
{has a corresponding closing brace}, as seen in line 8. We will be using these lines, as is, in almost every Java program. -
Line 4–5: These are the start of the executable part of the program. Every executable Java program has a main, which serves as its entry/starting point. The starting brace
{indicates the start of the second block of code. See the corresponding closing brace}in line 7. -
Line 6: It is the only line that caused the program to give output. It corresponds to the purpose of the whole program. Every other line is in support of line 6. We use
System.out.beforeprintas a requirement by the language. -
Line 7: This is the end of the main block of code. It corresponds to the opening brace in line 5.
-
Line 8: This is the end of the class block of code. It corresponds to the opening brace in line 3.
New line in the output
There are different ways of giving a line break in the output, as demonstrated in the following code:
Explanation
- Lines 6–7: The text of these lines is on the same line in the output. The
\nsymbol, termed as a new line character, causes the line break. - Line 8: This shows the use of
\nas a separate text. - Line 9: This illustrates the use of
printlnfor giving a line break in the output, as demonstrated from the output of line 10.
Personalize messages with a variable
Let’s write another Java program that inputs the name of the user before displaying a greeting message. We use the variable, yourName, to store the input given by the user in Java.
A variable name can only contain letters (
A–Zanda–z) and the underscore symbol (_). It may also contain digits (0–9), but the variable name can’t start with those. For example,Key_2is a valid variable name but2_keyis not. Variable names are case-sensitive, meaning thatname,Name, andNAMEare three different variables.
The Test.java in the left pane of the following widget is the name of the program file. .java indicates that it’s a Java program. When we press the “Run” button to execute the program, it shows a black screen called the terminal, where we can input values and see the resulting output:
import java.util.Scanner; // Import the Scanner class
class Test
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.print("Enter your name: " + '\n');
String yourName = myObj.nextLine(); // Read user input
System.out.print("Hello " + yourName + '\n');
System.out.print("Welcome to Educative" + '\n'); // Output user input
}
}The word exit at the end of the output indicates the completion of the program in the terminal.
Explanation
- Line 1: The
Scannerclass is used to get user input, and it is found in thejava.utilpackage. That’s why we import the package. - Line 6: To use the
Scannerclass, we have to create an object. In our case, we are creating an object,myObj, of theScannerclass and using any of the available methods found in theScannerclass.Scanner(System.in)is used to read input from the terminal window. - Line 8:
nextLine()reads a string value from the user.
Note:
\nis an escape character in Java that is used to enter a new line in the output.
The code above displays the message, "Hello ", before the value of the name variable on the first line. The space after Hello is part of the label to keep a space before the value of name in the output. Then, it displays “Welcome to Educative” on the second line.
Java programming practice
Let’s practice writing the first Java program that takes multiple inputs from the user.
Tell a story
Let’s write a program that tells a story with information given by the user. The program should ask the user to enter their name, age, city, college, profession, and pet’s name.
We’ll need to provide user input in the box labeled “Enter the input below.” Therefore, when the solution is ready for execution, we can test it by providing the following information line by line in the input box on behalf of the user.
- User’s name
- User’s age
- User’s city
- User’s college
- User’s profession
- User’s pet’s name
Once we are done writing the program, we can execute by clicking the “Run” button. The program should display the prompts to enter an input on the terminal, and we can enter the required input. Remember to store the input and print it using print/println, where required. The program should display the following story, inserting the user’s input into the appropriate locations in the following text:
There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted an animal named PETNAME. They both lived happily ever after!
import java.util.Scanner; // Import the Scanner class
class Test
{
public static void main(String args[])
{
// Write you code here
}
}