What are the first steps of programming

The first steps to Java programming

Martin Kompf


Basic tools

In order to be able to program in Java, you need at least the following tools:

  • A text editor to create the source code,
  • The Java SE Development Kit (JDK) for translating the source code into bytecode,
  • The Java SE Runtime Environment (JRE) to run the bytecode.

The abbreviation “SE” stands for “Standard Edition”. This is the most widely used Java edition for desktop applications. There is also a Micro Edition (ME) for embedded devices and an Enterprise Edition (EE) for corporate applications, which are not the focus of this beginner's tutorial.

Text editor

The text editor is used to create the Java source or source code. It is difficult to recommend a suitable text editor because personal preferences differ widely. In addition to the reliable function, you should pay attention to certain comfort features such as multi-level undo / redo, search and replace, colored syntax highlighting and so on.

A very incomplete list of suitable and free text editors is:

  • Vim - Powerful text editor for a variety of platforms including Unix and Windows.
  • gedit - Official text editor of the GNOME desktop with easy handling
  • Notepad ++ is an open source editor that supports a large number of programming languages ​​under MS Windows.

The organization of the work area

As a simple example in the context of these instructions, a small program will serve that outputs "Hello" followed by the login name of the user:

package de.kompf.tutor; / ** * Simple java program to greet the user. * / publicclass Hello {/ ** * MAIN * @param args ignored * / publicstaticvoid main (String [] args) {Hello hello = new Hello (); hello.greet (); } privatevoid greet () {String user = System.getProperty ("user.name"); System.out.println ("Hello" + user + "!"); }}

The program must therefore be entered in the text editor and then saved. When choosing the storage location and generally the organization of the work area, however, one should proceed in a planned manner. One possible way to do this is:

  • Each Java project gets its own directory in the file system, for example firststeps.
  • The folders src and am created. It contains the source code files or the bytecode generated from them. Later you can find other directories here, such as doc for documentation, lib for libraries and so on.
  • Below the folder src A directory structure must be set up that corresponds to the package structure of the Java project. This means that even large projects can be structured well. Each Java class belongs to a package, the name of which is specified by the directive at the beginning of the source code file. The example belongs to the package. The source code file then belongs to the directory de / kompf / tutor below src.
  • The name of the source code file corresponds to the class name followed by the extension .Java. In the example, the file name is Hello.java.
  • Please note that all names are case-sensitive. On Windows systems the directory separator is / by \ to replace.

In summary, this leads to the following structure of the work area in the example:

firststeps | + - am | + - src | + - de | + - compf | + - tutor | + - Hello.java

The Java SE Development Kit

The most important component of the Java Development Kit (JDK) is the Java Compiler javacwhich translates the source code into bytecode. This bytecode is platform-neutral, which means that it can be executed on a wide variety of operating systems. However, this requires the Java Runtime Environment (JRE) on every target platform, the most important components of which are the Java Virtual Machine (JVM) and the Java Standard API.

The JRE is part of the JDK, so that a Java developer only needs to install the JDK. For an end user who only wants to run Java programs, however, the installation of the JRE is sufficient.

There are a number of different manufacturers of JDKs. Only the implementation by the Java inventor Sun is recommended for beginners. The current JDKs for Windows, Linux and Solaris can be found on the download pages of java.sun.com. The complete JDK documentation is also available here and should be downloaded at the same time. Linux users should take a look at the package manager of their distribution beforehand; the current JDK may even be available there. For example, under Debian Lenny the corresponding package is called sun-java6-jdk.

After installing the JDK and unpacking the documentation, a first test is due. To do this, open a command prompt or a terminal and determine the versions of the JVM Java and the compiler javac:

java -version javac -version

It is important that the version numbers of Java and javac to match. This test regularly fails under Windows because after a standard installation only the JRE is in the search path and javac then is not found. This can be remedied by setting the environment variables and:

set JAVA_HOME = C: \ Program Files \ Java \ jdk1.6.0_13 set PATH =% JAVA_HOME% \ bin;% PATH% java -version java version "1.6.0_13" javac version javac 1.6.0_13

