Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Beginner's Guide to Executable Java Applications

DZone's Guide to

A Beginner's Guide to Executable Java Applications

Intended for Java novices, this is a guide to executable and nonexecutable Java applications.

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

In this article, excerpted from the OCA Java SE 8 Programmer I Certification Guide, I will cover executable Java applications.

Image title

Deal of the day-Nov 9, 2015: Get 50% off 'OCA Java SE 8 Programmer I Cert Guide', by using code dotd110915tw at manning.com.

The OCA Java SE 8 Programmer I exam requires that you understand the meaning of an executable Java application, and its requirements; that is, what makes a regular Java class an executable Java class. Even though you might be using an Integerated Development Environment (IDE), like Eclipse, to write and execute your Java code, you need to know how to execute a Java program from the command line for the exam.

Executable Java Classes Versus Nonexecutable Java Classes

“Doesn’t the Java Virtual Machine execute all the Java classes when they are used? If so, what is a nonexecutable Java class?”

An executable Java class is a class which, when handed over to the JVM, starts its execution at a particular point in the class — the main method, defined in the class. The JVM starts executing the code that is defined in the main method. You cannot hand over a nonexecutable Java class to the JVM and ask it to start executing the class. In this case, the JVM won’t know how to execute it because no entry point is marked, for the JVM, in a nonexecutable class.

Typically, an application consists of a number of classes and interfaces that are defined in multiple Java source code files. Of all these files, a programmer designates one of the classes as an executable class. The programmer can define the steps that the JVM should execute as soon as it launches the application. For example, a programmer can define an executable Java class that includes code to display the appropriate GUI window to a user and to open a database connection.

In figure 1, the classes Window, UserData, ServerConnection, and UserPreferences don’t define a main method. Class LaunchApplication defines a main method and is an executable class.

Figure 1

Figure 1 – Class LaunchApplication is an executable Java class, but the rest of the classes—Window, UserData, ServerConnection, and UserPreferences—aren’t.

The Main Method

The first requirement in creating an executable Java application is to create a class with a method whose signature (name and method arguments) match the main method, defined as follows:

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

This main method should comply with the following rules:

  • The method must be marked as a public method.

  • The method must be marked as a static method.

  • The name of the method must be main.

  • The return type of this method must be void.

  • The method must accept a method argument of a String array or a variable argument of type String.

Figure 2 illustrates the previous code and its related set of rules.

Image title

Figure 2 – Ingredients of a correct main method

It’s valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:

public static void main(String... args)            //It is valid to define args
                                                    //as a variable argument

To define a variable argument variable, the ellipsis (...) must follow the type of the variable and not the variable itself (a mistake made by lot of new programmers):

public static void main(String args...)    // This won’t compile. Ellipses should 
                                           // follow the data type, String

As mentioned previously, the name of the String array passed to the main method need not be args to qualify it as the correct main method. The following examples are also correct definitions of the main method:

public static void main(String[] arguments)     // The names of the method arguments are arguments
public static void main(String[] HelloWorld)    // and HelloWorld, which is acceptable

To define an array, the square brackets, [], can follow either the variable name or its type. The following is a correct method declaration of the main method:

public static void main(String[] args)           // The square brackets, [], can follow 
public static void main(String minnieMouse[])    // either the variable name or its type

It’s interesting to note that the placement of the keywords public and static can be interchanged, which means that the following are both correct method declarations of the main method:

public static void main(String[] args)    // The placement of the keywords public 
static public void main(String[] args)    // and static is interchangeable

On execution, the code shown in figure 2 outputs the following:

Hello exam

Run Java Program From Command Line

Almost all Java developers work with an IDE. The OCA Java SE 8 Programmer I exam, however, expects you to understand how to execute a Java application, or an executable Java class, using the command prompt.

NOTE: If you need help getting your system set up to compile or execute Java applications using the command prompt, refer to Oracle’s detailed instructions at http://docs.oracle.com/javase/tutorial/getStarted/cupojava/index.html.

