first java program

Write Your First Java Program : An Easy Guide For You

Creating the first Java program could be so exciting for a Java beginner. Kudos to that.! Also, it is important to learn and understand every piece of code in the program. 

This in-depth guide will help you write, learn, and understand your first Java program in a few minutes.

Previous Topic: How to Install and Setup Java on Windows, Linux

Next Topic: Compile And Run Java Programs

If you haven’t configured Java in your system, you must consider checking out the previous tutorial. If you have done that, then you are all set to continue with this tutorial.

Must-Have Things For Your First Java Program

First, let’s look at the important things you need to have with you to write your first Java program.

The first and most important thing you must do is download, install, and setup JDK in your System. This is inevitable. Without the JDK, we can’t compile and run our Java programs as you may have already known.

The second and the last thing you need for writing your first Java program is a Text Editor, or an Integrated Development Environment(IDE).

A text editor is enough for beginners. You can use the built-in text editor of the operating system on your PC. For example, the notepad in windows or the gedit text editor in Linux.

If you don’t prefer the built-in text editor, then you can download and use other popular open-source text editors like below.

A Text editor is a software program to create, edit, and save plain text content. So by using Text editors you can write and save your Java programs. But you must have to use the command window to compile and run the programs.

IDEs are software applications that provide the environment for software development. IDEs provide a lot of features other than creating and saving your programs.

Using an IDE you can create and save your programs, also compile, run and debug your programs. There are various popular open-source IDEs available. I have listed some of them below.

Eclipse is my choice. It is free, easy-to-use, and its primary purpose is to build Java applications. You can choose whichever you like. It’s up to you.

Write Your First Java Program

Sample Program

package sampleprograms;
public class FirstGeekyPointProgram {
	public static void main(String[] args) {
		System.out.println("Please don't print Hello World.!");
	}
}

The above-given is a very basic program that prints the sentence “Please don’t print Hello World.!” in the console. Use this sample program. But instead of copy-paste, I suggest you type the program.

Everything You Must Know About The Program

In our first Java program, we have created a Java class named ‘FirstGeekyPointProgram‘.

Concept of Classes in Java

Java is an object-oriented programming language. Right? If you don’t know the object-oriented concept in Java, click here first.

We define objects with certain properties and behaviors in Java by using the concept of classes.

A Class is a container we create to shape/form the objects in Java. 

A Java Class is like a white paper where you describe your Java objects.

In Java, we declare and define the attributes and behaviors of an object inside its class. So, every program statement we write in Java must be inside the class and with that class, you can create ‘n’ number of objects in Java.

To understand it better, I can provide you a classic example.

Imagine that the object you want to create is a ‘lion’. So first, you create a class with the name ‘Lion’.

Now you need to define its properties and behaviors.

What are the properties of a lion?

Its breed, age, color, weight, gender, length of its tail, etc. All these are its properties. You can see that these properties are of different types. Right? Age, weight, tail length are numeric values. Breed, color, gender are strings (sequence of characters).

We describe all these properties inside the ‘lion‘ class using different data-types available in Java.

What are the behaviors of a lion?

Run, hunt, eat, sleep, roar, etc are its behaviors. Each behavior is different. So, you must define each of these behaviors in your class.

How do you do that in Java? You do that by creating ‘methodsorfunctions‘. Behaviors equal to methods in Java.

Methods in Java

Methods are a set of programming statements. Methods are reusable pieces of code. We can give names to methods. Whenever we need to execute the code inside a method, we call it by using the method name.

We create methods/functions inside the class to define the object’s behaviors.

The Java Main Method

Our class contains a method named ‘main‘. The main method is the starting point of any Java program. i.e., the execution of a program begins with the main method in Java.

When we run the program, the Java Virtual Machine (JVM) looks for the class, which contains the main method. Once the JVM finds the main method, it calls the method, and it starts the execution of the program.

Source Code

The code we write is called source code.

Source File

The file which contains the source code is the source file.

Here in our source code, we have only one class, i.e. the FirstGeekyPointProgram. We can add multiple classes in a single source file. One class in the source file must contain the main method. The class that contains the main method is the main class

If the class we execute doesn’t contain the main method, then the JVM will throw an error like this: ‘Main method not found in class FirstGeekyPointProgram, please define the main method as: public static void main (String[] args)

