×

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

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map). Nested Maps are useful in various situations, including...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 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.

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.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.