Let's get started with Java with JShell.
A person who has no experience in programming manages to understand various concepts that appear in Java programming.
First of all, from the environment settings. Download the JDK from here. http://jdk.java.net/14/
If you are new to the command line, you may want to use the package with the installer with AdoptOpenJDK. https://adoptopenjdk.net/?variant=openjdk14&jvmVariant=hotspot For Mac and Linux people, download tar.gz
$ tar xf openjdk-14.0.2_osx-x64_bin.tar.gz
I think it's okay. On Windows, install the zip and unzip it to the appropriate folder.
Let's start JShell. Open "Command Prompt" for Windows users and "Terminal" for Mac and Linux users.
$ jshell
Lucky to start with
By the way, $ jshell
is a notation that you should type jshell
on such a command line and press the [enter] key.
If it doesn't start, start " \ Program files \ Java \ jdk-11 \ bin \ jshell "
for Windows. If you enter about \ Prog
and press [tab], it will be completed.
\
as .
For Mac, around / Library / Java / jdk-11 / Contents / Home / bin / jshell
.Enter 12 + 23
as a trial and press the [enter] key.
The result is 35
.
If you enter something in JShell and press the [enter] key, JShell will interpret the input as Java code and execute it. This time I entered just a calculation, but it will also be part of the Java program.
So, the first Java program is 12 + 23
. You did it!
Hereafter, the input to jshell and the result are expressed as follows.
jshell> 12 + 23
$1 ==> 35
This means that you should type 12 + 23
in JShell and press enter, and you'll see 35
. Ignore the $ 1 ==>
part for now.
I did the addition earlier. So what about subtraction? Try 4-3
.
jshell> 4 - 3
$2 ==> 1
Use *
for multiplication and /
for division. You can also calculate the remainder of the division with %
.
jshell> 8 * 2
$3 ==> 16
jshell> 8 / 2
$4 ==> 4
jshell> 7 % 5
$5 ==> 2
How about 3 + 4 * 2
?
jshell> 3 + 4 * 2
$6 ==> 11
The multiplication is calculated first. If you enclose 3 + 4
in parentheses, the addition will be calculated first.
jshell> (3 + 4) * 2
$7 ==> 14
By the way, what about 22/7
?
jshell> 22 / 7
$8 ==> 3
It is calculated as an integer. If you want the result after the decimal point, that is, if you want to calculate it as a real number, use 22.0 / 7
.
jshell> 22.0 / 7
$9 ==> 3.142857142857143
If you add a decimal point, it will be treated as a real number. If either term of the operation is a real number, the calculation is performed as a real number. In this way, Java distinguishes between integers and real numbers.
So far we have dealt with numerical values. Programs often deal with a series of letters, such as words and sentences. In the world of programming, such a series of characters is called a character string. In Java, it is enclosed in "
(double quotes) to represent a character string.
jshell> "aaa"
$10 ==> "aaa"
Use the +
operator to concatenate strings.
jshell> "te" + "st"
$11 ==> "test"
What about subtraction? It would be convenient if you could get " te "
with " test "-" st "
.
jshell> "test" - "st"
|error:
|Binary operator'-'Operand type is invalid
|First type: java.lang.String
|Second type: java.lang.String
| "test" - "st"
| ^-----------^
I got an error. Here, the operand is the term of the operator. It says that strings cannot be used in the -
operator. It would be nice to be able to read these error messages properly, but at this point it's okay to recognize that you can't use strings in the -
operator.
Only the +
operator can be used as an operator for strings.
You will want to perform various operations on the character string. For example, let's count the number of characters. Try typing " test ".length ()
. If you enter up to len
and press the [Tab] key, you will be able to enter the continuation. These functions are called "complementary".
jshell> "test".length()
$12 ==> 4
You got 4
This length ()
is called a method. Strings have many such methods to perform operations on strings.
Pressing the [Tab] key on " test ".
will display a list of methods that can be called on the string.
Method | Usage |
---|---|
length () | Get the length of a string |
repeat (n) | Repeat the string n times |
replace (old, new) | Replace old in a string with new |
charAt (index) | Extract the indexth character |
substring (begin, end) | Extract from the beginning to the end of the string |
toUpperCase () | Uppercase strings |
toLowerCase () | Make strings lowercase |
Now let's use other methods as well. Let's run " test ". repeat (3)
.
jshell> "test".repeat(3)
$13 ==> "testtesttest"
You see a string that test
repeats 3 times. The repeat
method is a method that repeats a string a specified number of times. As you can see, there are times when you need to specify something for a method. The value specified for such a method is called an "argument".
Let's use another replace
method. Try running " test ".replace ("st "," ")
.
The charAt
method allows you to retrieve the character at the specified location.
jshell> "test".charAt(2)
$13 ==> 's'
Note that the first character is the 0th character. In most programs, 0 is the first element and 1 is the second element.
jshell> "test".replace("st","")
$14 ==> "te"
The replace
method is a method that replaces a character string, and takes the character string before replacement and the character string after replacement as arguments. When taking two or more arguments like this, separate the arguments with ,
. " "
Is called an empty string. By replacing " st "
with " "
, you omitted " st "
from the string.
You can also concatenate method calls.
jshell> "test".repeat(3).replace("st","")
$15 ==> "tetete"
The " test "
is repeated 3 times to become the " test test test "
, and the " st "
is omitted to become the"tetete"
.
Exercise: Use the repeat
method to create a string that repeats"hi"
4 times
Exercise: Use the replace
method to create a string that replaces p
in " grape "
with d
.
Exercise: Use the toLowerCase
method to lowercase"HELLO"
Exercise: Use the substring
method to create a string extracted from the first (second in everyday conversation) of"minute"
.
As a basic operation, when you press the up key, the previously entered one will be displayed. It can be used when you want to re-execute what you entered earlier.
In JShell, if it can be determined that the input is up to the point when the [Enter] key is pressed, the expression is executed. However, if the line ends halfway, such as when a line break occurs in the middle or when there are not enough parentheses, you will be prompted to continue input as follows.
jshell> "test".repeat(
...>
It's nice if you start a new line when you enter a long line, but if you think you've entered one line but the line isn't finished due to lack of parentheses, it's a hassle to find the mistake and you should enter it again. Sometimes it's early. In such a case, you can cancel by pressing [Ctrl] + [c].
Use the / exit
command to exit JShell.
jshell> /exit
|Finish
$
By the way, since this value is close to pi, I would like to use it in various ways instead of pi. However, it is troublesome to enter 22.0 / 7
one by one.
So it's a variable.
Variables can be defined by setting var variable name = value
.
jshell> var pi = 22.0 / 7
pi ==> 3.142857142857143
This defines a variable called pi
and assigns it a value of 3.142857142857143
. Just type pi
and you'll see the assigned value.
jshell> pi
pi ==> 3.142857142857143
Use this to find the circumference of a circle with a radius of 5. The length of the circumference was diameter x pi. Variables can be used in operations as values.
jshell> 5*2*pi
$16 ==> 31.428571428571427
The area was radius x radius x pi.
jshell> 5*5*pi
$17 ==> 78.57142857142857
In this way, we were able to use variables to recycle values.
By the way, when the variable pi was defined at the position of $ 17
, it was displayed as pi
. In other words, this means that we have assigned 78.57142857142857
to the variable $ 17
.
jshell> $17
$17 ==> 78.57142857142857
By the way, in Java, Math.PI
actually holds a highly accurate pi.
jshell> Math.PI
$82 ==> 3.141592653589793
It's the PI
field of the Math
class, but let's study it separately.
Using this value as the pi, the area of a circle with a radius of 5 is:
jshell> 5*5*Math.PI
$81 ==> 78.53981633974483
Let's assign this Math.PI
to the variable pi
.
jshell> pi=Math.PI
pi ==> 3.141592653589793
In this way, you can also reassign values to variables.
When I calculated 5 * 5 * pi
again, I got the same result as when I used Math.PI
as follows.
jshell> 5*5*pi
$84 ==> 78.53981633974483
Let's assign a string to the variable pi
.
jshell> pi="circle ratio"
|error:
|Incompatible type: java.lang.Unable to convert String to double:
| pi="circle ratio"
| ^------------^
I got an error. You're told that String can't be converted to double
.
Java variables determine what kind of value the variable can be assigned to. Such a type of value is called a "type". In other words, variables have a fixed type.
Now let's check the type of the variable. In JShell, you can check the variable type with the / var
command.
jshell> /var pi
| double pi = 3.141592653589793
This means that the variable pi
is of type double
and is assigned the value 3.141592653589793
. double
is the type that handles real numbers.
Let's look at the case of strings. First, prepare the variable str
to which the character string"circle"
is assigned.
jshell> var str="circle"
str ==> "circle"
Let's check the type with the / var
command.
jshell> /var str
| String str = "circle"
It has a type of String
. The character string is represented by the String
type.
Attempting to assign a real number will result in an error.
jshell> str=3.14
|error:
|Incompatible type:double java.lang.Cannot convert to String:
| str=3.14
| ^--
So far, we have prepared variables using var
. If you use var
, the variable type will be decided automatically. You can also specify a type
here to prepare a variable.
jshell> String message="hello"
message ==> "hello"
You can also call methods on such variables.
jshell> message.length()
$325 ==> 5
The methods that can be called are determined by the type. The length
and repeat
methods are methods prepared for the String
type. There are no methods that can be called on the double
type.
You can also assign the value returned by the method to a variable.
jshell> var count=message.length()
count ==> 5
Here the variable count
is of type ʻint`.
jshell> /var count
| int count = 5
The ʻint` type is a type that handles integers.
Exercise: Let's use var
to prepare a variable root2
with a real number 1.414
.
Exercise: Instead of using var
, let's prepare a variable word
to which the string "apple" is assigned.
Exercise: Let's call the toUpperCase
method on the word
prepared above.
I was able to use variables to recycle values, but it would be nice to be able to recycle expressions like radius x radius x pi. In Java, you can reuse expressions by defining methods.
It's a bit long, but try running double menseki (double r) {return r * r * pi;}
.
jshell> double menseki(double r){return r*r*pi;}
|Created the following:Method menseki(double)
The menseki
method is now defined. You can use it as follows.
jshell> menseki(5)
$34 ==> 78.53981633974483
jshell> menseki(3)
$33 ==> 28.274333882308138
Now you can reuse the formula.
Let's take a closer look at the method definition. If you break the method definition appropriately, it will be as follows.
double menseki(double r) {
return r*r*pi;
}
The definition is as follows:
Result type method name(Argument type Variable that handles arguments) {
return expression;
}
The type is the type of value, and in the ones that have appeared so far, the integer is ʻint, the real number is
double, and the character string is
String. This time, we have defined a method named
mensekithat takes a real number and returns it. I am trying to receive the received argument with
r. The r of radius. Use the
return` statement when returning a value. Here, the received radius is multiplied twice and multiplied by the pi is returned.
You can also define it with line breaks in JShell as follows:
jshell> double menseki(double r) {
...> return r*r*pi;
...> }
|Changed the following:Method menseki(double)
Exercise: The name of the argument does not have to be r
. As menseki2, try defining a method with the same function so that the argument is received by a.
Exercise: Try defining a method that takes a radius and returns the length of the circumference.
Swing
Wasn't it boring with just letters? So let's do something that isn't just letters. Show a window. In Java, a GUI toolkit called Swing is provided as standard. A GUI toolkit is a set of parts that display windows and arrange buttons.
First, prepare a window.
jshell> var f = new javax.swing.JFrame("test")
f ==> javax.swing.JFrame[fram ... bled=true]
I'm not sure, but something was assigned to the variable f.
In response, try calling the show ()
method.
jshell> f.show()
Something was displayed in the upper left.
It's small, so try increasing the size. Use the setSize
method to determine the size. Here, specify the horizontal size and the vertical size.
jshell> f.setSize(400,300)
I've grown up!
When preparing a window
var f = new javax.swing.JFrame("test")
Was executed.
In Java, objects handled by the program such as windows and buttons are prepared as "objects". Here the variable f
is assigned a window object. In Swing, windows are represented by the type javax.swing.JFrame
. Objects are created based on some type. The type on which an object is based is called a "class". javax.swing.JFrame
is a class.
When you create an object from a class, use the new
operator to create it likenew class (argument)
. The arguments are determined by the class.
From some perspectives, it looks like you're calling a special method with the new
operator when you create an object. When viewed this way, this method is called a "constructor". A constructor is a method that has the same name as a class and requires the new
operator to call.
JavaDoc
The documentation for this javax.swing.JFrame
can be found here.
https://download.java.net/java/early_access/jdk11/docs/api/java.desktop/javax/swing/JFrame.html
It's English. If you like Japanese, the version is old, but here. https://docs.oracle.com/javase/jp/10/docs/api/javax/swing/JFrame.html
The format of this document is called "JavaDoc". The Java API documentation is generally in this format.
If you go around with javadoc + class name such as "javadoc JFrame", JavaDoc will come out.
For example, the constructor used this time has the following explanation.
If you look at this, you can see that we used a constructor called JFrame (String title)
. We also have a no-argument constructor, so you can see that you can create a window without specifying a title.
You may not know this unless you study the Java language a little more, but checking the JavaDoc can help you understand what you were doing.
Also, in general, it is not all explained in the manual, so it is important to refer to such primary information and grasp it accurately.
Exercise: Let's examine the String replace method used so far in JavaDoc. Tip: It is convenient to search in the search box on the upper right.
Now that the window is visible, let's place the text area. The text area is a part where you can enter a multi-line character string. In Swing, the text area is handled by the javax.swing.JTextArea
class. The parts placed in the window in this way are called "components".
In order to place the text area, you first need to create an object for the text area. To create an object, you called a method with the same name as the class name, that is, the constructor with the new
operator. However, javax.swing.JTextArea
is long and cumbersome to enter.
Actually, javax.swing.JTextArea
is divided into two parts, only the last delimiter is the class name, and before that it is the package name. In other words, it represents the JTextArea
class of the package javax.swing
. A "package" is a mechanism for classifying Java classes.
So you can use the ʻimport statement to omit the package name. ʻImport javax.swing. *
allows the class of the javax.swing
package to be represented by the class name alone, omitting the package name.
jshell> import javax.swing.*
I've been ignoring it until now, but sometimes the String
type was displayed as java.lang.String
. The String
type was in the java.lang
package, and the java.lang
package was pre-installed with ʻimport`, so the package name could be omitted.
Now let's create an object of the JTextArea
class that represents the text area.
jshell> var textarea = new JTextArea()
textarea ==> javax.swing.JTextArea[,0,0,0x0,i ... rap=false]
You need to place this in the window. You can add it to a window by calling the ʻadd method on the
JFrame` object that represents the window.
jshell> f.add(textarea)
$14 ==> javax.swing.JTextArea[,0,0,0x0,inval ... se,wrap=false]
However, it will not be displayed in the window as it is, so you need to have the window reorganized. Resizing the window will reorganize it, so try dragging the edge of the window to resize it or call the setSize
method. If the window size does not change when you specify the size with the setSize
method, nothing happens and you need to resize it a bit.
jshell> f.setSize(400,301)
A text area is displayed and you can enter characters.
You can add a string to the text area with the append method.
jshell> textarea.append("te")
jshell> textarea.append("st")
However, if it is left as it is, it will be added continuously without line breaks.
Line breaks are represented by \ n
. (For Windows, it is \ n
)
jshell> textarea.append("\ntester\n")
The line breaks have been made properly.
Now let's add a button. In Swing, buttons are handled by the JButton
class. You can specify the label string of the button in the argument of the constructor.
jshell> var button = new JButton("Hello")
button ==> javax.swing.JButton[,0,0,0x0,inval...pable=true]
I want to add this to the window, but since I have already placed the text area, I need to add it where it does not overlap. In JFrame, the component is placed by specifying north, south, east, west, and center.
ʻThe location to be placed in the first argument of the add` method and the component to be placed in the second argument are specified.
jshell> f.add("North", button)
$27 ==> javax.swing.JButton[,0,0,0x0,inval...ltCapable=true]
If you misspell North
, you will get an error like this. Please be careful as it is case sensitive.
jshell> f.add("Nort", button)
| Exception java.lang.IllegalArgumentException: cannot add to layout: unknown constraint: Nort
| at BorderLayout.addLayoutComponent (BorderLayout.java:468)
| at BorderLayout.addLayoutComponent (BorderLayout.java:429)
| at JRootPane$1.addLayoutComponent (JRootPane.java:507)
| at Container.addImpl (Container.java:1151)
| at Container.add (Container.java:1028)
| at JFrame.addImpl (JFrame.java:553)
| at Container.add (Container.java:459)
| at (#31:1)
By the way, this error is different from when I tried to assign a string to the variable pi a long time ago. It's also different from when you misspelled ʻadd`.
jshell> f.ad("North", b)
|error:
|Can't find symbol
|symbol:Method ad(java.lang.String,javax.swing.JButton)
|place:Type javax.swing.JFrame variable f
| f.ad("North", b)
| ^--^
These errors occur at different times, the error when trying to assign a character string to add or variable pi is the error when interpreting the program, the error when "North" is wrong is the interpreted processing This is an error when executing. An error when interpreting a program is called a compile error, and an error at runtime is called an exception. Now it's hard to tell the difference because both occur when you type in a command and press enter, but you'll see it clearly during actual development. For the time being, it's okay if you feel that there are two types of errors.
Well, even if add works fine, the button isn't showing yet.
If you reconstruct the window with the setSize
method, you will see the button.
jshell> f.setSize(400,300)
But when I press this button, nothing happens. I need to write some processing. Try typing: ʻAddActionListener is a bit long, but if you type up to ʻaddAc
and press the [tab] key, the rest should be completed.
jshell> button.addActionListener(ae -> textarea.append("Hello!\n"))
You should now see "Hello" when the button is pressed.
Use the ʻaddActionListenermethod to add processing when the button is pressed. Here, ʻae-> textarea.append ("Hello! \ N")
is specified as an argument. I had to pass some processing to the addActionListenermethod with the feeling "Please call this processing when the button is pressed". The processing here is
textarea.append (" Hello! \ N ")`, but you need to use "lambda expression" etc. to pass the processing as a value.
The lambda expression is written as follows:
argument->processing
In the case of processing when the button is pressed, ʻAe is used here because it receives the ʻActionEvent
object as an argument, but anything is fine as long as it is easy to understand. The received argument is not used this time.
Let's do our best.
Let's try to display the character string entered in the text field when the button is pressed.
I want to add a text field and a button, but I can't add it as it is with the JFrame layout method. So we use the JPanel
component.
jshell> var panel = new JPanel()
jshell> f.add("South", panel)
The JPanel
component has a layout in which the components are arranged in order from the left, and if you put various components here and then add them to the JFrame
window, it will look nice. I decided to add it to the South
position here.
When I change the window size, something is displayed a little.
Add a text field. The text field is a component that inputs only one line and uses the JTextField
component.
jshell> var textfield = new JTextField()
jshell> textfield.setColumns(15)
jshell> panel.add(textfield)
The width is determined by the setColumns
method.
Let's add a button at the end.
jshell> var printButton = new JButton("Print")
jshell> printButton.addActionListener(ae -> textarea.append(textfield.getText() + "\n"))
jshell> panel.add(printButton)
When you press the button, the character string entered in the text field is added to the text area.
Exercise: Let's add a button to display in the text area with Yeah!
.
Exercise: Let's add a button that capitalizes the alphabet of the character string entered in the text field and outputs it to the text area. To capitalize the alphabet of a string, use the toUpperCase
method. First, let's try using the toUpperCase
method on JShell.
Finally, let's write what we have tried with JShell as an independent Java program.
Enter the following source code in Notepad or TextEdit and save it on your desktop as FirstWindow.java
.
FirstWindow.java
import javax.swing.*;
public class FirstWindow {
public static void main(String... args) {
var frame = new JFrame("test");
var textarea = new JTextArea();
frame.add(textarea);
var textfield = new JTextField();
textfield.setColumns(15);
var button = new JButton("Print");
button.addActionListener(ae -> textarea.append(textfield.getText() + "\n"));
var panel = new JPanel();
panel.add(textfield);
panel.add(button);
frame.add("North", panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.show();
}
}
Various things that did not appear in JShell have been added. Also, the commands entered in JShell have a ;
(semicolon). However, compared to before I started this tutorial, I think it feels like "I can read it, I can read it!".
Now, let's move this source code.
Open a command prompt. I will not use JShell this time.
Use the cd
command to go to the desktop.
$ cd Desktop
Then compile the source code you just entered with the javac
command.
$ javac FirstWindow.java
If an error occurs, correct it, save it, and then compile it again.
When the error disappears, let's check the created file.
Use the dir
command on Windows and the ls
command on Mac and Linux.
$ dir FirstWindow.*
You now have a FirstWindow.class
file. Here is the Java executable code. Use the java
command to do this.
$ java FirstWindow
Did you see a window? If it is displayed, it is successful.
Start your full-scale study of Java from here.
Recommended Posts