If we declare the main class as public, then the filename and the main class name must be the same. Java allows only one public class in a single source file.

Note: The best practice is to keep one class per file and use the same name for the class and the source file.

The main method in our first Java program contains only one line of code. That is to print “Please don’t print Hello World.!” in the console.

I hope you have got a brief idea about the program. Now let’s look at every piece of code in our program line-by-line.

First Line

package sampleprograms;

‘package’ is a Java keyword to declare the package of a Java class/interface. This statement declares that the class ‘FirstGeekyPointProgram‘ is inside a package named ‘sampleprograms‘. The package statement must always be in the first line of the program.

Packages in Java

A package is a directory/folder where we store related Java classes and interfaces. Using packages you can organize your Java classes/interfaces that have common traits.

There are hundreds of inbuilt classes in the Java library. All these classes are inside packages.

In Java, it is always recommended to keep classes in packages.

It might not be a problem if your program contains only one or two classes.

But with large applications, the number of classes and interfaces will be big, obviously. If you don’t use packages in such huge applications, it will be extremely difficult for you to maintain them.

So make it a practice to keep your Java files in packages, no matter whether the applications are big or small.

You have two ways to refer to a class/interface in a different package in your class/interface.

  1. Import the class to your class using the import keyword
  2. Use the package name along with the class name wherever you use the class.

In normal scenarios, you can easily import the class you want to use in your program.

Importing a class

There are two ways of importing in Java.

  1.  Importing the particular class you want
  2. Importing the entire package

Importing a particular class

Let’s use the Date class in the java.util package in this example.

package sampleprograms;

import java.util.Date;

public class GeekyPoint {
	System.out.println(new Date());
}

The second line of the above program imports the ‘Date‘ class to our ‘GeekyPoint‘ class.

Importing the entire package
package sampleprograms;

import java.util.*;

public class GeekyPoint {
	System.out.println(new Date());
}

The second line of the above program imports all the classes/interfaces inside the java.util package to our ‘GeekyPoint‘ class. The asterisk symbol (‘*’) means ‘everything inside the package‘.

Use the package name along with the class name

You can use the package name along with the class name to refer to the class you want to use in your program. Here, you don’t have to use the import statement.

See the program below.

package sampleprograms;

public class GeekyPoint {
	System.out.println(new java.util.Date());
}

Once a class is inside a package, you can always use the package name along with the class name to refer to it specifically in any other classes of your Java application.

Using packages gives you the freedom to create multiple classes with the same name.

For example, let’s imagine you have two packages in your Java program, ‘pkgone‘ and ‘pkgtwo‘. Now create a class with the name ‘Geeky‘ inside the first package ‘pkgone‘.

Now, if you want to create another class with the name ‘Geeky’ in your Java program, you can easily do that by putting the class inside the second package ‘pkgtwo‘.

For example,

pkgone.Geeky – Referring to the class in the first package

pkgtwo.Geeky – Referring to the class in the second package

Referring to a class with the package name makes sense when you have to use multiple classes with the same name in a single class.

A class name along with the package name is known as the fully qualified name of the class.

In the above example, ‘pkgone.Geeky‘ is the fully qualified name of the class ‘Geeky’ in the first package, and ‘pkgtwo.Geeky‘ is the fully qualified name of the class ‘Geeky’ in the second package.

You can create package hierarchies in Java. There are main packages and inside that, there can be sub-packages. We use the dot operator.‘ after the main-package to access its sub-packages in Java. The same applies to the classes as well.

Second Line

