Repository navigation
Expand file tree
/
Copy pathch4_javadatatypes.ptx
More file actions
936 lines (820 loc) · 44 KB
/
Copy pathch4_javadatatypes.ptx
File metadata and controls
936 lines (820 loc) · 44 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
<?xml version="1.0"?>
<!-- Generated by Docutils 0.19 -->
<chapter xml:id="java-data-types">
<title>Java Data Types</title>
<section xml:id="numeric">
<title>Numeric</title>
<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>
With that distinction in mind, here are the common types you'll use, most of which are similar to Python's types:
<ul>
<li>
<p>
int: The primitive type for integers (whole numbers), such as 3, 0, and -76.
</p>
</li>
<li>
<p>
double: The primitive type for floating-point numbers like 6.3 or -0.9.
</p>
</li>
<li>
<p>
boolean: The primitive type that can only be true or false.
</p>
</li>
<li>
<p>
char: The primitive type for a single character, like 'a' or 'Z'. It is represented using single quotes.
</p>
</li>
<li>
<p>
String: An object type that represents a sequence of characters in double quotes, like "Hello".
</p>
</li>
</ul>
A data type fundamentally defines a set of values and the operations you can perform on them. For instance, you can do math with int and double values, but not with boolean values. This is simlar to Python, where you can perform arithmetic on integers and floats, but not on booleans or strings.
</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>
</ul>
</p>
<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>Variable Declaration</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>
A valid variable name in Java can contain letters, digits, and underscores. It must begin with a letter, an underscore, or a dollar sign. It cannot start with a digit and it cannot be a reserved keyword (like class, int, or static). Variable names are case-sensitive, so <c>fahr</c> and <c>Fahr</c> are different variables. The convention is to use lower case for variable names, and to use camel case (where the first word is lowercase and subsequent words are capitalized) for multi-word variable names, such as <c>fahrenheitTemperature</c>.
</p>
<p>
An important feature of Java is that when you declare a variable of a primitive type (like int or double), the system automatically allocates a fixed amount of memory to store its value directly. This is different from reference types (like String or Scanner), where the variable holds a memory address that points to the actual object data stored elsewhere. This distinction makes operations on primitives very fast.
</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. In our temperature converter, the calculation (fahr - 32) * 5.0/9.0 works correctly because 5.0 and 9.0 are treated as double values, preventing the integer division that would occur if we had written 5/9, which would result in 0.
</p>
</subsection>
</section>
<section xml:id="typecasting">
<title>Typecasting</title>
<p>
Typecasting is the process of converting a variable from one type to another. In Java, this is often necessary when you want to perform operations that require different data types. For example, if you have an integer and you want to convert it to a double for more precise calculations, you would use typecasting.
</p>
<p>
In Java, typecasting can be done in two ways: implicit and explicit. Implicit typecasting occurs automatically when converting from a smaller data type to a larger one (like int to double), while explicit typecasting requires you to specify the conversion manually (like double to int).
</p>
<p>
Implicit typecasting happens automatically when converting a value from a smaller data type to a larger one, as there is no risk of losing information. For example, you can assign an int to a double without any special syntax.
</p>
<pre>
int myInt = 10;
double myDouble = myInt; // Automatic casting from int to double
</pre>
<p>
Explicit typecasting is required when converting from a larger data type to a smaller one, as you might lose data. You must do this manually by placing the target type in parentheses () before the value.
</p>
<pre>
double originalDouble = 9.78;
int castedInt = (int) originalDouble; // Explicitly casts double to int. The value of castedInt is now 9.
</pre>
<p>
Besides primitive types, type casting is also a fundamental concept when working with objects, especially within an inheritance hierarchy. This involves converting an object reference from one class type to another, typically between a superclass and a subclass. This is often referred to as upcasting and downcasting.
</p>
<p>
Let's imagine we have a simple class hierarchy: an <c>Animal</c> superclass and a <c>Dog</c> subclass.
</p>
<pre>
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks!");
}
}
</pre>
<p>
<strong>Upcasting (Implicit):</strong> Upcasting is casting a subclass instance to a superclass reference type. This is always safe because a subclass object is guaranteed to have all the methods and properties of its superclass. Therefore, upcasting is done implicitly by the compiler.
</p>
<pre>
// A Dog object is created, but the reference is of type Animal.
// This is implicit upcasting.
Animal myAnimal = new Dog();
myAnimal.makeSound(); // This is valid, as makeSound() is defined in Animal.
// myAnimal.bark(); // This would cause a compile-time error!
// The compiler only knows about the methods in the Animal reference type.
</pre>
<p>
<strong>Downcasting (Explicit):</strong> Downcasting is casting a superclass reference back to its original subclass type. This is potentially unsafe because the superclass reference might not actually point to an object of the target subclass. You must perform an explicit cast. If you cast to the wrong type, Java will throw a <c>ClassCastException</c> at runtime.
</p>
<p>
To safely downcast, you should first check the object's type using the <c>instanceof</c> operator.
</p>
<pre>
// 'myAnimal' is an Animal reference, but it points to a Dog object.
if (myAnimal instanceof Dog) {
// The check passed, so this downcast is safe.
Dog myDog = (Dog) myAnimal;
// Now we can access methods specific to the Dog class.
myDog.bark(); // This is now valid.
}
</pre>
<p>
In this example, we first create a <c>Dog</c> object and assign it to an <c>Animal</c> reference (upcasting). Then, we check if the <c>Animal</c> reference is actually pointing to a <c>Dog</c> object before downcasting it back to a <c>Dog</c> reference.
</p>
</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>
<note>
<p>
The Java code below contains the first mention of the <idx><c>null</c></idx> <c>null</c> literal. Similar to Python’s <c>None</c> object, <c>null</c> in Java is used to indicate that a variable does not currently reference any object in memory. This is often used for variables that have not yet been initialized or for methods that return no object.
</p>
</note>
<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>
<p>
This program reads the file <c>alice30.txt</c> (which follows), and it then splits it into a list of words. Next it creates a dictionary called <c>count</c> which maps each word to the number of times that word occurs in the text. Finally, it prints out the words in alphabetical order along with their frequency.
</p>
<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>
<section xml:id="chapter4_summary">
<title>Summary & Reading Questions</title>
<p><ol label="1">
<li>
<p>All variables must be declared with their type before use in Java due to static typing.</p>
</li>
<li>
<p>Java has primitive types (<c>int</c>, <c>float</c>, <c>double</c>, <c>char</c>, <c>boolean</c>) and their corresponding Object wrapper classes (<c>Integer</c>, <c>Float</c>, <c>Double</c>, <c>Character</c>, <c>Boolean</c>) with automatic conversion between them called autoboxing.</p>
</li>
<li>
<p>The <c>import</c> statement in Java allows you to use shortened class names instead of fully qualified names like <c>java.util.Scanner</c>.</p>
</li>
<li>
<p><c>Scanner</c> objects are used to read input from various sources, including <c>System.in</c> for keyboard input.</p>
</li>
<li>
<p>Java Strings are immutable like Python, but use methods like <c>charAt()</c> and <c>substring()</c> instead of indexing operators.</p>
</li>
<li>
<p><c>ArrayList</c> is Java's dynamic array implementation that is similar to Python lists, but must declare the type of objects it contains using generics like <c>ArrayList<Integer></c>.</p>
</li>
<li>
<p>Maps (<c>HashMap</c> and <c>TreeMap</c>) are Java's equivalent to Python dictionaries for storing key-value pairs.</p>
</li>
</ol></p>
<reading-questions xml:id="rqs-summary4">
<exercise label = "summary-arraylist">
<statement>
<p>What is the correct way to declare an ArrayList that will hold String objects in Java?</p>
</statement>
<choices>
<choice correct="yes">
<statement>
<p>ArrayList<String> list;</p>
</statement>
<feedback>
<p>Good job!</p>
</feedback>
</choice>
<choice>
<statement>
<p>ArrayList list;</p>
</statement>
<feedback>
<p>No, you must specify the type of objects it will hold using generics.</p>
</feedback>
</choice>
<choice>
<statement>
<p>ArrayList[String] list;</p>
</statement>
<feedback>
<p>No, the syntax for generics uses < > brackets, not [ ].</p>
</feedback>
</choice>
<choice>
<statement>
<p>ArrayList() list;</p>
</statement>
<feedback>
<p>No, this is not a valid declaration.</p>
</feedback>
</choice>
</choices>
</exercise>
<exercise label = "summary-autoboxing">
<statement>
<p>The process of automatically converting between primitive types and their Object wrapper classes in Java is called:</p>
</statement>
<choices>
<choice correct="yes">
<statement>
<p>Autoboxing</p>
</statement>
<feedback>
<p>Right! Good job!</p>
</feedback>
</choice>
<choice>
<statement>
<p>Casting</p>
</statement>
<feedback>
<p>No, casting is manually converting a type.</p>
</feedback>
</choice>
<choice>
<statement>
<p>Overloading</p>
</statement>
<feedback>
<p>No, overloading refers to methods, not type conversion.</p>
</feedback>
</choice>
<choice>
<statement>
<p>Unboxing</p>
</statement>
<feedback>
<p>No, unboxing is the reverse of autoboxing.</p>
</feedback>
</choice>
</choices>
</exercise>
<exercise label = "summary-string-methods">
<statement>
<p>Which method would you use to get the character at position 3 in a Java String called str?</p>
</statement>
<choices>
<choice correct="yes">
<statement>
<p>str.charAt(3)</p>
</statement>
<feedback>
<p>Correct!</p>
</feedback>
</choice>
<choice>
<statement>
<p>str[3]</p>
</statement>
<feedback>
<p>No, Java does not support this type of indexing.</p>
</feedback>
</choice>
<choice>
<statement>
<p>str.get(3)</p>
</statement>
<feedback>
<p>No, this method does not exist in Java.</p>
</feedback>
</choice>
<choice>
<statement>
<p>str.substring(3)</p>
</statement>
<feedback>
<p>No, this will return a substring starting at position 3, not a single character.</p>
</feedback>
</choice>
</choices>
</exercise>
</reading-questions>
</section>
</chapter>