Repository navigation
Expand file tree
/
Copy pathch_4_javadatatypes.ptx
More file actions
710 lines (598 loc) · 34.8 KB
/
Copy pathch_4_javadatatypes.ptx
File metadata and controls
710 lines (598 loc) · 34.8 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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
<?xml version="1.0"?>
<!-- Generated by Docutils 0.19 -->
<chapter xml:id="java-data-types">
<title>Java Data Types</title>
<introduction>
</introduction>
<section xml:id="numeric">
<title>Numeric</title>
<introduction>
<p>
One of the great things about Python is that all of the basic data types are objects.
Integers are objects, floating point numbers are objects, lists are objects, everything.
In Java that is not the case.
In Java, some of the most basic data types like integers and floating point numbers are not objects.
The benefit of having these primitive data types be non-objects is that operations on the primitives are fast.
The problem is that it became difficult for programmers to combine objects and non-objects in the way that we do in Python.
So, eventually all the non-object primitives ended up with Objectified versions.
</p>
<table>
<tabular>
<row header="yes">
<cell> Primitive </cell>
<cell> Object </cell>
</row>
<row>
<cell> int </cell>
<cell> Integer </cell>
</row>
<row>
<cell> float </cell>
<cell> Float </cell>
</row>
<row>
<cell> double </cell>
<cell> Double </cell>
</row>
<row>
<cell> char </cell>
<cell> Char </cell>
</row>
<row>
<cell> boolean </cell>
<cell> Boolean </cell>
</row>
</tabular>
</table>
<p>
In older versions of Java, it was the programmers responsibility to convert back and forth from a primitive to an object whenever necessary.
This process of converting a primitive to an object was called “boxing.” The reverse process is called “unboxing.” In Java 5, the compiler became smart enough to know when to convert back and forth and is called “autoboxing.” In this book, we will typically use the Object version of all the numeric data types and let the compiler do its thing.
</p>
<p>
Let’s look at a simple Python function which converts a Fahrenheit temperature to Celsius.
If this program were run on the command-line, you would enter the temperature when prompted – the Javascript pop-up for input is only an artifact of the digital textbook.
</p>
<program interactive="activecode" language="python">
<code>
def main():
fahr = int(input("Enter the temperature in F: "))
cel = (fahr - 32) * 5.0/9.0
print("the temperature in C is: ", cel)
main()
</code> <tests> </tests>
</program>
<p>
Next, lets look at the Java equivalent. If this program were run on the command-line, you would enter the temperature when prompted – the “Input for Program” text box is only an artifact of the digital textbook.
</p>
<program interactive="activecode" language="java">
<code>
import java.util.Scanner;
public class TempConv {
public static void main(String[] args) {
Double fahr;
Double cel;
Scanner in;
in = new Scanner(System.in);
System.out.println("Enter the temperature in F: ");
fahr = in.nextDouble();
cel = (fahr - 32) * 5.0/9.0;
System.out.println("The temperature in C is: " + cel);
}
}
</code> <stdin> </stdin> <tests> </tests>
</program>
<p>
There are several new concepts introduced in this example. We will look at them in the following order:
</p>
<p>
<ul>
<li>
<p>
Import
</p>
</li>
<li>
<p>
Variable Declaration
</p>
</li>
<li>
<p>
Input/Output and the Scanner Class
</p>
</li>
</ul>
</p>
</introduction>
<subsection>
<title>Import</title>
<p>
In Java, you can use any class that is available without having to import the class, subject to two very important conditions:
</p>
<p>
<ol marker="1">
<li>
<p>
The <c>javac</c> and <c>java</c> commands must know that the class exists.
</p>
</li>
<li>
<p>
You must use the full name of the class
</p>
</li>
</ol>
</p>
<p>
Your first question might be how do the <c>java</c> and <c>javac</c> commands know that certain classes exist. The answer is the following:
</p>
<p>
<ol marker="1">
<li>
<p>
Java knows about all the classes that are defined in .java and .class files in your current working directory.
</p>
</li>
<li>
<p>
Java knows about all the classes that are shipped with Java.
</p>
</li>
<li>
<p>
Java knows about all the classes that are included in your <c>CLASSPATH</c> environment variable. Your <c>CLASSPATH</c> environment variable can name two kinds of structures.
</p>
<p>
<ol marker="1">
<li>
<p>
A .jar file that contains Java classes
</p>
</li>
<li>
<p>
Another directory that contains Java class files
</p>
</li>
</ol>
</p>
</li>
</ol>
</p>
<p>
You can think of the import statement in Java as working a little bit like the <c>from module import xxx</c> statement in Python. However, behind the scenes, the two statements actually do very different things. The first important difference to understand is that the class naming system in Java is very hierarchical. The <em>full</em> name of the Scanner class is really <c>java.util.Scanner</c>. You can think of this name as having two parts: The first part <c>java.util</c> is called the <term>package</term> and the last part is the <term>class</term>. We’ll talk more about the class naming system a bit later. The second important difference is that it is the Java class loader’s responsibility to load classes into memory, not the import statement’s.
</p>
<p>
So, what exactly does the import statement do? What it does is tell the compiler that we are going to use a shortened version of the class’s name. In this example we are going to use the class <c>java.util.Scanner</c> but we can refer to it as just <c>Scanner</c>. We could use the <c>java.util.Scanner</c> class without any problem and without any import statement, provided that we always referred to it by its full name. As an experiment, you may want to try this yourself. Remove the import statement and change the string Scanner to <c>java.util.Scanner</c> in the rest of the code. The program should still compile and run.
</p>
</subsection>
<subsection>
<title>Declaring Variables</title>
<p>
Here is where we run into one of the most important differences between Java and Python. Python is a <term>dynamically typed</term> language. In a dynamically typed language a variable can refer to any kind of object at any time. When the variable is used, the interpreter figures out what kind of object it is. Java is a <term>statically typed</term> language. In a statically typed language the association between a variable and the type of object the variable can refer to is determined when the variable is <term>declared</term>. Once the declaration is made it is an error for a variable to refer to an object of any other type.
</p>
<p>
In the example above, lines 5—7 contain variable declarations. Specifically we are saying that <c>fahr</c> and <c>cel</c> are going to reference objects that are of type <c>Double</c>. The variable <c>in</c> will reference a <c>Scanner</c> object. This means that if we were to try an assignment like <c>fahr = "xyz"</c> the compiler would generate an error because <c>"xyz"</c> is a string and <c>fahr</c> is supposed to be a double.
</p>
<p>
For Python programmers, the following error is likely to be even more common. Suppose we forgot the declaration for <c>cel</c> and instead left line 6 blank. What would happen when we type <c>javac TempConv.java</c> on the command line?
</p>
<pre>TempConv.java:13: cannot find symbol symbol : variable cel location: class TempConv cel = (fahr - 32) * 5.0/9.0; ^ TempConv.java:14: cannot find symbol symbol : variable cel location: class TempConv System.out.println("The temperature in C is: " + cel); ^ 2 errors</pre>
<p>
When you see the first kind of error, where the symbol is on the left side of the equals sign, it usually means that you have not declared the variable. If you have ever tried to use a Python variable that you have not initialized the second error message will be familiar to you. The difference here is that we see the message before we ever try to test our program. More common error messages are discussed in the section <xref ref="common-mistakes-id1"/>.
</p>
<p>
The general rule in Java is that you must decide what kind of an object your variable is going to reference and then you must declare that variable before you use it. There is much more to say about the static typing of Java, but for now this is enough.
</p>
</subsection>
<subsection>
<title>Input / Output / Scanner</title>
<p>
In the previous section we created a <c>Scanner</c> object. In Java, <c>Scanner</c> objects make getting input from the user, a file, or even over the network relatively easy. In our case we simply want to ask the user to type in a number at the command line, so in line 9 we construct a <c>Scanner</c> by calling the constructor and passing it the <c>System.in</c> object. Notice that this <c>Scanner</c> object is assigned to the name <c>in</c>, which we declared to be a <c>Scanner</c> on line 7. <c>System.in</c> is similar to <c>System.out</c> except, of course, it is used for input. If you are wondering why we must create a <c>Scanner</c> to read data from <c>System.in</c> when we can write data directly to <c>System.out</c> using <c>println</c>, you are not alone. We will talk about the reasons why this is so later when we talk in-depth about Java streams. You will also see in other examples that we can create a <c>Scanner</c> by passing the <c>Scanner</c> a <c>File</c> object. You can think of a <c>Scanner</c> as a kind of “adapter” that makes low level objects easier to use.
</p>
<p>
On line 11 we use the <c>Scanner</c> object to read in a number. Here again we see the implications of Java being a strongly typed language. Notice that we must call the method <c>nextDouble</c> because the variable <c>fahr</c> was declared as a double. So, we must have a function that is guaranteed to return each kind of object we might want to read. In this case, we need to read a Double so we call the function <c>nextDouble</c>. The compiler matches up these assignment statments and if you try to assign the results of a method call to the wrong kind of variable it will be flagged as an error.
</p>
<p>
The table below shows some commonly used methods of the <c>Scanner</c> class. There are many more methods supported by this class and we will talk about how to find them in our chapter about <xref ref="java-documentation-id1"/>.
</p>
<table>
<tabular>
<row header="yes">
<cell> Return type </cell>
<cell> Method name </cell>
<cell> Description </cell>
</row>
<row>
<cell> boolean </cell>
<cell> hasNext() </cell>
<cell> returns true if more data is present </cell>
</row>
<row>
<cell> boolean </cell>
<cell> hasNextInt() </cell>
<cell> returns true if the next thing to read is an integer </cell>
</row>
<row>
<cell> boolean </cell>
<cell> hasNextFloat() </cell>
<cell> returns true if the next thing to read is a float </cell>
</row>
<row>
<cell> boolean </cell>
<cell> hasNextDouble() </cell>
<cell> returns true if the next thing to read is a double </cell>
</row>
<row>
<cell> Integer </cell>
<cell> nextInt() </cell>
<cell> returns the next thing to read as an integer </cell>
</row>
<row>
<cell> Float </cell>
<cell> nextFloat() </cell>
<cell> returns the next thing to read as a float </cell>
</row>
<row>
<cell> Double </cell>
<cell> nextDouble() </cell>
<cell> returns the next thing to read as a Double </cell>
</row>
<row>
<cell> String </cell>
<cell> next() </cell>
<cell> returns the next thing to read as a String </cell>
</row>
</tabular>
</table>
</subsection>
</section>
<section xml:id="string">
<title>String</title>
<p>
Strings in Java and Python are quite similar. Like Python, Java strings are immutable. However, manipulating strings in Java is not quite as obvious since Strings do not support an indexing or slicing operator. That is not to say that you can’t index into a Java string, you can. You can also pull out a substring just as you can with slicing. The difference is that Java uses method calls where Python uses operators.
</p>
<p>
In fact, this is the first example of another big difference between Java and Python. Java does not support any operator overloading. Table 3 maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called “str”
</p>
<table>
<tabular>
<row header="yes">
<cell> Python </cell>
<cell> Java </cell>
<cell> Description </cell>
</row>
<row>
<cell> <c>str[3]</c> </cell>
<cell> <c>str.charAt(3)</c> </cell>
<cell> Return character in 3rd position </cell>
</row>
<row>
<cell> <c>str[2:4]</c> </cell>
<cell> <c>str.substring(2,4)</c> </cell>
<cell> Return substring from 2nd up to but not including 4th </cell>
</row>
<row>
<cell> <c>len(str)</c> </cell>
<cell> <c>str.length()</c> </cell>
<cell> Return the length of the string </cell>
</row>
<row>
<cell> <c>str.find('x')</c> </cell>
<cell> <c>str.indexOf('x')</c> </cell>
<cell> Find the first occurrence of x </cell>
</row>
<row>
<cell> <c>str.split()</c> </cell>
<cell> <c>str.split('\s')</c> </cell>
<cell> Split the string on whitespace into a list/array of strings </cell>
</row>
<row>
<cell> <c>str.split(',')</c> </cell>
<cell> <c>str.split(',')</c> </cell>
<cell> Split the string at <c>','</c> into a list/array of strings </cell>
</row>
<row>
<cell> <c>str + str</c> </cell>
<cell><c>str + str</c> or <c>str.concat(str)</c> </cell>
<cell> Concatenate two strings together </cell>
</row>
<row>
<cell> <c>str.strip()</c> </cell>
<cell> <c>str.trim()</c> </cell>
<cell> Remove any whitespace at the beginning or end </cell>
</row>
</tabular>
</table>
</section>
<section xml:id="list">
<title>List</title>
<p>
Next, let’s look at a program which reads numbers from a file and produces a histogram showing the frequency of the numbers. The data file we will use has one number between 0 and 9 on each line of the file. Here is a simple Python program that creates and prints a histogram.
</p>
<program interactive="activecode" language="python">
<code>
def main():
count = [0]*10
data = open('test.dat')
for line in data:
count[int(line)] = count[int(line)] + 1
idx = 0
for num in count:
print(idx, " occured ", num, " times.")
idx += 1
main()
</code> <tests> </tests>
</program>
<p>
Test running the program. It will read this data:
</p>
<datafile label="datafile-test" filename="test.dat" editable="no" cols="12" rows="6">
<pre>
1
2
3
9
1
</pre> </datafile>
<p>
Lets review what is happening in this little program. First, we create a list and initialize the first 10 positions in the list to be 0. Next we open the data file called ‘test.dat’. Third, we have a loop that reads each line of the file. As we read each line we convert it to an integer and increment the counter at the position in the list indicated by the number on the line we just read. Finally we iterate over each element in the list, printing out both the position in the list and the total value stored in that position.
</p>
<p>
To write the Java version of this program we will have to introduce several new Java concepts. First, you will see the Java equivalent of a list, called an <c>ArrayList.</c> Next, you will see three different kinds of loops used in Java. Two of the loops we will use are going to be very familiar, the third one is different from what you are used to in Python but is easy when you understand the syntax:
</p>
<p>
<ul>
<li>
<p>
<c>while (condition) { code }</c>
</p>
<p>
<ul>
<li>
<p>
The <c>code</c> will be repeatedly executed until the <c>condition</c> becomes false.
</p>
</li>
</ul>
</p>
</li>
<li>
<p>
<c>for (initialization statement; condition; loop statement) { code }</c>
</p>
<p>
<ul>
<li>
<p>
The <c>code</c> will be repeatedly executed until the <c>condition</c> becomes false. As shown in the example below, the <c>initialization statement</c> and <c>loop statement</c> make this form useful for iterating over a range of numbers, similar to how you might use <c>for i in range(10)</c> in Python.
</p>
</li>
</ul>
</p>
</li>
<li>
<p>
<c>for (Type variable : collection) { code }</c>
</p>
<p>
<ul>
<li>
<p>
The <c>code</c> will be executed once for each element in the <c>collection</c>. Each execution, <c>variable</c> will be assigned to the next element of <c>collection</c>. Known as the “for-each” loop. This form is useful for iterating over members of a collection, similar to how you might use <c>for a in array</c> in Python.
</p>
</li>
</ul>
</p>
</li>
</ul>
</p>
<p>
Here is the Java code needed to write the exact same program:
</p>
<program interactive="activecode" language="java" datafile="test.dat">
<code>
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
public class Histo {
public static void main(String[] args) {
Scanner data = null;
ArrayList<Integer> count;
Integer idx;
try {
data = new Scanner(new File("test.dat"));
}
catch ( IOException e) {
System.out.println("Unable to open data file");
e.printStackTrace();
System.exit(0);
}
count = new ArrayList<Integer>(10);
for (Integer i = 0; i < 10; i++) {
count.add(i,0);
}
while(data.hasNextInt()) {
idx = data.nextInt();
count.set(idx,count.get(idx)+1);
}
idx = 0;
for(Integer i : count) {
System.out.println(idx + " occured " + i + " times.");
idx++;
}
}
}
</code> <tests> </tests>
</program>
<p>
Before going any further, I suggest you try to compile the above program and run it on some test data that you create.
</p>
<p>
Now, let’s look at what is happening in the Java source. As usual, we declare the variables we are going to use at the beginning of the method. In this example we are declaring a <c>Scanner</c> variable called <c>data</c>, an integer called <c>idx</c> and an <c>ArrayList</c> called <c>count</c>. However, there is a new twist to the <c>ArrayList</c> declaration. Unlike Python where lists can contain just about anything, in Java we let the compiler know what kind of objects our array list is going to contain. In this case the <c>ArrayList</c> will contain <c>Integers</c>. The syntax we use to declare what kind of object the list will contain is the <c><Type></c> syntax.
</p>
<p>
Technically, you don’t <em>have</em> to declare what is going to be in an array list. The compiler will allow you to leave the <c><``*Type*</c>>`` off the declaration. If you don’t tell Java what kind of object is going to be on the list Java will give you a warning message like this:
</p>
<pre>Note: Histo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.</pre>
<p>
Without the <c><Integer></c> part of the declaration Java simply assumes that <em>any</em> object can be on the list. However, without resorting to an ugly notation called casting, you cannot do anything with the objects on a list like this! So, if you forget you will surely see more errors later in your code. (Try it and see what you get)
</p>
<p>
Lines 13—20 are required to open the file. Why so many lines to open a file in Java? The additional code mainly comes from the fact that Java forces you to reckon with the possibility that the file you want to open is not going to be there. If you attempt to open a file that is not there you will get an error. A try/catch construct allows us to try things that are risky, and gracefully recover from an error if one occurs. The following example shows the general structure of a try/catch block.
</p>
<pre>try { Put some risky code in here, like opening a file } catch (Exception e) { If an error happens in the try block an exception is thrown. We will catch that exception here! }</pre>
<p>
Notice that in line 16 we are catching an <c>IOException</c>. In fact, we will see later that we can have multiple catch blocks to catch different types of exceptions. If we want to be lazy and catch any old exception we can catch an <c>Exception</c> which is the parent of all exceptions. However, catching <c>Exception</c> is a terrible practice, since you may inadvertently catch exceptions you do not intend to, making it harder to identify bugs in your program.
</p>
<p>
On line 22 we create our <c>ArrayList</c> and give it an initial size of 10. Strictly speaking, it is not necessary to give the <c>ArrayList</c> any size. It will grow or shrink dynamically as needed, just like a list in Python. On line 23 we start the first of three loops. The for loop on lines 23–25 serves the same purpose as the Python statement <c>count = [0]*10</c>, that is it initializes the first 10 positions in the <c>ArrayList</c> to hold the value 0.
</p>
<p>
The syntax of this for loop probably looks very strange to you, but in fact it is not too different from what happens in Python using range. In fact <c>for (Integer i = 0; i < 10; i++)</c> is exactly equivalent to the Python <c>for i in range(10)</c> The first statement inside the parenthesis declares and initializes a loop variable <c>i</c>. The second statement is a Boolean expression that is our exit condition. In other words we will keep looping as long as this expression evaluates to true. The third clause is used to increment the value of the loop variable at the end of iteration through the loop. In fact <c>i++</c> is Java shorthand for <c>i = i + 1</c> Java also supports the shorthand <c>i--</c> to decrement the value of i. Like Python, you can also write <c>i += 2</c> as shorthand for <c>i = i + 2</c> Try to rewrite the following Python for loops as Java for loops:
</p>
<p>
<ul>
<li>
<p>
<c>for i in range(2,101,2)</c>
</p>
</li>
<li>
<p>
<c>for i in range(1,100)</c>
</p>
</li>
<li>
<p>
<c>for i in range(100,0,-1)</c>
</p>
</li>
<li>
<p>
<c>for x,y in zip(range(10),range(0,20,2))</c> [hint, you can separate statements in the same clause with a ,]
</p>
</li>
</ul>
</p>
<p>
The next loop (lines 27–30) shows a typical Java pattern for reading data from a file. Java while loops and Python while loops are identical in their logic. In this case, we will continue to process the body of the loop as long as <c>data.hasNextInt()</c> returns true.
</p>
<p>
Line 29 illustrates another important difference between Python and Java. Notice that in Java we can not write <c>count[idx] = count[idx] + 1</c>. This is because in Java there is no overloading of operators. Everything except the most basic math and logical operations is done using methods. So, to set the value of an <c>ArrayList</c> element we use the <c>set</c> method. The first parameter of <c>set</c> indicates the index or position in the <c>ArrayList</c> we are going to change. The next parameter is the value we want to set. Notice that, once again, we cannot use the indexing square bracket operator to retrieve a value from the list, but we must use the <c>get</c> method.
</p>
<p>
The last loop in this example is similar to the Python for loop where the object of the loop is a Sequence. In Java we can use this kind of for loop over all kinds of sequences, which are called Collection classes in Java. The for loop on line 33 <c>for(Integer i : count)</c> is equivalent to the Python loop <c>for i in count:</c> This loop iterates over all of the elements in the ArrayList called count. Each time through the loop the Integer variable <c>i</c> is bound to the next element of the <c>ArrayList</c>. If you tried the experiment of removing the <c><Integer></c> part of the <c>ArrayList</c> declaration you probably noticed that you had an error on this line. Why?
</p>
</section>
<section xml:id="arrays">
<title>Arrays</title>
<p>
As I said at the outset of this section, we are going to use Java <c>ArrayLists</c> because they are easier to use and more closely match the way that Python lists behave. However, if you look at Java code on the internet or even in your Core Java books you are going to see examples of something called arrays. In fact you have already seen one example of an array declared in the ‘Hello World’ program. Lets rewrite this program to use primitive arrays rather than array lists.
</p>
<program interactive="activecode" language="java" datafile="test.dat">
<code>
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class HistoArray {
public static void main(String[] args) {
Scanner data = null;
Integer[] count = {0,0,0,0,0,0,0,0,0,0};
Integer idx;
try {
data = new Scanner(new File("test.dat"));
}
catch ( IOException e) {
System.out.println("Unable to open data file");
e.printStackTrace();
System.exit(0);
}
while(data.hasNextInt()) {
idx = data.nextInt();
count[idx] = count[idx] + 1;
}
idx = 0;
for(Integer i : count) {
System.out.println(idx + " occured " + i + " times.");
idx++;
}
}
}
</code> <tests> </tests>
</program>
<p>
The main difference between this example and the previous example is that we declare <c>count</c> to be an <c>Array</c> of integers. We also can initialize short arrays directly using the syntax shown on line 8. Then notice that on line 22 we can use the square bracket notation to index into an array.
</p>
</section>
<section xml:id="dictionary">
<title>Dictionary</title>
<p>
Just as Python provides the dictionary when we want to have easy access to key-value pairs, Java also provides us a similar mechanism. Rather than the dictionary terminology, Java calls these objects Maps. Java provides two different implementations of a map, one is called the <c>TreeMap</c> and the other is called a <c>HashMap</c>. As you might guess the <c>TreeMap</c> uses a balanced binary tree behind the scenes, and the <c>HashMap</c> uses a hash table.
</p>
<p>
Lets stay with a simple frequency counting example, only this time we will count the frequency of words in a document. A simple Python program for this job could look like this:
</p>
<program interactive="activecode" language="python">
<code>
def main():
data = open('alice30.txt')
wordList = data.read().split()
count = {}
for w in wordList:
w = w.lower()
count[w] = count.get(w,0) + 1
keyList = sorted(count.keys())
for k in keyList:
print("%-20s occurred %4d times" % (k, count[k]))
main()
</code> <tests> </tests>
</program>
<datafile label="datafile-alice1" filename="alice30.txt" editable="no" cols="30" rows="15"><pre> Down, down, down. Would the fall NEVER come to an end! 'I wonder how many miles I've fallen by this time?' she said aloud. 'I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think--' (for, you see, Alice had learnt several things of this sort in her lessons in the schoolroom, and though this was not a VERY good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice to say it over) '--yes, that's about the right distance--but then I wonder what Latitude or Longitude I've got to?' (Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say.) </pre></datafile>
<p>
Notice that the structure of the program is very similar to the numeric histogram program.
</p>
<program interactive="activecode" language="java" datafile="alice30.txt">
<code>
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.util.TreeMap;
public class HistoMap {
public static void main(String[] args) {
Scanner data = null;
TreeMap<String,Integer> count;
Integer idx;
String word;
Integer wordCount;
try {
data = new Scanner(new File("alice30.txt"));
}
catch ( IOException e) {
System.out.println("Unable to open data file");
e.printStackTrace();
System.exit(0);
}
count = new TreeMap<String,Integer>();
while(data.hasNext()) {
word = data.next().toLowerCase();
wordCount = count.get(word);
if (wordCount == null) {
wordCount = 0;
}
count.put(word,++wordCount);
}
for(String i : count.keySet()) {
System.out.printf("%-20s occured %5d times\n", i, count.get(i) );
}
}
}
</code> <tests> </tests>
</program>
<p>
Improve the program above to remove the punctuation.
</p>
</section>
</chapter>