Repository navigation
Expand file tree
/
Copy pathch_3_firstjavaprogram.ptx
More file actions
275 lines (271 loc) · 13.2 KB
/
Copy pathch_3_firstjavaprogram.ptx
File metadata and controls
275 lines (271 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?xml version="1.0"?>
<!-- Generated by Docutils 0.19 -->
<chapter xml:id="lets-look-at-a-java-program">
<title>Lets look at a Java Program</title>
<p>A time-honored tradition in Computer Science is to write a program
called “hello world.” The “hello world” program is simple and easy.
There are no logic errors to make, so getting it to run relies only on
understanding the syntax. To be clear, lets look at a “complicated”
version of hello world for Python:</p>
<pre>def main():
print("Hello World!")</pre>
<p>Remember that we can define this program right at the Python command
line and then run it:</p>
<pre>>>> main()
"Hello World!"
>>></pre>
<p>Now lets look at the same program written in Java:</p>
<program interactive="activecode" language="java">
<code>
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
</code>
<tests>
</tests>
</program>
<p>What we see is that at the core there are a few similarities, such as a
main and the string “Hello World”. However, there is a lot more stuff
around the edges that make it harder to see the core of the program. Do
not worry! An important skill for a computer scientist is to learn what
to ignore and what to look at carefully. You will soon find that there
are some elements of Java that will fade into the background as you
become used to seeing them. One thing that will help you is to learn a
little bit about Java <xref ref="naming-conventions-id1"/>.</p>
<p>The first question you probably have about this little program is “How
do I run it?” Running a Java program is not as simple as running a
Python program. The first thing you need to do with a Java program is
compile it. The first big difference between Java and Python is that
Python is an interpreted language. We could run our Python programs in
the Python <term>interpreter</term> and we were quite happy to do that. Java
makes running programs a two step process. First we must type the hello
world program into a file and save that file using the name
<c>Hello.java</c> The file name must be the same as the public class you
define in the file. Once we have saved the file we <term>compile</term> it from
the command line as follows:</p>
<program language="java">
<code>
$ javac Hello.java
$ ls -l Hello.*
-rw-r--r-- 1 bmiller bmiller 391 Jul 19 17:47 Hello.class
-rw-r--r-- 1 bmiller bmiller 117 Jul 19 17:46 Hello.java
</code>
</program>
<p>The command <c>javac</c> compiles our java source code into compiled byte
code and saves it in a file called <c>Hello.class</c>. <c>Hello.class</c> is a
binary file so you won’t learn much if you try to examine the class file
with an editor. Hopefully you didn’t make any mistakes, but if you did
you may want to consult the <xref ref="common-mistakes-id1"/>
section for helpful hints on compiler errors.</p>
<p>Now that we have compiled our java source code we can run the compiled
code using the <c>java</c> command.</p>
<program language="java">
<code>
$ java Hello
Hello World!
$
</code>
</program>
<p>Now you may be wondering what good is that extra step? What does
compiling do for us? There are a couple of important benefits we get
from compiling:</p>
<p>
<ul>
<li>
<p>Early detection of errors</p>
</li>
<li>
<p>Faster program execution</p>
</li>
</ul>
</p>
<p>The job of the compiler is to turn your java code into language that the
Java Virtual Machine (JVM) can understand. We call the code that the JVM
understands <term>byte code</term>. The JVM interprets the byte code much like
the Python interpreter interprets your Python. However since byte code
is much closer to the native language of the computer it can run faster.</p>
<p>When the compiler does the translation it can find many different kinds
of errors. For example, if you make a typo, the compiler will find the
typo and point it out to you before you ever run the program. We will
look at some examples of compiler errors shortly. Chances are you will
create some on your own very soon, too.</p>
<p>Now that we have run our hello world program, lets go back and look at
it carefully to see what we can learn about the Java language. This
simple example illustrates a few very important rules:</p>
<p>
<ol marker="1">
<li>
<p>Every Java program must define a class, and all code is inside a class</p>
</li>
<li>
<p>Everything in Java must have a type</p>
</li>
<li>
<p>Every Java program must have a function called
<c>public static void main(String[] args)</c></p>
</li>
</ol>
</p>
<p>Lets take the hello world example a line at a time to see how these
rules are applied. On line 1 we see that we are declaring a class called
Hello:</p>
<program language="java">
<code>
public class Hello {
</code>
</program>
<p>As rule 1 says all Java code resides inside a class. Unlike
Python where a program can simply be a bunch of statements in a file,
Java programs must be inside a class. So, we define a class <c>Hello</c>,
which is not a very useful class because it has no instance variables, and only one
method. You will also notice the curly brace <c>{</c>. In Java, blocks of
code are identified by pairs of curly braces. The block starts with a
<c>{</c> and ends with a <c>}</c>. You will notice that I indented my code
that followed the left brace, but in Java this is only done by
convention, it is not enforced.</p>
<p>On the next line we start our method definition. The name of this method
is:</p>
<program language="java">
<code>
public static void main(String[] args)
</code>
</program>
<p>Everything on this line is significant, and helps in the identification
of this method. For example the following lines look similar but are in
fact treated by Java as completely different methods:</p>
<p>
<ul>
<li>
<p>
<c>public void main(String[] args)</c>
</p>
</li>
<li>
<p>
<c>public static void main(String args)</c>
</p>
</li>
<li>
<p>
<c>public static void main()</c>
</p>
</li>
<li>
<p>
<c>void main(String args)</c>
</p>
</li>
</ul>
</p>
<p>Just digging in to this one line will take us deep into the world of
Java, so we are going to start digging but we are not going to dig too
deeply right away. Much of what could be revealed by this one line is
better understood through other examples, so be patient.</p>
<p>The first word, <term>public</term> indicates to the Java compiler that this is a
method that anyone can call. We will see that Java enforces several
levels of security on the methods we write, including <term>public</term>,
<term>protected</term>, and <term>private</term> methods.</p>
<p>The next word, <term>static</term> tells Java that this is a method that is part
of the class, but is not a method for any one instance of the class. The
kind of methods we typically wrote in Python required an instance in
order for the method to be called. With a static method, the object to
the left of the <c>.</c> is a class, not an instance of the class. For example,
the way that we would call the <c>main</c> method directly is:
<c>Hello.main(parameter1)</c>. For now, you can think of static methods the
same way you think of methods in Python modules that don’t require an
instance, for example the math module contains many methods: sin, cos,
etc. You probably evaluated these methods using the names
<c>math.cos(90)</c> or <c>math.sin(60)</c>.</p>
<p>The next word, <term>void</term> tells the Java compiler that the method <c>main</c>
will not return a value. This is roughly analogous to omitting the
return statement in a Python method. In other words, the method will run
to completion and exit but will not return a value that you can use in
an assignment statement. As we look at other examples we will see that
every Java function must tell the compiler what kind of an object it
will return. This is in keeping with the rule that says everything in
Java must have a type. In this case we use the special type called
<c>void</c> which means no type.</p>
<p>Next we have the proper name for the method: <term>main</term>. The rules for
names in Java are similar to the rules in Python. Names can include
letters, numbers, and the <c>_</c>. Names in Java must start with a letter.</p>
<p>Finally, we have the parameter list for the method. In this example we
have one parameter. The name of the parameter is <c>args</c>, however,
because everything in Java must have a type, we also have to tell the
compiler that the value of <c>args</c> is an array of strings. For the
moment you can just think of an array as being the same thing as a list
in Python. The practical benefit of declaring that the method <c>main</c> must
accept one parameter and the parameter must be an array of strings is
that if you call <c>main</c> somewhere else in your code and and pass it an
array of integers or even a single string, the compiler will flag it as
an error.</p>
<p>That is a lot of new material to digest in only a single line of Java!
Lets press on and look at the next line:</p>
<program language="java">
<code>
System.out.println("Hello World!");
</code>
</program>
<p>This line should look a bit
more familiar to you. Python and Java both use the dot notation for
finding names. In this example we start with <c>System</c>. System is a
class. Within the system class we find the object named <c>out</c>. The
<c>out</c> object is the standard output stream for this program. Having
located the <c>out</c> object Java will now call the method named
<c>println(String s)</c> on that object. The <c>println</c> method prints a
string and adds a newline character at the end. Anywhere in Python that
you used the <c>print</c> function you will use the <c>System.out.println</c>
method in Java.</p>
<p>Now there is one more character on this line that is significant and
that is the <c>;</c> at the end. In Java the <c>;</c> signifies the end of a
statement. Java statements can spread across many lines, but the compiler
knows it has reached the end of a statement when it encounters a <c>;</c>.
In Python, it is not required (or recommend) to use semicolons in this way,
but whitespace is meaningful.
In contrast, in Java semicolons are <term>required</term> to end statements, but
whitespace is not considered meaningful.
This is a very important difference to remember! In Java, the following
statements are all legal and equivalent. I would not encourage you to
write your code like this, but you should know that it is legal.</p>
<program language="java">
<code>
System.out.println("Hello World");
System.out.println("Hello World")
;
System.out.println
(
"Hello World"
) ;
System.
out.
println("Hello World")
;
</code>
</program>
<p>The last two lines of the hello world program simply close the two
blocks using <c>}</c>. The first or outer block is the class definition. The second or
inner block is the function definition.</p>
<p>If we wanted to translate the Java back to Python we would have
something like the following class definition.</p>
<program language="java">
<code>
class Hello(object):
@staticmethod
def main(args):
print("Hello World!")
</code>
</program>
<p>Notice that we used the decorator <c>@staticmethod</c> to tell the Python
interpreter that <c>main</c> is going to be a static method. The impact of
this is that we don’t have to, indeed we should not, use <c>self</c> as the
first parameter of the main method! Using this definition we can call
the main method in a Python session like this:</p>
<program language="java">
<code>
>>> Hello.main("")
Hello World!
>>>
</code>
</program>
</chapter>