×

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

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.