Let’s revisit the code shown in figure 1:

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

To execute the preceding code using command prompt, issue the command java HelloExam, as shown in figure 3.

Image title

Figure 3 – Using a command prompt to execute a Java application

I mentioned how the main method accepts an array of String as the method parameter. But how and where do you pass the array to the main method? Let’s modify the previous code to access and output values from this array:

public class HelloExamWithParameters { 
    public static void main(String args[]) {
        System.out.println(args[0]); 
        System.out.println(args[1]);
    }
}

Execute the class in the preceding code using a command prompt, as shown in figure 4.

Figure 4 Passing command parameters to a main method

Figure 4 – Passing command parameters to a main method

As you can see from the output shown in the preceding figure, the keyword java and the name of the class aren’t passed on as command parameters to the main method. The OCA Java SE 8 Programmer I exam will test you on your knowledge of whether the keyword java and the class name are passed to the main method.

Twist in the Tale Exercise

Here’s a ‘Twist in the Tale’ exercise for you based on executable classes. All chapters in this book, include similar exercises. For these exercises, I’ve tried to use modified code from the examples already covered in the chapter. The Twist in the Tale title refers to modified or tweaked code. These exercises will help you understand how even small code modifications can change the behavior of your code. They should also encourage you to carefully examine all of the code in the exam. The reason for these exercises is that in the exam, you may be asked more than one question that seems to require the same answer. But on closer inspection, you’ll realize that the questions differ slightly, and this will change the behavior of the code and the correct answer option!

In this exercise, and in the rest of the book, you’ll see the names Shreya, Harry, Paul, and Selvan, who are hypothetical programmers also studying for this certification exam. In the book, answer to these exercises is provided in the appendix. For this exercise, I have included the answer, at the end of the article.

_________________________________________________________

One of the programmers, Harry, executed a program that gave the output “java one”. Now he’s trying to figure out which of the following classes outputs these results. Given that he executed the class using the command java EJava java one one, can you help him figure out the correct option(s)?

a)

class EJava {

    public static void main(String sun[]) {

        System.out.println(sun[0] + " " + sun[2]);

    }

}

b)

class EJava {

    static public void main(String phone[]) {

        System.out.println(phone[0] + " " + phone[1]);

    }

}

c)

class EJava {

    static public void main(String[] arguments[]) {

        System.out.println(arguments[0] + " " + arguments[1]);

    }

}

d)

class EJava { 

    static void public main(String args[]) {

        System.out.println(args[0] + " " + args[1]);

    }

}

_________________________________________________________

Answer to Twist in the Tale 

Purpose: This exercise encourages you to execute the code in the options to understand the correct method signature of the method main together with the method parameters that are passed to it.

Answer: a, b

Explanation: All the options in this question are supposed to execute using the command javaEJava java one one. The purpose of each of these terms is as follows:

Term 1: java—Used to execute a Java class.

Term 2: EJava—Name of class to execute.

Term 3: java—Passed as the first argument to the method main.

Term 4: one—Passed as the second argument to main.

Term 5: one—Passed as the third argument to main.

To output “java one”, the main method should output the first and either the second or third method parameters passed to it.

Options (a) and (b) are correct because they use the correct method signature of the method main. The name of the method parameter need not be args. It can be any other valid identifier. Option (a) outputs the values of the first and third terms passed to it. Option (b) outputs the values of the first and second terms passed to it.

Option (c) is incorrect because this main method accepts a two-dimensional array. Hence, it won’t be treated as the main method.

Option (d) is incorrect because this code won’t compile. The access modifier of a method (public) should be placed before its return type (void); otherwise, the code won’t compile.

I wish Good Luck to you with your exam preparation and hope you earn it with flying colors!

-Mala

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:
oca ,oracle ,certification ,java ,java 8

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}