2-First Code In Java
First Java Program in VS Code
Choosing a Theme
On the first launch of VS Code, you will be asked to choose a theme according to your
preference. We will choose the dark theme. After opening the editor, you will see several
icons on the left panel of the screen:
1. Explorer Icon: Used for locating files and folders.
2. Search Icon: Used to search for the desired file or folder.
3. Source Control Icon: Used for sharing or pushing our code to a repository or any
version control system.
4. Run & Debug Icon: Used to run our program and debug it later if any error occurs.
5. Extensions Icon: Used to add suitable and required extensions.
Creating a Project
1. Click on New Project.
o A project is a group of multiple files, including multiple external libraries and
dependencies.
o As this is our first project, we are not using any external library.
o Choose a location where you will store your project files.
2. Checking Java Version:
o Open the terminal in VS Code by clicking on the + icon and selecting Open
Terminal.
o Type the following commands to check the Java and Javac versions:
java -version
javac -version
o Ensure you have Java 17, which is an LTS version.
Creating Your First Java File
1. Create a New File:
o Name the file Hello.java.
o As we use .js extension for JavaScript and .c for C files, we use .java
extension for Java files.
2. Writing the Code:
o To print "Hello, World!" on the screen as output, we need to write at least 3-4
lines of code because Java is a structured language.
o However, from Java 9, we have JShell, which was introduced for beginners to
understand the syntax and for experimental purposes. Using JShell, we can
print this in a single line.
3. Using JShell:
o Open JShell by typing jshell in the command prompt.
o In VS Code, click on the + icon and select Open Terminal to open the
terminal.
o
o Type the following command in JShell:
System.out.println("Hello, World!");
o Whenever we write text inside the braces, we need to put it in double quotes.
For numbers, we just write them as they are.
o Press Enter, and you will see the console displaying "Hello, World!".
Running the Code in a Java File
If we try to compile and run the single line System.out.println("Hello, World!"); in a Java
file, it will give errors.
We will explore the errors and their meanings in the next chapter.