Raspberry Pi and a cup of Java, please! (Part 1)

  • Tutorial

This article is a translation from the English article by Vladimir Alarcón and Nathaniel Monson “A Pi and a cup of Java, please!” Published in the 14th issue of MagPi . This article is the first in a series of articles describing the practical basics of Java programming using the Raspberry Pi.

What you need:
  • Raspberry Pi and Raspbian OS.
  • 150 MB of free space on the SD card.
  • Basic programming knowledge.
  • Basic command line skills.


Introduction



In this article, I will tell you how to write and run Java programs on your Raspberry Pi.

Java is an object-oriented programming language that translates the source code of programs into bytecode to run them regardless of the operating system and without the need for recompilation. Java also includes a wide range of technologies designed to solve problems in areas such as launching clusters of websites or highly loaded applications critical to the result of execution. In this article, I will only cover the basics of this language. Once you learn its basics, you can easily find websites on the Internet with a more detailed description of Java technologies and containing more complex examples of them.

In the beginning I will show how to install Java on the Raspberry Pi. Then we will create a couple of simple Java programs ... And only then will we launch them! In the first part of the article, you will generally learn how to run examples, and then in more detail I will explain the principles of their work. The idea is that it will make it easier for you to see the basics of writing real Java programs, and then you yourself can try to create new elements for them and set the necessary functionality. How to do this, I will try to explain after you write and run your first program.

1. Installation



To write, copy and run a program, you need two things: a text editor and JDK. You can use any text editor to write Java programs. I prefer Geany as it supports syntax highlighting, but Leafpad or GEdit do it too. I chose OpenJDK 7 as the JDK. By default, the JDK package includes the compiler and the Java Virtual Machine (JVM). The compiler generates programs for execution from the source code, and the JVM provides their launch.

Install Geany and OpenJDK 7 by opening a terminal window and typing:

  sudo apt-get install -y openjdk-7-jdk geany


It will take about 9 minutes to download and install all the necessary packages, but it may take longer, as it all depends on the speed of your Internet connection.

After completion, check that everything was installed correctly. To do this, you can open Geany from the “Programming” tab of the Raspbian main menu. And to test OpenJDK 7, open a terminal window and type:

  java -version


A few lines should appear on the screen starting with:

  java version "1.7...
  OpenJDK ...


2. Launch of the first program



Let's start by creating a directory for storing our programs. I chose the name "cupofjava" for him, but you can choose any other if you wish. Open the terminal window and type:

  mkdir cupofjava


Now let's start writing our first Java program (class). I will call it HiThere. Please remember that Java is an object-oriented programming language, and that every program is a class, which in turn can be used by other classes.

Open a text editor (in my case Geany ) to create the HiThere.java file and save it in a previously created directory. In this file we type (or copy) the following source code of the program:

public class HiThere {
  public static void main(String[] args) {
    System.out.println("A Java Pi!");
  }
}

Now compile it. Using the terminal window, go to the "cupofjava" directory, where before that you created the program:

  cd cupofjava


and type:

  javac HiThere.java


The javac team compiles Java programs. She analyzing the source code you typed generates a program to run. After 15 seconds or so, this command will complete the execution. If you make a mistake, she will report it, indicating where this problem occurred. To fix it, return to the text editor, check your code and correct the mistakes made, save the file, and try to run the compilation again. If there are no more errors, then the compilation was successful. Then you will find the new HiThere.class file in the current directory. This is the program and will be launched by you.

Ok, now let's run our program. In the terminal window, type:

  java HiThere


You do not have to specify the .class extension . What's the difference? The javac command compiles the programs, and the java command starts them.

The program will be launched and executed:

  Hi there!


Great ... Congratulations! You wrote and launched your first Java program on the Raspberry Pi.

You probably noticed that the program took several seconds to write this message. Why so long? In fact, Java is pretty fast. The program as a whole took only a couple of milliseconds to execute, the rest of the time it took to load at the beginning of the JVM environment to execute Java code. But there is good news that after loading the JVM, the program will work very quickly.

Well, now, we can consider the program more carefully. It essentially only executes one line. This is the line:

  System.out.println("A Java Pi!");


The remaining lines specify the name of the class “HiThere” (in line 1), as well as the name of the main method in line 3). This class, like any other Java class, can include many methods, but for this example we use only one main method main .

Let's complicate task # 1: your actions. Open the source file in a text editor, change the quoted message from “A Java Pi!” To “My name is Name.” (Enter your name) and save the result. In the terminal window, compile the program again and run it with the javac and java commands already used . If everything was done correctly, now the program will show your name. You did a great job!


Note: The syntax (command vocabulary and punctuation) of writing Java programs is very similar to the syntax of C. Any programmer familiar with C can easily learn the basics of Java.


3. Java variables and control constructs



The following example illustrates the use of variables and control structures. In the same directory where we saved the first program, create a second program by calling it DiceRoller.java . Type (or copy) the source code below:

import java.util.Random;
public class DiceRoller {
  public static void main(String[] args) {
    Random generator = new Random();
    int d = 0;
    while (d < 4) {
      System.out.print("Rolling... ");
      int face = 1 + generator.nextInt(6);
      System.out.print("I got a "+ face
        + ".  ");
      if (face == 1) {
        System.out.print("Wow! An ACE!");
      }
      System.out.println();
      d = d + 1;
    }
  }
}


Save it in a file. We compile and run our new program by typing two commands:

  javac DiceRoller.java
  java DiceRoller


You will see something like this:

Rolling... I got a 2.
Rolling... I got a 1.  Wow! An ACE!
Rolling... I got a 4.
Rolling... I got a 5.


The program will roll four dice and the one on which the unit will be won will win. Are you curious about how it works?

In this example, several interesting things can be demonstrated. This program uses two variables d and face . The d variable is applied when we make only four throws, not three and not five, and the face variable remembers what value was received at each of the throws. The program also receives a set of lines in the args variable . This variable passes command line parameters if you set them, but in our example they are not.

And yet, remember Java classes can use other classes? In our example, this is a generator variable. Through it, our program accesses the external class Random , which performs the generation of pseudorandom numbers. In our case, we call only one of its nextInt () methods to get a random number in the range from 0 to 5.

Additionally, curly braces { and } are used in Java to determine the scope of commands called in blocks. Each block may be empty or contain from one or more commands. If necessary, you can, using control structures, select sub-blocks inside existing blocks.

And now you can talk about it. In this example, two control constructs are used: if and while . Control structureif starts block execution only if the logical expression in brackets is true . While the control while construct works the other way around, its block is executed until the logical expression in brackets becomes false ( false ). Also in Java control structures are used: for , do-while , switch , if-else , etc.

In our example, if checks for the truth of the expression face == 1 . According to this, a message about winning appears only when a unit drops out.

The control while construct starts its block four times while the value of the variabled is less than 4. The initial value of this variable is 0 and with each block execution cycle it increases by 1. Therefore, the block is executed the first four times (0, 1, 2, 3), and only for the fifth time (when the variable d is 4 ) it will be interrupted.

Let's complicate task # 2 : Change the program for 7 dice rolls, increasing the range of possible values ​​to 10. In the terminal window, compile the program again and run it using the javac and java commands already used . If everything was done correctly, now the program will show the value for 7 dice rolls. And now, for the job!


Translator's note: You can find the source codes, the text of the article and the layout in Scribus in the repository github.com/svininykh/magpi-issue14-ru/tree/master/cup-of-java

Also popular now: