×

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 Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

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

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

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

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Java.lang.Exception.NoRunnableMethods

In Programming language, the java lang unexpected no precompiled methods error generally refers to a Junit exception that happens whenever Junit is incapable of locate the precompiled test methods. When...

4 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

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

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.