Chapter 6, Introducing Java
Total Page:16
File Type:pdf, Size:1020Kb
Chapter 6, Introducing Java John M. Morrison January 19, 2021 Contents 0 Introduction 1 1 Welcome to JShell! 2 2 Coding Mechanics 5 3 Python Classes 8 4 Java Classes 10 5 Java's Integer Types 16 5.1 Using Java Integer Types in Java Code . 18 6 Four More Primitive Types 24 6.1 The boolean Type.......................... 25 6.2 FloatingPoint Types . 26 6.3 The char type ............................ 27 7 More Java Class Examples 27 0 Introduction We will begin our study of the Java language using its REPL, jshell. This chapter will introduce you the idea of class. A class is a blueprint for the 1 1 WELCOME TO JSHELL! creation of objects. Both Python and Java support classes; this chapter will introduce those. You will notice some important stylistic and linguistic dierences. One is that all Java code must live in an class. Clearly this is optional in Python. Variable naming rules are the same in both languages. However, there is a style dierence. Names for classes in both languages are capitalized and are formatted in camel notation. Variable and method names in Java are format- ted in camel notation, while these in Python are predominantly formatted in snake_notation. You will also see that worker statements in Java must end with a semicolon, and that boss statements have no mark at the end. Python programs only have one epoch, run time. A Python program will run until it ends or it encounters a fatal error. Variables in Python are typeless names. Java programs have two epochs, compile time and run time. Java runs on a virtual machine, which is a computer implemented in software. The rst step is to compile, which translates your Java code into the machine languages for the JVM which is called Java byte code. If you program does not make syntactic sense, compilation aborts and error messages issue forth. You must stamp out all syntax errors before your program will compile. For a Java program to run, you will need to create a special main method. To get started we will be using jshell to learn about the type system and to inspect some simple classes we will create. 1 Welcome to JShell! If you run Python with no le, you get an interactive Python shell. Java has a similar feature named jshell. To re up jshell, type jshell at the command prompt and you will see this. unix> jshell > jshell | Welcome to JShell -- Version 9.0.1 | For an introduction type: /help intro jshell> JShell has command that allows you to see the symbol table for your session, obtain help, and quit. We will use it quite a bit for inspecting and exploring classes. ©2009-2021, John M. Morrison 2 1 WELCOME TO JSHELL! Here is a summary of the commands. All of them begin with a /. /exit This quits jshell. /help This gives help on commands. The ussage is /imports This lists all classes you have imported. /list This lists all snippets you have entered. /open This reads a class into jshell so you can inspect it. /types This lists all active classes in the session. /vars This lists all variables and their values /help /command and you get a little man page for that command. Here we show how to quit jshell using the /exit command. unix> jshell jshell | Welcome to JShell -- Version 14.0.1 | For an introduction type: /help intro jshell> jshell> /exit | Goodbye unix> You can also quit it by typing control-d on Mac/UNIX or control-z on Windoze. You enter pieces of code called snippets into the shell and jshell runs them. Let's do that and test-drive some of the commands. Begin by entering some variable declarations. jshell> intx=4; x ==>4 jshell> String y= "spaghetti"; y ==> "spaghetti" jshell> intz= 15; z ==> 15 You should notice some things right o. In the declaration int x = 4; we specied a type for the variable x. Java variables have type and this type must be known at compile time. Java variables can only point at objects of thier type. The compiler enforces this rule. ©2009-2021, John M. Morrison 3 1 WELCOME TO JSHELL! You have now seen examples of Java's integer type, int and its string type, String. Now, watch jshell evaluate an expression. jshell>x*z $4 ==> 60 The symbol \$4 is a valid variable in your jshell session. The jshell applica- tion is a hoarder; it gives a local variable name to just about everything you don't name. jshell> $4 $4 ==> 60 Now we try the /vars command. jshell>/vars | intx=4 | String y= "spaghetti" | intz= 15 | int $4 Ooh, yummy, here is our visible symbol table. Now let's make a /list and check it twice. jshell>/list 1: intx=4; 2 : String y= "spaghetti"; 3: intz= 15; 4:x*z 5 : $4 Here we see all of the snippets we have created this session. Next let us try /vars. Now let us quit this session. We will show how to inspect a class. Create this class. public class Example { public void go() { intx=5; System.out.println("x = "+ x); } } ©2009-2021, John M. Morrison 4 2 CODING MECHANICS Next crank up jshell and open the le and inspect a method as follows. jshell>/open Example.java jshell> Example e= new Example(); e ==> Example@26653222 jshell> e.go() x=5 Now see the /types command in action. jshell>/types | class Example Observe the use of the langauge keyword new. Its use indicates that Java is creating an object on the heap and the associated variable is storing the memory addreess of that object. The dot notation you see in e.go() has the same eect as a Python method. It is reective of the genetive case; you are calling e's go() method. While we are here, let us create the same class in Python. You will see a mysterious argument self in Python class methods. We will explain more about this later. class Example: def go(self): x=5 print(f"x ={x}") Now we can import it into our Python session and inspect it. >>> from Example import Example >>>e= Example() >>>e.go() x=5 >>> In both cases, our Example object can do one thing, go(). 2 How does Java Work on a Mechanical Level? We will begin by looking at the mechanics of producing a program. We will then sketch a crude version of what actually happens during the process and ©2009-2021, John M. Morrison 5 2 CODING MECHANICS rene it as we go along. Here is a simplied life-cycle for a Java program. So you can follow along, make this empty class. Foo.java. public class Foo { } 1. Edit You begin the cycle by creating code in a text editor and saving it. Each le of Java will have a public class in it. The class is the fundamental unit of Java code; all of your Java programs will be organized into classes. Java classes are similar to those in Python; later we will compare them. The name of the class must match the name of the le; otherwise, you will get a nastygram from the compiler. As you saw in the example at the end of the last section, the le containing public class Foo must be be named Foo.java. Deliberately trigger the naming convention error creating an empty class Right in the le Wrong.java. Compile and you will receive this beating. unix> javac Wrong.java Wrong.java:1: error: class Right is public, should be declared in a file named Right.java public class Right ^ 1 error unix> An optional but nearly universal convention is to capitalize class names. You should adhere to this rule in the name of wise consistency. This is done by all serious Java programmers; uncapitalized class names just confuse, annoy, and vex others. 2. Compile Java is an example of a highlevel language. A complex program called a compiler converts your program into an executable form. Compilation of Java in a command window is simple. To compile Foo.java, proceed as follows unix> javac Foo.java When done, list your les and you should see Foo.class. If your program contains syntactical errors that make it unintelligible to the compiler, the compilation will abort. When this happens, nothing executes and no executable le is generated. In contrast, in the Python language, the program stops running when an syntactical error is encountered; in Java the program does not run at all unless it compiles successfully. There is no compile time in Python. If your program does not compile, you will get one or more error messages. These will be put to stderr, which by default, is your terminal window. You will need to reedit your code to stamp out these errors before it will compile. ©2009-2021, John M. Morrison 6 2 CODING MECHANICS Java compiles programs in the machine language of the Java Virtual Ma- chine; this machine is a virtual computer that is built in software. Its machine language is called Java byte code. In the Foo.java example, suc- cessful compilation yields a le Foo.class; this le consists of Java byte code. Your JVM takes this byte code and converts it into machine lan- guage for your particular platform, and your program will run. Java is not the only language that compiles to the JVM. Others include Scala, Clojure, a Lisp dialect, Processing, an animation language created in the MIT media lab, and Groovy, a scripting language. There is even a JVM implementation of Python called Jython.