What's wrong with this java program below

Compile and run Java programs

Javaschubla.de - Java as the first programming language

This lesson introduces the first simple Java program and explains how to compile and run Java programs.

Preparatory work under Windows

The prerequisite is that the PATH variable has been changed as described. In addition, the following settings should be made:

  1. Open any folder (e.g. by double-clicking on My Computer)
  2. click on Tools> Folder Options (in Win9x View> Folder Options)
  3. Select View (the middle of the three tabs) and make the following settings
    • Allow filenames in capital letters
    • DO NOT hide the file extensions of known files

No preparatory work is necessary under Linux.

Here we go

You start a text editor (Notepad, Editor, TextPad, UltraEdit, kate, gedit, emacs, vi or another program that can save "plain text") and type in the Java program. Under no circumstances use Wordpad, Word or OpenOffice, because if you saved the file with formatting, it would be unusable.

The following program will be easy Hello World! output in the DOS window / on the console:

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

The file and class name

You save it under the name of the main class, so here HelloWorld.java. (Depending on the Windows version, it may be necessary to put quotation marks around the name when saving, so that Notepad / Editor does not append .txt.)

The name must not contain any spaces or special characters (except for _ and $, which are also undesirable). Umlauts are allowed, but should be avoided if you are not the only one who will use this class, otherwise problems can arise on other operating or file systems. Warning: Java is different Large and lower case! HalloWelt, Hallowelt, hallowelt and HALLOWELT are 4 different classes / programs for Java.

Compile (javac)

Now we have to use the Java compiler, called javac, to convert the source text file HalloWelt.java into a byte code file HalloWelt.class.

javac is a command line program, i.e. we first have to open a DOS window (under Windows) or a console (under Linux).

Windows: MS-DOS Prompt (Skip)

The MS-DOS prompt (DOS prompt, DOS window, DOS box) is located under Start> Programs or Start> Programs> Accessories, depending on the Windows version. You can also go to Start> Run and enter it under Windows 9x / ME or under Windows NT / 2000 / XP.

Now you can see a DOS window, a black window with white letters. It will probably say there

C: \ Windows>

or something similar. This is the command prompt or prompt. You now have to change to the directory in which the HalloWelt.java file is saved. You can change directories with the command cd (change directory). With cd .. you go one level up (with cd ... two levels etc.). For example, if the java file is in the C: \ Java directory, enter

cd .. cd java

(and of course presses Enter). If the java file is in the D: \ Java directory, the drive must first be changed. You just give it

D:

one, and then like above

cd java

Around directory names with spaces you have to put quotation marks, e.g.

cd "My Documents"

One way to quickly switch to a folder is to type cd (with a space after cd) and then drag the folder icon from the upper left corner of the folder window into the DOS window.

If you have now navigated to the directory with the HalloWelt.java file, you can (for directory) - this will list the files in the directory, there should also be HalloW ~ 1.jav or HalloWelt.java.

Linux: Console (Skip)

Most Linux users have probably used the console at some point. If not: look for Console, Terminal (also X-Terminal or GNOME-Terminal is correct), Shell or Bash in the menu under System. Depending on the system, the terminal window is usually either black with white letters or white with black letters, but there are also other colors and translucent windows.

Depending on the system, this window will say something like

username @ computername: ~ $

Username is the name with which you are currently logged in, the computer name was usually assigned during the installation. ~ stands for the home directory, the current directory always appears there. The $ is the prompt. Depending on the system, the user name and / or the computer name and / or the current directory may not be displayed, so that only the prompt may be displayed. Instead of $, the prompt can also be%, # or another symbol.

You now have to change to the directory in which the HalloWelt.java file is saved. You can change directories with the command cd (change directory). With cd .. you go one level up (with cd ../ .. two levels etc.). Note the space after cd.

For example, if the java file is in the / home / username / myjava directory, enter

cd myjava

(and of course presses Enter). Around directory names with spaces you have to put quotation marks, e.g.

cd "My Java Files"

or escape the spaces with a backslash (\):

cd My \ Java files

You can get to the desired folder faster if you just type the first few letters and then press the tab key (this is the key to the left of the Q with the two opposite arrows). Under KDE it is also possible to right-click in Konqueror and choose Action -> Open Terminal.

If you have now navigated to the directory with the HalloWelt.java file, you can (for list) - this will list the files in the directory, there should also be HalloWelt.java.

javac

You are now in the DOS window / console in the correct directory with the HelloWelt.java file to be compiled. Just now

javac HelloWorld.java

enter.

If there is no error message and the command prompt simply appears again, everything is fine. If not, you should check whether you wrote javac and not java, thought of the .java at the end and did not make any other mistakes. Typical sources of error in the program text that need to be checked: Upper and lower case (string, not string, system, not system), the semicolon (;) after System.out.println ("Hello world!") And that both before also after Hello World! there is a quotation mark (Shift + 2).

So if all goes well, a file called HelloWorld.class will appear in the same directory. This is the byte code file. It can now be passed on and run unchanged on Windows, Linux, Mac and Solaris computers. (If there are multiple classes in the .java file, multiple .class files are created.)

Run (java)

Now, of course, we want to run the file too. The JRE (Java Runtime Environment) or JVM (Java Virtual Machine, contained in the JRE) is responsible for this. This is simply called up with the command.

So you enter in the DOS prompt or in the console

java HelloWorld