public class FirstGeekyPointProgram {
Keywords In Java

Here the first two words public and class are keywords in Java.  A keyword is a reserved word that has a special meaning and a purpose in the programming language. There are 51 keywords in Java. Keywords in Java are small single words, and we must write them in lowercase letters.

The Public Keyword in Java

The first keyword public is an access modifier in Java. Access modifiers in Java are used to specify the accessibility/visibility of classes, variables, methods, interfaces, etc.

If you see anything in Java with a public keyword, it means you can access it from anywhere in the program.

I will explain more details about the access modifiers in a separate tutorial.

The Class Keyword in Java

The second keyword class is used to create a Java class. After the keyword, you must enter the name of the class. Here, you can see that the class name is FirstGeekyPointProgram. We call this an identifier in Java. Identifiers are the names you give to your classes, method, variables, packages, etc.

Common Rules For Identifiers in Java
  • The identifier name must contain at least one character.
  • The Identifier name must start with a letter, underscore (‘_‘), or dollar (‘$‘) symbol.
  • The identifier names should not start with a digit.
  • The identifier names should not include spaces. Instead, use an underscore between two words. Eg: My_Class.
  • The identifier name can contain alphanumeric characters, underscore, and the dollar symbol.
  • Java does not allow an identifier with only an underscore.
  • Java does not allow keywords as identifier names
  • Examples of valid Identifiers: GeekyPoint, geeky_Point, _GeekyPoint4u, $GeekyPoint_, geeky$point, firstJavaProgram.
  • Examples of invalid Identifiers: 2geekypoint, geeky.point, first java program.

Java is a case-sensitive programming language. So, Apple, apple, and APPLE are three different things for Java.

Since it is case-sensitive, there are some naming conventions in Java. For Example in Java, we write class names in the Pascal-Case format.

What is Pascal-Case?

Did you notice that each word in our class name ‘FirstGeekyPointProgram’ starts with a capital letter? We call this the Pascal-Case format. In the Pascal-Case format, the first letter of each meaningful word must be in uppercase.

Entering class names in Pascal-Case is just one of the naming conventions in Java.

Naming conventions in Java are some rules/standards to follow while writing your Java programs.

What happens even if you don’t follow these rules? Nothing.! Your program will run fine. But it is always better to follow these rules in every Java program.

Why Naming conventions are important?

Naming conventions establish a coding standard and improve code readability. It helps other programmers to read your code easily. So you must learn and apply the naming conventions in all your programs.

Note: Here I cover only a few naming conventions. You can expect a detailed explanation of all the Java naming conventions in the coming tutorials.

Use of Curly Braces { }

The curly-brace ‘{‘ after the class name is used to denote a block. Java is a block-structured programming language. In Java, we write program statements inside blocks. Each block contains a collection of program statements. We define the boundary of a block by the open and close braces’{}‘ in Java.

In the sample program, you can see that there are two blocks. One is for the class FirstGeekyPointProgram and the other is for the main method.

Third Line

public static void main(String[] args) {
The Static Keyword in Java

The second line contains three Java keywords. i.e., public, static, and void. I have already talked about the keyword public. Let’s jump into the next keywords.

The keyword static is one of the non-access modifiers in Java.  So, what is a non-access modifier in Java? Non-access modifiers in Java are used to provide certain functionality to a class, method, variables, etc.

If you see anything with the static keyword in Java, it means you can access it without creating an object. This is because the static items are not for a specific object, but for the class. They will have a static memory allocated to them at runtime.

The main method is static by default in Java. You can’t change it because the JVM wants to call the main method without creating an object.

The Void Keyword in Java

We use the void keyword with Java methods to denote that the method returns nothing.

Return Types

In Java, you can create methods that return data of any type. For Example a digit, a character, a sequence of characters, objects, a list of objects, etc. We call this the return type of method.

If a method in Java returns nothing, then we must give the keyword void at method declaration, just before the method name.

The main method returns nothing in Java, Hence we use the keyword void. The return type of the main method is void.

After the keyword void, we have given ‘main‘ as the method name. The method names also have a naming convention in Java, just like the class names. In Java, we use the camelCase format for methods and variables.

What is Camel Case?

In the camelCase format, the first word in the name must be in lowercase letters, and the subsequent words will be in the PascalCase format. i.e. from the second word onwards, the first letter of each meaningful word must be in uppercase. Eg: myFirstMethod, secondVariable.

Note: If the method or the variable name has only one word, then obviously it must be in lowercase letters.

So far we have covered the second line of our first Java program up to ‘public static void main. What left now is ‘ (String[] args) {‘.

Hope you are still here.!

Use of Parentheses () in Java

After the method name, you can see that there are parentheses ‘ () ‘. You can use the parentheses to add the method parameters/arguments.

In Java, we use parentheses with methods, constructors, conditional statements, mathematical and programming expressions, etc.

It is mandatory to include parentheses in every Java method after the method name, even if no method parameter is present.

We can discuss the other uses of parentheses in Java in the forthcoming tutorials.

Method Parameters

Parameters are the local variables of a method that accept the values we send to the method while we call the method.

Remember that, in Java, The JVM executes the statements inside a method only if there is a call to that method.

When we call a method, we can input/pass values to that method.

We achieve this by using the method parameters. Parameters are optional. We use them if we need them.

Note: Method parameters are part of the method-signature in Java.

Method-Signature

Method-signature includes the method name and parameters. We differentiate Java methods by considering their signatures. It should be different for different methods. 

Inside the parentheses of the main method, there is one parameter, i.e. String[] args. This is a string array parameter. Well, then what is a string in Java? What is an array? Let’s understand it one-by-one.

String in Java (in brief)

The String is a built-in class in Java. A string is a sequence of characters. In Java, we create strings using double-quotes. For example, “learn here“, “first java program“, “geekypoint“, “12345“, etc.

Every string we create in Java is the object of the String class in Java.

Where is this String class stored?

String class is inside the Java base package ‘java.lang‘.

In the java.lang package, java is the main-package and lang is the sub-package.

We call the java.lang the base package because we don’t have to import this package to our Java programs to use it. The java.lang package is imported by default in Java. Therefore, it is always there in every Java program.

Arrays in Java (in brief)

Array is a data structure to store similar types of data in Java. You can define the size of the array in Java. Once you define the array size, you cannot alter it, and also you cannot store different types of elements in arrays.

You can store strings, digits, single characters, objects, etc in an array. We use square brackets ‘[]’ to declare arrays in Java.

That’s why there are square brackets in the main method parameter ‘String[] args‘. First, we must specify the data type of the array. Here the data type is String. ‘args‘ is the parameter name.

The square brackets should come right after the data type or the parameter name.

You can pass string values to the ‘String[] args’ parameter when you run the program in a command window. Hence, the parameter ‘String[] args’ is known as the command line argument.

Can I Change The Java Main Method Syntax?

You know that the main method is the entry point of any Java program, and JVM is the one that calls the main method at runtime. JVM wants the main method to be public and static.

The main method should return nothing, hence the return type should be void. And it should contain a String array parameter.

Let’s see if we can change anything in the main method syntax.

Default declaration: public static void main(String[] args) {

You can only do some minor changes to the Java main method. I have listed them below.

  1. Swap public and static like this: static public void main(String[] args) {
  2. Put square brackets after the argument name: public static void main(String args[]) {
  3. Change the parameter name: public static void main(String geeky[]) {

These are the only changes we can make to the Java main method.

Let’s move on to the next line of the program.

Fourth Line

System.out.println("Please don't print Hello World.!");

This statement will print the string “Please don’t print Hello World.!” inside the double quotes in the command window/console.

Let’s break it down.

System Class in Java

The System is a Java class that provides the standard input, output, and error streams along with some useful utility methods. ‘System’ class is also inside the java.lang package just like the String class.

Use of The Variable out

out‘ is a static variable inside the System class. Since it is static, you don’t need an object to access it. You can access it just by using the class name, as you can see in the third line.

The type of ‘out’ is PrintStream. PrintStream is a Java class inside the java.io package. Here we use the variable ‘out’ to call the method ‘println‘.

Use of The Method ‘println

Println is a method inside the PrintStream class. Println method accepts a parameter value and prints it on the console. After printing the value, the cursor will go to the next line.

What you see in the third line is a call to the println method.

We pass the String value “Please don’t print Hello World.!to the println method here in our sample program.

You can pass any digit, String, character, boolean(true or false), etc to the println method. 

Use of Semicolon in Java

Every program statement in Java ends with a semicolon ‘;‘. Semicolons are used in Java to specify the end of each program statement.

It doesn’t matter if the program statements are in the same line or not. Semicolons are part of the Java syntax.

Your program won’t compile if you miss adding a semicolon after program statements.

After the third line, there are closing braces ‘}’ of the main method and our class ‘FirstGeekyPointProgram‘.

That’s it. You have made it to the end of this guide.

Conclusion

I hope this helps you to write your first Java program (also master it.!).

So, do you like this Java guide?

Is there anything you think I must add to this topic?

Let me know all your thoughts by dropping a comment.!

Also, please share this with your friends if you find this guide useful.

Check out the next guide to learn how to run a Java program.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *