×

How to write basic Java Programs

Java Basic Programs

In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list.

To execute a Java program, one has to:

  • Install JDK
  • Set the jdk/bin path in the PATH environment variable.

Before executing any Java program, ensure the above two points without installing JDK execution of Java program is not possible.

Let’s create a Hello-World Java program.

Filename: HelloWorldExample.java

public class HelloWorldExample
{
public static void main(String[] args)
{             
System.out.println("Hello World");
}
}

Output:

Hello World

Explanation: Everything in Java should be written inside a class. Otherwise, the compiler will punish. In the above code snippet, we have used the following keywords. Let’s discuss each of them.

class: It is a keyword in Java that is used to define a class. The class encapsulates the whole code into itself. The class keyword is always followed by the class name. In our case, the class name is HelloWorldExample.

public: It is an access specifier which tells that the class is accessible by any other class available in the Java universe.

static: It is a keyword ensures that the main method is a class method. A class method is a method that can be called with the help of the class name.

void: It is also a keyword. It denotes nothing. If a method has the keyword void it means nothing is returned by the method.

public static void main(String[] args): It is the entry point of any Java program. A program can never have more than one entry point. The main method is invoked by the JVM.

It is mandatory to declare the main() method as public. Otherwise, the program won’t compile. This is because any other specifier (such as private, protected, etc.) reduces the visibility of the main() method, and the JVM cannot find it. If we make the main() method private or protected, the JVM shows an Error:Main method not found in class FactorialProgramExample, please define the main method as: public static void main(String[] args).

The name of the file containing the above source code must match with the class name containing the public access specifier, and the extension of the file should be .java. Thus, the complete file name would be: HelloWorldExample.java

After compiling the HelloWorldExample.java file, we get a .class file, namely, HelloWorldExample.class. A Java .class file contains Java bytecode. The .class file is then executed by JVM to generate the output.

Note: The number of .class files will always be equal to number of classes present in the .java file.

System.out.println() is the Java statement that prints whatever we passed as an argument. Here, the class name is System, out is the object of the PrintStream class and println() is the method of the PrintStream class. The last letters ‘ln’ of the println() method is for the new line. It means after printing the argument, the cursor jumps to the next line. In the above code, if we add one more println-statement like the following:

System.out.println("Hello World");
System.out.println("Hello World");

We will get the output as:

Hello World
Hello World

If we remove the ‘ln’ from the first println-statement, we will get:

Hello-WorldHello-World

To compile a .java file we use the javac command and to run it we use java command. Thus,

For compilation: javac HelloWorldExample.java

For execution: java HelloWorldExample

In the main method, String[] args is the command-line argument. The command-line argument is an array of the type String. Its value can be set in the command prompt when we execute the Java program. Thus, another way to print Hello-World will be:

FileName: HelloWorldExample1.java

public class HelloWorldExample1
{
public static void main(String[] args)
{             
for(int i = 0; i < args.length; i++)
{
System.out.print(args[i]);
}
}
}
For compilation: javac HelloWorldExample1.java
For execution: java HelloWorldExample1 Hello-World

Output:

Hello-World

At the execution time, we have passed the command line-argument Hello-World. Then, in the code, we are iterating over the String array args to print the Hello-World.

Similarly, we can also write other basic Java programs such as:

We will cover the above Java programs one by one in the coming section.


Related Topics

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.