Where can I make my Java code

17 Switching to Java (IntelliJ)

Last update: 04/11/2018
Treated commands: static main method, System.out.println, public, private, protected, Javadoc, import

learning goals

  • Create and start projects in the IDE IntelliJ
  • Create Java classes with access modifiers and, if necessary, getter and setter methods
  • Create an executable Java program

In this chapter we move up from Processing Java around. We also get to know a professional development environment (IDE), IntelliJ IDEA (short: IntelliJ), which will make our lives easier in the medium term.

Why do we have to switch to "Java" at all? Isn't Processing Java? Processing is just almost java. Processing uses a library of additional functions and a medium-sized "magic trick" to make your life easier. The magic trick is that all of your programs are actually a subclass of the PApplet class. When you program in Java, on the one hand some functions are no longer available and on the other hand you have to learn things like "How do I start my Java program?"

We also want to learn this semester Android devices to program. Why? Because you program completely in Java and we can (almost) already. And why Android and not iOS (Apple)? In 2017, Android climbed to over 85% market share in the mobile sector, i.e. smartphones and tablets.

To make the switch to Android easy for us, we use the IntelliJ development environment, because the development environment for Android (Android Studio) is based on IntelliJ.

17.1 IntelliJ and Java

An "Integrated Development Environment" (IDE) combines various services in a single program with a stylish interface. Some of these services are:

  • Write code: make an editor available, provide completion suggestions while typing (code completion), quickly navigate through the code
  • Compile and run code: Code is compiled, program is started, console output is displayed, program can be interrupted at any time
  • Debug code: run through the code line by line and see the current state of variables
  • Code refactoring: Rename classes, methods and variables, replacing all occurrences of the construct in question with the new name

IntelliJ is just one of several IDEs that can be used for Java. A good reason to choose IntelliJ is that Google chose IntelliJ as the basis for the Android development environment Android Studio (since 2015).

There are of course other IDEs. The two best known are NetBeans and Eclipse. Netbeans is the "official" IDE of the company that is currently developing Java: Oracle. Eclipse is similar to NetBeans and has more of the "independent" character and is known for its countless plugins. NetBeans and Eclipse are both free.

Installation of Java

To be able to program in Java, you first need Java SE (SE for Standard Edition). Java has been in Version 10 in front. If this is not already installed on your computer, go to the Java Downloads page and download and install the JDK (Java Development Kit, not to be confused with JRE).

I also recommend you the API documentation Download the Java classes and bookmark them in your browser. To do this, you have to click the download button on the Java Downloads page for "Java SE 10 Documentation" (relatively far below). To open the API, click the index.html File.

Another technical note: Never use umlauts (ä, ü, ö) or the sharp s (ß) in the code. Of course, you can use umlauts in strings or comments, but not for class, package, method or variable names. Unfortunately, umlauts always cause problems.

Installation of IntelliJ

Then install IntelliJ. To do this, download the free Community Edition (CE) in the download area. Then install the software and start IntelliJ.

Create Project

What is a "Sketch" in Processing is a in IntelliJ Project. Like a sketch, a project is saved in its own directory. Select in the main menu File> New Project ... and a dialog box will appear to guide you through the process.

The first thing you need to say is IntelliJ where is your java. (If you already have something with "java" in the "Project SDK" line, you can simply skip this point with "Next".)

On one Mac does it look like this.

Under Windows is it somewhere under Programs> Java

For any intermediate steps, simply press "Next" without marking anything!

Now give your project one Names and change that as needed directorywhere to save the IntelliJ projects.

Done! IntelliJ shows you the integrated interface. You will see two panes for the code (right) and for the project directory (left).

Located in Java each class in its own file with the extension .java (the file must be named exactly like the class!). In the project directory you will see a subdirectory "src". This is where all of your classes go in.

Create a new class by right-clicking on "src" and New> Java Class choose.

The class then appears in the project directory under "src". You can now write the code for the class "Foo" in the right area:

We'll find out what the code means in a moment ...

Entry point with main

An important difference between Java and Processing is: In Java, a program consists only of classes, there is no "main program" and no setup () or draw (). If there is no main program, the question arises: What code is executed when we start our program? So where is that Entry point, from where the program lines are processed?

The answer is: You create a special method in one of your classes that Java uses as an entry point. This method is called thestatic main () method. It must have the return type and a string array as a parameter. Let's say you define this method in the class. Then you can tell Java to "start the Foo class". Java looks for the main () method in the class and, if it exists, it is executed.

What does "static" mean? In Java, static means that a method can be executed even though no object of the class exists. Usually a method can only be executed on one object. Imagine a class "Person" with the method "getFullName ()". The method can only be executed on specific objects, not on the class. The main () method, on the other hand, does not belong to any object, but to the class. Static methods are also called Class methods.

System.out.println

We just want to print a string when we start MyClass. In Java there is unfortunately no simple "println" like in Processing. Instead, write:

System.out.println ("hello");

The meaning of this expression is as follows: is a class that Java provides by default. This is a variable of the class System, but one static variable (see above), which is why you can also call it on the class. The variable out contains an object of the type. PrintStream provides the commands and, as you can read in the Java API.

In order to save you paperwork, there are so-called in modern IDEs Templates, these are very common code parts that can be activated with the first letters of the words. At IntelliJ that means Live templates: you can find more about this in the documentation). You type in an abbreviation, e.g. "sout" for "System.out.println" ...

... and then press the tab key (or ENTER). IntelliJ replaces the abbreviation with code:

Now let's write the text:

Start the program

And start the program with the green play button in the toolbar.

Pressing the play button solves both that Compile of the code (translation into machine language, more precisely: bytecode) as well as that Start of the code (more precisely: the main method in MyClass).

In the lower right part the now also appears consolethat you also know from Processing.

You have written your first Java program!

Summary

  • A program is called a Project managed (own directory)
  • A Java program is a collection of classes
  • Each class corresponds to a file (with the extension .java) in the "src" directory, which has exactly the same name as the class
  • A class can do a static main method then you can start this class
  • static means that the method / variable belongs to the class and not to an object
  • Console output takes place with System.out.println
  • IntelliJ provides code templates for faster coding (complete list), for example "sout" (then tab key) for "System.out.println ()"

Exercises

17.1 a) (a) Hello world

Start IntelliJ and start a new project Hello at.

Write the class. Put one there static main method at. In this method, say "Hello, world!" out.

17.2 Classes in Java

We approach Java by writing a second program. To do this, we create a "SecondTimeJava" project.

Packages

Java offers "packages" to better organize your classes. Packages can be nested like directories. It is recommended that you set up a package right from the start. We call ours "fancyproject". Note that package names completely in lower case to be written.

The new package is shown within "Source Packages". If you are creating a new class, highlight the package and then right click:

We create the class (toys). You can see the line at the very top of the code

package fancyproject;

This indicates that the class is in the "fancyproject" package:

Sub-packages

You can get packages and Sub-packages invest. A sub-package is simply appended to the parent with a period.

Create a second package that consists of two sub-packages. You can enter directly when creating a package:

de.hsa.toyproject

Create a class in the package.

You can see that in the code under the "Path" is written with dots. But on your hard drive for each sub-package created a subdirectory. That means the file is under

src / de / hsa / toyproject

Take a look at the directory "src" and the corresponding subdirectories in your file explorer.

Access modifiers

We create three instance variables:

public class toy { private String description; private int serial number; private double price; }

You will notice the terms and. These are access modifiers (also: visibility modifiers). These terms indicate who can access this class or the variables.

The term means: Everyone can access the class / variable, in particular other objects can access it. In the case of variables, this means that only an object of this class can access them.

There is one more modifier. With this modifier, the subclasses can also access the variable (and also all classes within the same package).

The following table summarizes who has access to a class, constructor, method or instance variable:

modifierOwn classSubclassesClasses in the same packageAll classes
X   
XXX 
XXXX
X X 

You can also see here what happens if you omit the modifier entirely ("empty"). This case is called package-private. The subclasses have no access here, but all classes in the same package do. This combination rarely makes sense, so you should always write down a modifier.

Now let's create a constructor. IntelliJ offers you an automatic system that you can use with Code> Generate ... or with a key combination specified there or with a right click (in the code) and Generate triggers. Then select "Constructor ...":

IntelliJ asks you which of the three instance variables you would like to have as parameters in the constructor. Select all three (click together with SHIFT or CTRL or CMD on the Mac). Then OK.

IntelliJ produces a textbook-like constructor:

Getter and Setter Methods

In Java, the visibility of a variable plays a major role. The rule of thumb for instance variables is: If in doubt, declare each instance variable as "private".

Private variables are not allowed to be touched even by subclasses. How do you then manipulate the variables from the outside? For example this one:

private String description;

Very simple: you define methods to manipulate the variables. To get the value, one defines one Getter methodwhich is of course "public" and can therefore be accessed from anywhere.

public string getDesignation () {return label; }

To change the value, one defines one Setter methodthat gets the new value as a parameter:

public void set description (string b) {label = b; }

IntelliJ relieves us of the hassle of writing the same getter and setter methods. Again we solve that Generate ... Menu. This time we take "Getter and Setter ..."

In the next step you say which instance variables you want to make accessible via getter and setter:

Finally, you will see the generated code, which of course you can freely edit or delete.

Static main

We'll write a class to manage toy objects, including adding toy objects and printing them out.

package fancyproject; import java.util.ArrayList; / ** * @author Michael Kipp * / public class ToyAlbum {private ArrayList toys; public ToyAlbum () {toys = new ArrayList (); } public void addToy (Toy toy) {toys.add (toy); } public void printToys () {for (Toy toy: toys) {System.out.println (toy); }}}

Finally we write a static main method. Use the useful code template here psvm for "public static void main (String [] args)":

public static void main (String [] args) {ToyAlbum album = new ToyAlbum (); album.addToy (new Toy ("Lonny", 25001, 29.95)); album.addToy (new Toy ("Donny", 25002, 31.95)); album.addToy (new Toy ("Bonny", 25003, 79.95)); album.printToys (); }

In the main method we create a ToyAlbum object and add some test objects. Then we print out all objects. Press the IntelliJ Run button.

We see the property issues. To make it more informative, we'll add a toString method in the Toy class.

public string toString() {return description + "," + serial number + "," + price + "EUR"; }

Now we have a meaningful output:

Import classes

Let's say we want to store a list of toy objects.Although the class is part of the Java standard library, it cannot simply be used, it must be usedimported become. This is done by the command that must still be above the class. Fortunately, IntelliJ supports us in this.

You type your code and see the error message (red underline appears, then hold the mouse over the lightbulb on the left).

Press CTRL-ENTER to get the following context menu and choose Fix imports. (Alternatively in the main menu underSource> Fix Imports ...)

You can now see the "import java.util.ArrayList" above the class. this is the full class name. You can see that the class is located in a package called "java" and there in the subpackage "util". Packages and sub-packages are separated by periods.

Another useful feature is code completion. Whenever you're typing a command, class, or variable name, you can always press CTRL-SPACEBAR and IntelliJ will make suggestions on how to complete it.

Exercises

17.2 a) (a) First program

Start IntelliJ and start a new project FirstProg at.

Put the package de.hsa and look at the directory structure in src in your file explorer or finder.

Write the class. Put one there static main method at. In this method you create a ArrayList of strings and fill in with 5 sample strings. Then output the strings on the console using a foreach loop.

tip
Remember to include ArrayList too import! See the script above for how to do this.

Summary

  • Packages are like directories for classes. You should always define an initial package. You can use the same class name in two different packages. The package comes in Java code with package specified.
  • In Java, the Access modifiers public, protected and private used for classes, instance variables, constructors and methods.
    • public: all objects can access it
    • protected: only objects from subclasses and from the same package can access
    • private: only objects of the same class are allowed to access (especially objects of subclasses Not access
  • Instance variables should always private be. For public access to instance variables one can useGetter and Setter Methods write, which are then public.
  • Classes and Constructors are always public (With constructors there are cases where private access also makes sense).
  • Methods are public if they should also be accessible from other classes. They are private if they are only used for clarity within the class and are only called up within the class.
  • There is a subdirectory in the project directory src the source code: packages are shown there as nested directories. Code files have the extension .Java.
  • With Javadoc specially formatted comments are transferred to the overall documentation as HTML pages. Javadoc comments are bracketed with and.
  • In Java, in contrast to Processing, usually uses the type double for floating point numbers (and not float).

17.3 Documentation

Directory structure

If you go to the directory where an IntelliJ project is stored, you will see the following (after starting your program at least once):

The main directory is src, Short for "source code", meaning source code, these are your class files, all of which have the extension .Java to have. There is a subdirectory for each package that you have created, i.e. you have a subdirectory "fancyprojects" in which the files "Toy.java" and "ToyAlbum.java" are located.

In the register out the files translated into bytecode are saved. There is a directory structure that is analogous to the source code, except that each class file has .class ends. (In other tools, this directory is often called "build".)

The file with the extension .iml contains setting information for your project.

Comments and Javadoc

In Java, comments can be used in such a way that comprehensive code documentation can be generated from them in the form of web pages. For example, the documentation for the Java standard library was created in exactly the same way.

The tool that converts the comments into HTML documentation is called Javadoc. Not all comments are used for this documentation, only those that are directly in front of a class, instance variable, constructor or method and that look like this:

/ ** * This is my first grade. * * @author Lisa Schmidt * / public class MyClass {...}

The double asterisk at the beginning is decisive. This signals to Javadoc that the comment should be included in the documentation. The special key "@author" allows the authors of the class to be inserted. Such information is placed in specific places in the HTML documentation.

For one method it looks like this:

/ ** * Calculates total. * * @param a first summand * @param b second summand * @return Sum of a and b * / public int computeSum (int a, int b) {return a + b; }

The keywords and are extensions of the comment that allow Javadoc to create more detailed documentation.

You can run Javadoc on your own project using Tools> Generate JavaDoc. You then have to do this under "Output directory" directory specify where the corresponding documentation pages (HTML) are to be created. A good place would be a subdirectory called docthat you have to create in your project directory.

Javadoc generates several HTML files which IntelliJ then opens. The files can be found in the subdirectory that you specified / created.

If you change / expand your comments in the code, you have to call the "Generate JavaDoc" again to update your documentation. It doesn't happen automatically.

Use Java documentation

The evolution of the language is fascinating in that much of the language is written in Java itself. The developers of Java wrote classes like or and added them to the language. A collection of classes is also called Library (English library). The classes that are part of the Java language are called the Java standard library.

The Java developers did the above Javadoc used to document the standard library. This documentation is always used when programming in Java.

You can always find the latest Java documentation on the Internet. It is even better to download the documentation from the Java Downloads page and bookmark it in the browser so that you can access it offline.

On the start page you can see all packages (top left) and all classes (bottom left):

If you are looking for a specific class - for example, it is best to use the Search function of the browser (CTRL-F or CMD-F). The browser then searches, among other things, in the class list (bottom left). Once you have found the class, click on it and you will be taken to a new page with the class description.

In the Class description you can see which package the class belongs to, which constructors, which methods it has and much more.

Further down the page you will find the Methodswhich are of course particularly interesting.

One click takes you to a more detailed description of the method.

Refactoring

A "killer" feature of IDEs like IntelliJ is the ability to rename the names of classes, variables, and methods throughout your project without having to search every place where that name comes up. Such an action is called Refactoring (Refactoring generally means rebuilding the code so that it is more robust and easier to read).

Let's say you want to rename the Toy class to Toy. The term toy appears in many places, e.g. at "ArrayList ". With a right click on the class name (no matter where it appears), you get a context menu in which you can Refactor> Rename select (also look at the keyboard shortcut, varies by operating system):

In simple cases you edit directly in the code, in more complex cases, as already here with Toy, a dialog appears asking for the new name.

After pressing Refactor, all occurrences of the name are replaced.

Double instead of float

In Processing we are used to creating variables of the type for floating point numbers. In Java it is Conventionto use the type, i.e. the data type that allows double precision, but also requires twice as much memory (8 bytes instead of 4 bytes).

So you better get used to using it all the time, because all classes from libraries use it and otherwise you have to constantly cast the numbers from type to.

In Java it is used as the standard type for floating point numbers. Try to get used to it quickly and always use!

Exercises

17.3 a) (a) Bookstore

Start a new project BookStore at. To do this, put the package de.hsa.bookstore at.

Create the following classes:

The class Book has the properties and (type: double). Write a constructor that sets both properties and getter methods. Also, write a suitable method.

The BookStore class has an ArrayList of Book objects as a property. The method receives two arguments (string and double), creates a corresponding book object and adds it to the list. Another method is to print the books on the console.

In, write your static main () method. You create an object there and add 3 books. Then call on the object.

Note: In contrast to Processing, Java usually uses the type double for floating point numbers (see above in the script).

Note 2: Actually you should for money (property price)Not use the type double or float because rounding errors occur more often than expected! We are doing this here anyway to keep things simple. If you are interested in sustainable solutions, read the following article, for example, which recommends the Java class: Correct calculations with precision in Java.

17.3 b) (b) Comments

Write Javadoc comments for the BookStore project. Comment out the BookStore and Book classes and the addBook and printBooks methods. Take advantage of this too.

Generate the appropriate JavaDoc document (HTML) and check that your comments are displayed correctly.

17.3 c) (c) Name generator

This task has nothing to do with the above tasks.

Write a class. The class should contain two lists of strings: first names and last names.

Write two methods and with which you can fill the two lists.

The really important method is that generates a new name by putting together a random first name and last name and then returning it.

Note: To do this, you need the Java class, which works a little differently than the mechanism in Processing. Check the current Java API documentation to see how it works.

Test your program with the following code (in your static main):

NameGenerator gen = new NameGenerator (); gen.addfirst name ("Harry"); gen.add first name ("Sally"); gen.addFirst Name ("Brad"); gen.add first name ("Angie"); gen.add first name ("Barack"); gen.addlastname ("Miller"); gen.addSurname ("Merkel"); gen.addsurname ("Obama"); gen.addsurname ("Putin"); gen.addsurname ("Sanders"); for (int i = 0; i <5; i ++) {System.out.println (gen.createName ()); }

17.3 d) (d) Quiz

Write a quiz program like "Who Wants to Be a Millionaire?" Your program asks a series of questions and always provides four possible answers. The user submits his tip and finds out whether he / she was correct.

To do this, create two classes: and. The Quiz class contains a list of Question objects. A Question object contains a question, the four possible answers (a string array) and the index of the correct answer (int).

Simply create three sample objects in the Quiz constructor. The query should then begin with the start () method. One Keyboard input from the user with the following code:

Scanner scanner = new Scanner (System.in); String input = ""; while (! input.equals ("q")) {input = scanner.nextLine (); // User Input System.out.println ("Your input:" + input); // only for testing} scanner.close ();

Create a static main () in quizzes and test your program. Here is a possible course:

Question: What is the name of the US President? [0] Steam [1] Trump [2] Trumpf [3] Tram 1 R I C H T I G Question: Author of Emilia Galotti? [0] Schiller [1] Kleist [2] Goethe [3] Lessing 0 Unfortunately wrong. Correct is: Lessing Question: Where will the 2022 Olympics take place? [0] Tokyo [1] Beijing [2] L.A. [3] Hamburg 1 Unfortunately wrong. Correct: Tokyo You answered 0 of 3 questions correctly.

Note: You convert a string into a number (int) with:

Summary

  • Packages are like directories for classes. You should always define an initial package. You can use the same class name in two different packages. The package comes in Java code with package specified.
  • In Java, the Access modifiers public, protected and private used for classes, instance variables, constructors and methods.
    • public: all objects can access it
    • protected: only objects from subclasses and from the same package can access
    • private: only objects of the same class are allowed to access (especially objects of subclasses Not access
  • Instance variables should always private be. For public access to instance variables one can useGetter and Setter Methods write, which are then public.
  • Classes and Constructors are always public (With constructors there are cases where private access also makes sense).
  • Methods are public if they should also be accessible from other classes. They are private if they are only used for clarity within the class and are only called up within the class.
  • There is a subdirectory in the project directory src the source code: packages are shown there as nested directories. Code files have the extension .Java.
  • With Javadoc specially formatted comments are transferred to the overall documentation as HTML pages. Javadoc comments are bracketed with and.
  • In Java, in contrast to Processing, usually uses the type double for floating point numbers (and not float).

17.4 Java screened

Here are two videos that shed light on what the difference is between your source code and the executable program. You will also see how you can compile and execute your code on a "command shell" (also called a console).

Video: runtime vs. compile time (3:10)

This video explains the difference between compiling and running a program.

Video: Java on the console (14:53)

This video explains the difference between compiling and running a program.

17.5 Literature

  • Take a look at my Java emergency book, where the most important concepts are clearly presented in a PDF
  • One of the most widely used books on Java is not only available online, but also free of charge: Java is also an island by Christian Ullenboom
  • The ultimate source for further understanding (very readable) is the Core Java Books by Cay Horstmann.
  • Access Modifiers Java Tutorial Page (Oracle)