a. (Make sure that it is called java, not javac, is case-sensitive, and that it is simply HelloWorld, not HalloWelt.class or HalloWelt.java.)

Now the program is executed and it appears in the DOS window / on the console. Then it ends immediately and the command prompt follows again.

Changes

If you change something in the program, you have to recompile it (with javac) before executing it (with java). There are development environments like Eclipse that do this for you, so all you have to do is press a button, but for starters we want to do it by hand.


Exercise 1

Build in errors and look at (and if possible remember or even write down) what kind of errors the compiler outputs which error message. Then it will be much easier to deal with the error messages later. So just try out what either the compiler or the JRE says first

  • if you do that; omits
  • if you accidentally enter; behind public static void main (String [] args)
  • if you write class instead of class
  • if you write main instead of main
  • if you write string instead of string
  • if you write system instead of system
  • if you leave out the [] after string
  • if you have one {and / or one} too much or too little (it is best to try all combinations, the error messages are very confusing and you should definitely know later that you should look for your curly brackets for such errors)
  • if you just write lgjklgja in different places
  • if you forget the first, the second or both quotation marks

args (for arguments) can be renamed as you like, some people write argv, and you could also use hugo. It's just a variable name. args is most common.

exercise 2

You can not only output strings (character strings, enclosed in quotation marks), but also, for example, calculations. Try something

System.out.println (1 + 2); System.out.println (1-2); System.out.println (3 * 4); System.out.println (12/4); System.out.println (12.345 / 3.4);

There are no quotation marks! would 1+2 spend while 3 issues.

You can put any spaces around numbers and operators, for example

System.out.println (1 + 2);

These are not included. They would only be output if they were within a string, i.e. between two quotation marks, e.g. the space between Hello and World!.

stands for print-line, i.e. output and go one line lower. You can also use, then the next output comes on the same line.

System.out.println ("Hello"); System.out.println ("World!");

gives

Hello World!

off while

System.out.print ("Hello"); System.out.println ("World!"); Hello World!

issues.

Try it a little. Most of the time, it will help you get comfortable with compiling and running.

Exercise 3

Call the Java API that you either downloaded or from which you saved the link. In case you forgot to do that, use this link: Java API. At the top left is a small frame with the packages, at the bottom left is a longer frame with the classes and interfaces in the current package (as long as no package has been selected, all Classes and interfaces), on the right is a large frame with the currently clicked class (or interface, at the moment still package overview). Select the package java.lang in the top left. This is the standard package that is always imported automatically. In the frame at the bottom left you will find the String class. You will also see the System class there. Click on them. It appears on the right. There you can see that it has an attribute called. Click on the type in front of it, so on. You get to class. There you can see that this class has many and methods (functions).


Explanations of the HalloWelt program (skip)

You just have to remember it first

  1. that you are spending something on the screen
  2. that you wrap your commands in one
  3. that you put a semicolon after each command.

But some readers may now be plagued with curiosity about what the rest of them mean. As I said, it doesn't matter if you don't understand it exactly at the beginning, there are some things you can't understand at all now.

public static void main (String [] args)

With

Return type name(Type1 name1, Type2 name2, ...) {... commands here ...}

you define a method (= function, procedure, subroutine, subroutine, ...) with the name Surname, the return type Return type and the parameters name1, name2, ... of the type Type1, Type2, ...

For example

void main (String [] args) {...}

is the name of the main method, its return type is void (meaning that it Nothing returns), it receives a parameter named args of type String-Array (String []). Incidentally, this parameter contains the arguments passed on the command line (command line parameters).

public is an access modifier, the public means. There are also private, protected and if you don't write anything down, "package level access".

static you can only understand if you understand object orientation a little. You can easily access a static method or variable via the class name, you don't have to create an object first. When the program is just starting, there are no objects yet, so main must be static. (This is different with applets, whose methods are not static, there is an applet object from the start.)

When you call up, the JRE searches in the Classname.class a method with the name main, return type void and a parameter of type String [] and calls it.

Convention: Method names are capitalized, but inner words are capitalized, e.g. lastIndexOf. This is called a camel case.

class

Everything in Java is made up of classes. A class is a program, a collection of methods, a type, a data structure, and more.

With

class Class name {... variables here ... ... methods here ...}

you define a class called Class name. In the example we have defined a class called HelloWorld.

Convention: Class names are capitalized, as are inner words.

System.out.println

Like String, System is one of the predefined classes in the standard package java.lang. You don't have to explicitly import this package, it is always imported automatically. You could also have written java.lang.System.out.println and java.lang.String [] (but you don't).

out is a variable in the System class. It is of the type PrintStream. (PrintStream is a class in the java.util package.)

println () is a method in the PrintStream class.

Convention: Variable names (like out) are written in small letters, inner words in capital letters.

Constant names are written in ALL_CAPS (completely capitalized with underscores for subdivision). Otherwise no underscores are used for subdivision.


To notice

  1. Classes are (among other things) programs. The simplest form of a program is: class Class name {public static void main (String [] args) {... Instructions here ... } }
  2. prints something and goes one line below, prints something without going a line below.
  3. A semicolon (;) follows an instruction.
  4. You compile with and execute with.
  5. Capitalize class names and capitalize inner words (CamelCase)
  6. You indent after an opening curly bracket (e.g. by two spaces) and after the closing curly bracket you indent by the same number of spaces.
  7. Java distinguishes between upper and lower case letters.

The next lesson is about special characters in strings