Java Progamming For Beginners Lesson 3: Your Second Program (Java Basic Syntax)

In this Tutorial 3, we would write a second program and also understand java basic syntax. In Tutorials 1 we installed NetBeans which is the compiler you will be using.
In Tutorial 2, we wrote our first program.


Let’s start with a little exercise. (Your Second Program)
Write and run the program below. You already know how to create Java application in NetBeans.

 

public static void main(String[] args) {
String name = "Kindson The Genius"; //You can replace Kindson The Genius with your own name
      String title = "Researcher";
      String location = "Europe";
      int duration = 1;

      System.out.println("My Name is "+ name );
      System.out.println("I am a " + title );
      System.out.println("I live in " + location);
      System.out.println("I have stayed here for " + duration + " year");
    }

Listing 1.0: Your Second Program

 

If you have written it correctly and run it, the window would be as shown in Figure 1 below.

Figure 1

Let’s understand a few things about the program above

1. The first four lines following the main line show a declaration of four variables. The first 3 are strings while the last one is an integer(number). A variable is just a memory location to hold values.

      String name = "Kindson The Genius"; //YOu can replace Kindson The Genius with your own name
      String title = "Researcher";
      String location = "Europe";
      int duration = 1;

Variable declaration in Java

2. Note in the first line that there is a part that starts with // You can replace… This is example of a comment. The compiler ignores comments. Comments are what you add to a program to explain it to someone reading it. The compiler does not execute it.

//YOu can replace Kindson The Genius with your own name

Example of comment in Java

3. Note the use of + sign in the last four lines. This plus sign is called ‘concatenation operation’ (say in 5 times!). It is used to combine two variable together into a string.

      System.out.println("My Name is "+ name );
      System.out.println("I am a " + title );
      System.out.println("I live in " + location);
      System.out.println("I have stayed here for " + duration + " year");

Concatenation in Java

4. Also note that part of the statement to be printed is enclosed in double quotes. This is called string literal. The next part not enclosed in quotes is called variable (can be string variable or integer variable)

Try to digest this all that have been mentioned here and then Tutorial 4 would be out is couple of days.

 

Tutorial 1: Introduction to Java and NetBeans Installation
Tutorial 2: Write Your First Java Program in NetBeans