Please wait ......

Creating a Java class in NetBeans IDE

Learn how to create a new Java class, write some simple logic inside main method and run the program.


We will write a Java program to obtain a name as input and just print it. To implement the logic of a Java program we create one or more Java classes. Here as the logic is very simple we will create only one Java class called NamePrinter.java

Java program - Entry point :

How will the JRE know where to start in a given Java program when we run it?

 

 

The answer is simple - It will search for a method with the following signature

public static void main (String args[]){

//Logic here

}

Now let us create NamePrinter.java and the main method in it using NetBeans IDE.

  1. Click on the Source Packages and select New -> Java Class.
  2. Fill in the values as shown in the screen shot below and then click "Finish" button

 

What is a package?

We will learn more about in the future chapters. We will skip the explanation as of now.

Creating the main method and the logic:

Inside NamePrinter.java create a main method as below.

   public static void main(String[] args) {
        System.out.println(args[0]);
    }

Here args is a String array which will contain the input values to a Java program. (More about Arrays in future chapters). Zero index refers to the first input element. Hence as we are going to pass the name as the first input element, we have written to print the String at zeroth index

System.out.println(args[0]);

Let us learn how to pass input arguments to this Java program in NetBeans:

Choose Customize option as shown in the screenshot below.

In the pop-up, fill in details as indicated and then press "Ok" button at the bottom

Now press the Run button as indicated in the screen shot below.

The output should be like

run:
KatrinaKaif
BUILD SUCCESSFUL (total time: 0 seconds)

 

Watch the below video showing the entire workflow: