JavaRush /Java Blog /Random EN /Compiling and running Java without an IDE
Ve4niY
Level 14

Compiling and running Java without an IDE

Published in the Random EN group
At one time on reddit.com , in the topic Compiling and running Java without an IDE , the question was asked: Is there a command that compiles a group of Java files that are inside a package into a separate folder (let's call it bin ), and how would I go about starting new class files? " Compiling and running Java without an IDE - 1Topic author, kylolink , explains: "When I started using Java, I relied on Eclipse to do all the compilation for me and was just worried about writing the code." I've seen this question many times, and, indeed, this is what What prompted me to blog post GPS systems and IDEs: good or bad? I love powerful modern Java IDEs and they make my life easier on a daily basis, but there are also benefits to knowing how to build and run simple examples Java without them. This post is about how to do just that. In my blog on learning Java with simple tests, I wrote about how I sometimes like to use a simple text editor and command line tools to write, build and run simple applications. I have a pretty good idea now of how much "overhead" my favorite Java IDEs require and make an early decision as to whether the benefits achieved by using the framework are enough to justify the "overhead". In most real applications, there is no doubt that the VL IDE is worth a lot. However, for the simplest example applications, this is not always the case. The rest of this post shows how to build and run Java code without an IDE for these situations.

Writing and Executing Java Code

To make the example more clear, I'll be using some very simple Java classes that are related to each other through composition or inheritance and are in the same package called dustin.examples . Two classes are missing a function main; the third class, Main.java, has a function mainthat allows you to demonstrate how to run the class without an IDE. Below is the code for these three classes: Parent.java
package dustin.examples;

public class Parent
{
   @Override
   public String toString()
   {
      return "I'm the Parent.";
   }
}
Child.java
package dustin.examples;

public class Child extends Parent
{
   @Override
   public String toString()
   {
      return "I'm the Child.";
   }
}
Main.java
package dustin.examples;

import static java.lang.System.out;

public class Main
{
   private final Parent parent = new Parent();
   private final Child child = new Child();

   public static void main(final String[] arguments)
   {
      final Main instance = new Main();
      out.println(instance.parent);
      out.println(instance.child);
   }
}
The following screenshot shows the directory structure with these .java classes . The screenshot shows that the source files are in the directory hierarchy representing the package name ( dustin/examples because the package information is dustin.examples ) and that this package reflecting the directory hierarchy is under the subdirectory SRC. I also created a classes subdirectory (which is currently empty) to house the compiled .class files so Javac won't create this directory when it doesn't exist.

Building with JAVAC and running with Java

No matter what approach one uses to create Java code (Ant, Maven, Gradle or IDE), it ultimately comes down to JAVAC. The standard options in the Oracle/Sun provided JAVAC command line tool can be seen by running JAVAC -help and additional extension options can be viewed by running JAVAC -help -X. More information on how to use these options can be found in the JAVAC tool documentation for Windows or Unix/Linux. As the Javac documentation says, the -sourcepath option can be used to express the directory in which source files exist. In my directory structure shown in the screenshot above, this means that, assuming I'm running the JAVAC command from the C:\Java\examples\javacAndJava\ directory , I would have to have something like this in my command: Javac -sourcepath src SRC\Dustin\examples\*. Java . The following screenshot shows the results of this. Compiling and running Java without an IDE - 2Because we did not specify a directory for the .class files , they were placed by default in the same directory as the source .java files from which they were composed. We can use the option -dto fix this situation. Our command can be run now, for example, as Javac -sourcepath src -d classes src\Dustin\examples\*. Me you . As noted earlier, the selected folder (classes) must already exist. When this happens, the command will place the .class files in the specified folder as shown in the following screenshot Compiling and running Java without an IDE - 3With the Java source files compiled into corresponding .class files in the specified directory, we can launch the application using the quick launch menu of the Java command line tool. This is simply done by following the instructions provided on the Java -help or Java tools pages and specifying the location of the .class files with the -classpath( or -cp) option. Using both approaches to specify the classes directory where to look for .class files is demonstrated in the following screenshot. The last argument is the full (entire Java package) name of the class that has the main function to be executed. The commands demonstrated in the following screenshot are java classes -cp dustin.examples.Main and java classes -classpath dustin.examples.Main. Compiling and running Java without an IDE - 4

Building and Running with Ant

For the simplest Java applications, it is quite easy to use JAVAC and Java to create and run the application, respectively, as just demonstrated. As applications get a little more complex (for example, code existing in more than one package/directory or more complex dependency classes on third party libraries and frameworks), this approach can become unwieldy. Apache Ant is the oldest of the "big three" Java build tools and has been used in thousands of applications and deployments. As I said in a previous blog post, a very simple Ant build file is easy to create, especially if it starts with a template like I outlined in this post. The following code list is for Ant's build.xml file , which can be used to compose .java files into .class files and then run the class dustin.examples.Main as was done above with JAVAC and Java. build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="BuildingSansIDE" default="run" basedir=".">
   <description>Building Simple Java Applications Without An IDE</description>

   <target name="compile"
           description="Compile the Java code.">
      <javac srcdir="src"
             destdir="classes"
             debug="true"
      includeantruntime="false" />
   </target>

   <target name="run" depends="compile"
           description="Run the Java application.">
      <java classname="dustin.examples.Main" fork="true">
         <classpath>
           <pathelement path="classes"/>
         </classpath>
      </java>
   </target>
</project>
I didn't use the Ant properties and didn't include the common goals I usually include (such as "pure" and "Javadoc") to keep this example as simple as possible and keep it close to the previous example using JAVAC and Java. Note also that I have enabled "debug" set to "true" for the JAVAC Ant task because this is not true in case of Ant failure, but is true with JAVAC's default. Not surprisingly, Javac task and Java Ant task resemble JAVAC command tools and Java. Because I used the default name Ant expects a build file when it is not specified explicitly (build.xml) and because I provided the "Run" target as the "default" for this build and because I included "compile" as a dependency run the "Run" target and because Ant was on my environment's path, all I had to do on the command line was to get Ant to compile and run the ant example in the directory with the build.xml file . This is shown in the following screenshot. Compiling and running Java without an IDE - 5Although I have demonstrated compiling and running a simple Java application with Ant, I tend to only compile with Ant and run with Java (or a script that calls Java if the classpath is heavy).

Building and Running with Maven

Although Ant was the first core Java build tool, Apache Maven eventually gained its fame largely due to its adoption of convention-based configuration and support for shared library repositories. Maven is easy to use when the code and generated objects follow its standard directory layout. Unfortunately, my example does not follow this directory structure, but Maven does allow us to override the expected default directory structure. The following list is code for a Maven POM file that is used in place of the source and target directories and provides the other minimum required elements for a Maven build using Maven 3.2.1. pom.xml
<project>
   <modelVersion>4.0.0</modelVersion>
   <groupId>dustin.examples</groupId>
   <artifactId>CompilingAndRunningWithoutIDE</artifactId>
   <version>1</version>

   <build>
      <defaultGoal>compile</defaultGoal>
      <sourceDirectory>src</sourceDirectory>
      <outputDirectory>classes</outputDirectory>
      <finalName>${project.artifactId}-${project.version}</finalName>
   </build>
</project>
Since the above pom.xml file defines the "defaultGoal" of "compile" and because the pom.xml files are the default POM custom that the Maven executable (MVN) looks for and because the Maven installation bin directory is on my path, only I need to run "MVN " to compile .class files as mentioned in the following screenshot. Compiling and running Java without an IDE - 6I can also run the compiled application from Maven using the Mvn Exec command: Java -Dexec.mainClass = dustin.examples.Main , which is observed in the following screenshot. Compiling and running Java without an IDE - 7As with Ant, I tend not to use Maven to run my simple Java application, but instead use Java on compiled code (or use a script that calls Java directly on long classes).

Building and running with Gradle

Gradle is the newest, trendiest, and stylish of the three major Java build tools. I'm sometimes skeptical about the essence of what's trendy, but I've found a lot of things to like about Gradle (written in Groovy instead of XML, built-in Ant support, built-in Ivy support, configuration by convention that's easy to reconfigure, Maven repository support, and etc.). The following example shows a Gradle build that can be used to compile and run a simple application, which is the main sample code for this post. I presented this adapted example on the Simple Gradle Java Plugin Customization blog. build.gradle
apply plugin: 'java'
apply plugin: 'application'

// Redefine where Gradle should expect Java source files (*.java)
sourceSets {
    main {
        java {
            srcDirs 'src'
        }
    }
}

// Redefine where .class files are written
sourceSets.main.output.classesDir = file("classes")

// Specify main class to be executed
mainClassName = "dustin.examples.Main"

defaultTasks 'compileJava', 'run'
The first two lines from the build.gradle file indicate the use of the Java plugin and the Application plugin, resulting in a bunch of functionality automatically being built into this build. Defining "sourceSets" and "sourceSets.main.output.classesDir" allows you to override the Gradle plugin's default Java directories for Java source code and compiled binary classes, respectively. "MainClassName" allows you to explicitly specify which class should be run within the Application plugin. Line "defaultTasks" defines the tasks that will run by simply typing "Gradle" on the command line: 'compileJava' is the default task provided by the Java plugin and 'Run' is the default task provided by the Application plugin. Because I named the assemblies build.gradle and that's why I specified the default tasks as 'compileJava' and 'Run' and because I have the Gradle installation bin directory in my path, all I had to do to build and run the examples was type 'Gradle' and this is demonstrated in the following screenshot . Compiling and running Java without an IDE - 8Even the biggest skeptic must admit that Gradle builds are very slippery for this simple example. It combines the conciseness of relying on certain conventions and assumptions with a very easy mechanism for overriding defaults when necessary. The fact that it is in Groovy instead of XML is also very attractive! As with Ant and Maven, I tend to build only with these tools and tend to run compiled .class files directly from Java or a script that calls Java. By the way, I tend to also archive these .classes into a jar for launch, but that is beyond the scope of this article.

Conclusion

An IDE is often not necessary to build simple applications and examples and can be even more expensive than it costs to build simple examples. In such a case, it is quite easy to use JAVAC and Java to directly build and run the examples. As examples of becoming more involved, a build tool such as Ant, Maven, or Gradle becomes more attractive. The fact that many development environments support these build utilities means that a developer can migrate to the IDE using a built-in tool created earlier in the process if it was determined that IDE support was needed as a simple application grew into a full-fledged project.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION