📜 ⬆️ ⬇️

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


This article is translated from English by Vladimir Alarcón and Nathaniel Monson’s “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 devoted to the description of the practical principles of Java programming using Raspberry Pi.

What you need:


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 byte-code, to run them independently 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 high-load applications that are critical to the result of execution. In this article I will cover only the basics of this language. As soon as 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 we will launch them! In the first part of the article you will generally learn how to run the examples, and then I will explain in more detail 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 can try to create new elements for them and define the necessary functionality. How this can be done, 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 a JDK. You can use any text editor to write Java programs. I prefer Geany , as it supports syntax highlighting, but Leafpad or GEdit does that too. I chose OpenJDK 7 as the JDK. As a standard, the compiler and the Java Virtual Machine (JVM) are included in the JDK package. The compiler generates the program from the source code for execution, and the JVM ensures that it starts.

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

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


It takes about 9 minutes to download and install all the necessary packages, but it may take more time, since it all depends on the speed of your Internet connection.

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

  java -version 


On the screen should appear several lines starting with:

  java version "1.7... OpenJDK ... 


2. Run the first program



Let's start by creating a directory to store our programs. I chose the name “cupofjava” for it, but you can choose any other option. Open a terminal window and type:

  mkdir cupofjava 


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

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

 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 you created the program:

  cd cupofjava 


and recruit:

  javac HiThere.java 


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

Ok, now run our program. In the terminal window we type:

  java HiThere 


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

The program will be launched and executed:

  Hi there! 


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

You probably noticed that it took the program a few seconds to write this message. Why so long? In fact, Java runs 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 downloading the JVM program will work very quickly.

Well, now, we can consider the program more closely. It essentially runs only one line. This is the string:

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


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

Complicate task # 1: your actions. Open the source file in a text editor, change the message in quotes 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 using the javac and java commands that you already used. If everything is done correctly, now the program will show your name. You did a great job!


Note: The syntax (command vocabulary and punctuation) of writing programs in the Java language is very similar to the syntax of the C language. Any programmer who is 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 with the name 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 the file. 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 drops will win. Are you interested to find out how this works?

In this example, you can demonstrate a few interesting things. This program uses two variables d and face . The variable d is used when we make only four throws, not three or five, and the face variable remembers what value was obtained for each of the throws. The program also gets a set of strings in the variable args . This variable passes the command line parameters if you specify them, but in our example they are not.

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

In addition, Java uses curly brackets { and } that define the scope of commands to be called in blocks. Each block can be empty or contain one or more commands. If necessary, you can, using control structures, select sub-blocks within existing blocks.

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

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

The while control construct starts its block four times while the value of variable d is less than 4. The initial value of this variable is 0 and with each block execution cycle it increases by 1. Therefore, the first four times (0, 1, 2, 3) the block is executed successfully, and only for the fifth time (when the variable d is 4) will it 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, recompile the program again and run it with the javac and java commands used. If everything is done correctly, now the program will show the value for 7 die rolls. Now for the work!


Translator's note: Source code, the text of the article itself and the layout in Scribus can be found in the repository github.com/svininykh/magpi-issue14-ru/tree/master/cup-of-java

Source: https://habr.com/ru/post/208306/


All Articles