This is only an example, the exact paths depend on the installed Java version and must be adapted accordingly!

must point to the directory in which the JDK was installed and is about the am Expand directory of JDK. Under Unix, the syntax for setting the environment variables must be adapted to the shell used, for example for Bash:

export JAVA_HOME = / usr / lib / jdk1.6.0_13 PATH = $ JAVA_HOME / bin: $ PATH

If - as suggested above - the JDK has been imported via the package manager of the Linux distribution, this step should not be necessary at all.

Compiling with javac

After this preliminary work, the first Java program can finally be compiled. To do this, switch to the project directory set up above firststeps and calls the Java Compiler.

javac -d bin src / de / kompf / tutor / Hello.java

The specified source code file is then compiled, the bytecode is specified in the directory using an option am filed. The bytecode file bears the name of the Java class followed by the extension .class. The folder structure again corresponds to the package structure. This creates the file in the example bin / de / kompf / tutor / Hello.class.

Run with java

The JVM behind the program is required to execute the bytecode Java hides:

java -cp bin de.kompf.tutor.Hello Hello Martin!

The program Java gets the name of the class passed with the method. Mind you, it is the name of the class including the package and not the file name! That is why the point is used as a separator and there is no file extension.

The option denotes the Classpathin which the .class Files are searched. This can be a list of directories or JAR files (more on that later). The components of the list are separated with the platform-specific PATH separator, i.e. semicolons ; under Windows or colon : under Unix.

Packaging with jar

If all tests are successful, you might want to make your new Java program available to other people. It is possible, but also very time-consuming and error-prone, to have the complete directory structure below the am Distribute directory. A more suitable form of distribution is to pack all required files together in an archive, the JAR File. The tool is used for this jar:

jar cvfe firststeps.jar de.kompf.tutor.Hello -C bin.

Parameters of the call to jar are the name of the JAR file to be created, the name of the class with the method, the directory with the .class Files and the list of files. The point used here . stands for all files in all subdirectories.

The JAR file created in this way can be accessed again using Java are executed. You only have to specify the name of the JAR file, the name of the main class is already there (by calling jar) firmly anchored in the archive:

java -jar firststeps.jar Hello Martin!

The JAR file with the bytecode it contains is platform-independent. It is not a problem to run the JAR on any operating system, as long as a JRE is available there. This is a big advantage of Java compared to programming in C or C ++!

The examples show only a small part of the possible options of the tools javac, jar and Java presented. Complete documentation is available in the JDK documentation, section Tool Docs.

Automation with ant

The compilation, execution / testing and packaging steps presented in the last chapter are typically carried out over and over again during software development. This is annoying and error-prone, especially with larger projects with many source code files, you can quickly lose track of things. Automating the process can help here.

The Tool for automating build processes in the Java environment is Ant. It is also implemented in Java itself and can therefore run on all platforms supported by Java.

You can use the distribution's package manager again for installation under Linux. The corresponding package is called Debian Lenny ant.

Otherwise (under Windows) you have to download the distribution from http://ant.apache.org/ and unpack it into an empty directory. Then the environment variables have to be set so that they contain the path to this directory. Also needs to be expanded by. For example:

set ANT_HOME = C: \ Program Files \ apache-ant-1.6.2 set PATH =% ANT_HOME% \ bin;% PATH%

Ant is controlled via a project-specific build file in XML format. The default name for this file is build.xml and is located directly in the project directory - in the example in the directory firststeps. Ant's way of working can best be seen in an exemplary manner build.xml illustrated:

<project name="firststeps"default="compile"basedir="."><!-- The main class of the project --><property name="main.class"value="de.kompf.tutor.Hello"/><property name="jar.file"value="${basedir}/${ant.project.name}.jar"/><property name="src.dir"value="${basedir}/src"/><property name="build.dir"value="${basedir}/bin"/><path id="run.classpath"><pathelement path="${build.dir}"/></path><target name="init"><mkdir dir="${build.dir}"/></target><target name="compile"depends="init"description="compile"><javac srcdir="${src.dir}"destdir="${build.dir}" /></target><target name="run-hello"depends="compile"description="Run the program"><java classname="${main.class}"classpathref="run.classpath" /></target><target name="jar"depends="compile"description="Create a jar file"><jar destfile="${jar.file}"><fileset dir="${build.dir}"/><manifest><attribute name="Main-Class"value="${main.class}"/></manifest></jar></target></project>

The outer bracket forms the element project. There are several targets declared. A target stands for a specific, self-contained task, such as compiling (target), executing () or packaging (). You can get an overview of all targets by entering:

ant -p Main targets: compile compile jar Create a jar file run-hello Run the program Default target: compile

This only works if the build file has the name build.xml and is located in the current directory. Otherwise you have to pass their name via the command line option.

A target can be executed directly by entering followed by the name of the target:

ant jar

If the target is omitted, the default target is executed, which is specified in the attribute default of the element project was defined.

Targets can be dependent on each other, this is indicated by the attribute depends marked. When the target is executed, it is first called internally, which in turn executes first.

There are one or more within a target Tasks. You determine what ultimately happens when the target is processed. In the example, the target calls the task. A list of all tasks built into Ant and the associated attributes can be found in the Ant manual. The extensive palette ranges from operations in the file system, working with archives, compiling and executing programs to sending e-mails.

The presented minimum build.xml can be used as a starting point for your own projects. In order to keep changes to a minimum, variable parameters were saved at the beginning of the file as property Are defined. For example, the property contains the name of the main class. The build file then refers to this property at various points by means of the construction.

Integrated development environments

Despite the automation with Ant, the procedure described so far is still tedious for larger projects. The constant change between text editor and command line, missing cross-references between different source code files and imperfect input aids such as automatic source code completion are annoying and time-consuming.

This can be remedied by using an integrated development environment (IDE). Well-known and free IDEs in the Java environment are

Both IDEs are equally extensive and powerful, but sometimes differ considerably in terms of concept and operation. You should try both once and then commit to an IDE.

Getting started with Eclipse

An installed JRE is required to operate Eclipse. Nevertheless, the IDE is not a pure Java implementation, so you have to select the appropriate operating system on the download page. The “Eclipse IDE for Java Developers” package is the right choice for development on the basis of Java SE.

Under Debian Lenny you can also handle the installation of Eclipse via the package manager, the package is called eclipse and installs the outdated, but sufficient version 3.2 of the Eclipse platform including the Java Development Tools.

After starting, Eclipse asks you to select the workspace directory. The projects will later be created under this directory. You can accept the standard setting - when you start Eclipse for the first time, the «Welcome» page will appear.

A new Java project is created using File - New - Project - Java Project at. A wizard appears in which you should at least enter the project name - for example firststeps. A separation of source and bytecode is also recommended; this is achieved by selecting the option Create separate source and output folders.

The newly created project now appears in the Package Explorer of the Java perspective. By File - New - Class you can create a new Java class. As a package you wear de.kompf.tutor and as a name Hello a. Now the new class appears in the Package Explorer and a Java Editor window opens. The Java source code from the example above can be entered here. When saving with a key combination, the class is automatically compiled immediately and any errors are displayed. If this does not happen, one should make sure that the option Project - Build Automatically is switched on.

The Java program can also be executed directly in the IDE by selecting Hello.java Right-click in the Package Explorer and select from the context menu Run As - Java Application out.

The possibilities of Eclipse are so extensive that they would go beyond the scope of this beginner's tutorial. Therefore, at this point only the reference to two interesting and frequently used features:

By activating the button, class, method and variable names are transformed into links when the mouse is hovered over them. When you click on it, you immediately get to the declaration of the corresponding class, method or variable.

The Code completion makes suitable suggestions for completing the program code while typing when activating the key combination:

With the methods described here, it is possible to set up development environments with different levels of performance and convenience for Java programming. Although the combination of editor plus JDK is sufficient for smaller projects, every developer will later use an IDE such as Eclipse or NetBeans. However, tools like Ant are indispensable when it comes to automating build processes as they are indispensable in software product development and teamwork.