PDF Reviewing Java Second Edition Alex Maureau download
PDF Reviewing Java Second Edition Alex Maureau download
com
https://ebookgate.com/product/reviewing-java-second-edition-
alex-maureau/
OR CLICK HERE
DOWLOAD NOW
https://ebookgate.com/product/corporations-and-contract-law-second-
edition-edition-alex-wan/
ebookgate.com
https://ebookgate.com/product/polaris-the-second-book-in-the-alex-
benedict-series-first-edition-jack-mcdevitt/
ebookgate.com
https://ebookgate.com/product/building-java-programs-a-back-to-basics-
approach-second-edition-stuart-reges/
ebookgate.com
https://ebookgate.com/product/schaum-s-outline-sof-data-structures-
with-java-second-edition-john-hubbard/
ebookgate.com
Introduction to Neural Networks with Java 1 st Edition
Second printing Heaton Jeff.
https://ebookgate.com/product/introduction-to-neural-networks-with-
java-1-st-edition-second-printing-heaton-jeff/
ebookgate.com
https://ebookgate.com/product/reviewing-qualitative-research-in-the-
social-sciences-1st-edition-audrey-a-trainor/
ebookgate.com
https://ebookgate.com/product/reviewing-research-evidence-for-nursing-
practice-systematic-reviews-1st-edition-christine-webb/
ebookgate.com
https://ebookgate.com/product/java-2-micro-edition-java-in-small-
things-james-white/
ebookgate.com
https://ebookgate.com/product/bait-1st-edition-alex-sanchez/
ebookgate.com
REVIEWING JAVA
SECOND EDITION
The Best Resource for Beginners
Alex Maureau
2
Visit:
www.cstutoringcenter.com/problems
for some fun programming challenges in Java.
3
Special Thanks To
Dani Maureau
My beautiful, supportive wife & the English teacher who
helped edit this book. I love you now and forever.
Matthew McClure
Computer Science wizard who initially inspired me to update
my books with his total nerdgasm once he found out I wrote
them.
Anne Smith-Thompson
For making last minute contributions and changes to this
book. And for being a great professor and friend!
Stephanie Gallagher
For giving me the last bit of inspiration I needed to
update this book. And who also gave me this funny exchange:
Her: “I saw him with your book and I was like ‘I know that
guy!’”
Me: “That’s awesome. What a small world!”
Her: “And I thought, ‘Oh, Java? Like Java the Hut!’”
Me: “It’s not Java the Hut!!...but that’s so going in the
book now.”
4
PREFACE
As many students embark on learning Java, some find it a challenge, and others find it
as easy as others find it impossible. I’ve learned that there are many students who are
willing to just give up at the drop of a hat or even after they fail miserably on the first
exam (i.e. the “JOptionPane” exam).
During my own experiences, I realized that there are quite a few students who do not
want to come into my office and ask me questions. To this day I still do not know why.
Perhaps it is the stigma of the tutor or aide; too nerdy or “geeky” for some, or not
important enough to others. I was once the latter, but quickly snapped out of it once I
embarked on my computer science career.
This material is written to give hope to those lost students who have to take a
programming class as it is mandated by their degree requirements, or those students
who are anxious to learn a new subject. I hope you find this information helpful and
understandable, so that you have a pleasant experience with Java programming. The
material contained herein is a summary of the major topics of Java.
5
TABLE OF CONTENTS
Material
CHAPTER 1
An Introduction to Java ……………………....……………………………… 9
CHAPTER 2
Variables & Operators .…………………….…………………………….. 16
CHAPTER 3
Wrapper Classes & Parsing ..……………………………………………. 39
CHAPTER 4
Input/Output Techniques .…….…………………………………………. 49
CHAPTER 5
Decisions & Logic ………..…….……………………………………….... 59
CHAPTER 6
Strings in Java ………...……..…………………………………………... 88
CHAPTER 7
Looping ………..……….…….…………………………………………... 114
CHAPTER 8
Methods ………..……….…….………………………………………….. 143
CHAPTER 9
Recursion ...………………….…………………………………………… 175
CHAPTER 10
Arrays ..…………………….…………………………………………..... 196
CHAPTER 11
Some Useful Libraries .….……………………………………………..… 249
6
CHAPTER 12
Some Sorting Techniques …….……………………………………...….. 278
CHAPTER 13
Working with Classes & Objects ……………………………………..…. 288
CHAPTER 14
Inheritance ...…………………………………………………………….. 309
CHAPTER 15
Exceptions ………...……………………………………………………… 338
CHAPTER 16
File Input/Output ………..……………….……………………………… 351
CHAPTER 17
Abstract Classes & Interfaces .…………………………………………… 369
CHAPTER 18
Threading & Multitasking ...…………………………………………….. 395
CHAPTER 19
Introduction to Generics, Collections, & Enums ………………………… 408
CHAPTER 20
Data Structures & the java.util Library ...………………………………... 430
CHAPTER 21
Dealing with Dates & Times ...………………………………………….. 482
Appendices
APPENDIX A
ASCII Chart ……………………………………………………………… 521
APPENDIX B
Number Conversions ………………………………………………….…. 522
7
APPENDIX C
The Game of Keno ……………..………………………………………… 535
APPENDIX D
Programming Challenges…………………………………………………. 565
APPENDIX E
Jeopardy! Fun! How Much Can You Win on the Game of Jeopardy! …… 575
8
CHAPTER 1
An Introduction to Java
TOPICS
1. Console Input/Output 10
2. Hello World Program 11
3. Command Line Arguments 12
4. Documentation & Javadoc 14
5. Terminating Programs 15
9
Java is a high level programming language that is strictly object-oriented. That means
there is nothing but objects and classes that make up the language. So what parts are
there to a class?
Constructor
A constructor will build the class. A class or object does not exist
until you construct it. All classes are instantiated with the word
new.
All Java programs, AT THE BARE MINIMUM, will look like this:
Where in the above, Name is the useful name of the object (class) for the start of the
program; and the main method always looks like that. The argument of the main
method is an array of Strings that represent command line arguments.
A lot has happened here in just a short time. Each part will become clearer as each
chapter unfolds.
CONSOLE INPUT/OUTPUT
All basic input and output streams are contained in the System library. Below is a
description of some methods contained in that library:
10
System.out.print( things to print )
This will simply print something to the console. It can print a
variable, String, character, double, Object, etc… When attempting to
print something, it will look for a toString method that will handle
the conversion needed. This method does not print a new line character
at the end.
Let’s create the most basic program. The program is collectively called the “Hello
World” program, which will simply print a message to the console.
As stated, the above program will print the message to the console.
To compile a Java program, you need to use the built in compiler for the command line
called javac. That stands for “java compiler.” The general format for compiling a
program is:
javac FileName.java
where FileName is the name of the java file to compile. To compile multiple Java
programs all at once, you may do this:
11
javac *.java
where the * will compile all filenames with the java extension. So using the above
example of “Hello World,” here is how to compile it:
javac Hello.java
A Java program can contain what’s called a command line argument. When compiling
a program, you can give certain values to the main method’s array of arguments.
Let’s see an example that will allow you to enter your first and last name in the
command line.
The above program will execute first by checking the number of command line
arguments (more details emerge on this aspect later in Chapter 10). It will then print
out the name entered by the user, since we know the arguments are correct. The user’s
first name is contained in args[0] and the last name is contained in args[1]. More on
Strings and arrays will follow later.
Take note that in the above the + operator is used to join (or concatenate) Strings.
12
Here is the command line for compiling and executing. To compile the program:
javac Example1.java
To run the program, simply replace the message in the quotes with your first and last
name, respectively, WITHOUT THE BRACKETS:
Also note that the arguments are separated by a space. This allows the array to note the
separate arguments. Say that we ran the program above with the following command
line:
We get the error message because the program did not contain the proper number of
command line arguments. Now if we ran the program with this command line:
Please see Chapter 3 (Wrapper Classes & Parsing) for more on command line
arguments and their use.
13
DOCUMENTATION & JAVADOC
An important part of programming is documentation. Without it, you can run into a lot
of trouble when trying to debug a program. There are three types of documentation for
a program in Java; in-line comments, block comments and Javadoc comments.
The first type of comment is an in-line comment that may look like this:
The in-line comment is denoted by the two forward slashes. Anything appearing on
that line past those two markers is ignored by the compiler.
The second type of comment is the block comment that may look like this in a code
snippet:
Note that to START the block comment, there is the /* while to END the block
comment, there is the */. They are different from each other so be careful.
The final piece of commenting is Javadoc. The Javadoc comments are written thusly:
/**
* Javadoc writing here. The Javadoc will explain
* and document a method.
*/
public static void main(String args[]){
//code here for main
}
14
One important note is to realize that there is a /** to begin the Javadoc and the */ to
finish it. If you are using a fancy schmancy environment such as Eclipse, it will turn
blue to signify Javadoc. A block comment and in-line comment will turn green.
A good view of Javadoc is to take a look at the current Java APIs online at
https://docs.oracle.com/en/java/
TERMINATING PROGRAMS
To terminate a program earlier than it should be, you can use the exit() method in the
System library. The syntax will be as follows:
System.exit(1);
You can of course replace the number 1 with any integer of your choosing. Mostly, 0
and 1 are used. One is used to denote a problem and signal to a debugger that there is
an early termination. Zero is used to state that there are no issues. Again, it is not a
requirement to just use 0 and 1, but rather the most commonly-used integers for this
purpose.
15
CHAPTER 2
Variables & Operators
This chapter discovers what variables are and how we can work
with them in a program. Variables are essential to programming.
This chapter covers the many different data types of variables and
how we can operate on them.
TOPICS
1. Declaring Variables 17
2. Data Types 17
3. Variable Exercises 19
4. Operators 19
5. Operator Exercises 27
6. Example Programs 28
7. Types of Variables 31
8. Type Casting 34
9. Overflow 35
10.Overflow Exercises 37
16
In Java, a variable will be used to hold some form of data. That data can be of any type,
such as an integer, decimal or character, or a custom data type (we will explore that
later in the book), just to name a few.
While variables hold some form of data, we want to be able to work with them in a
program, or “operate” on them as it’s called. By operating on variables, you can assign
information/data to them, modify data, perform mathematical operations, perform
logical operations -- basically anything you need to do run your program.
DECLARING VARIABLES
There are numerous ways to use and declare variables in Java. Here is one of the ways
to declare a variable:
Where in the above, identifier can be public, private, protected or nothing (see later); type
is the data type of the variable and var_name is a useful name of the variable.
You can also declare a variable and assign a value to it. This is called initializing the
variable.
Where in the above, identifier can be public, private, protected or nothing (see later); type
is the data type of the variable; var_name is a useful name of the variable; and
initial_value is the default value given to a variable.
DATA TYPES
While we now know how to declare a variable, we need to know both the different data
types, as well as how to operate on them. The below chart consists of the primitive data
types used in Java (note: String is not primitive, but will be used frequently throughout
the book).
17
Type Name Description Size
char Character or small integer. 1 byte
Signed range: -128 to 127
Unsigned range: 0 to 255
short Short Integer. 2 bytes
Signed: -32768 to 32767
Unsigned: 0 to 65535
int Integer. 4 bytes
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
long Long Integer. 4 bytes
Signed: -2147483648 to 2147483647
Unsigned: 0 to 4294967295
boolean Boolean value. Either true or false. 1 byte
Acceptable as 1 or 0, respectively.
float Floating point number. 4 bytes
3.4e +/- 38 (7 digits)
double Double precision floating point number. 8 bytes
1.7e +/- 308 (15 digits)
String A class dedicated to strings in Java (more on this in
Chapter 6). Note, the S is capitalized and must be in
order for Java to recognize this type.
Let’s show a few examples of declaring variables below with the certain data types:
18
VARIABLE EXERCISES
DIRECTIONS: Answer each question below to the best of your ability. Solutions on page 588.
Problem 1:
Declare each of the following types of variables. Do not initialize, just declare them.
Problem 2:
Declare and initialize each of the above variables in problem 1. You may choose to
initialize them to any value (in its correct range), as well as any way you wish. They
must match the data type of the variable.
OPERATORS
Now that we know a bit about variables, we can now know how to operate on them.
An operator performs an action on a variable(s). It can assign values (the = operator),
perform arithmetic (+, -, *, /), concatenate String objects (the + operator), as well as many
more things that we will explore.
Below is a collection of operators and the category under which each falls. Examples for
each of these operators will follow the chart.
19
* Arithmetic Multiplication Performs the multiplication of a
variable(s)
/ Arithmetic Division Performs the division of a variable(s)
% Arithmetic Modular Performs the modular division of a
Division variable(s)
++ Arithmetic Pre/post Increase the value of a variable by 1
increment
-- Arithmetic Pre/post Decrease the value of a variable by 1
decrement
== Relational Equals Evaluates whether both sides of an
expression have the same truth value.
!= Relational Does not equal Evaluates whether both sides of an
expression do not have the same truth
value.
> Relational Strictly greater One side of an expression must be
than strictly greater than the other side in
order to return an overall value of true.
>= Relational Greater than or One side of an expression can be greater
equal to than or equal to the other side, in order
to return an overall value of true.
< Relational Strictly less One side of an expression must be
than strictly less than the other side in order
to return an overall value of true.
<= Relational Less than or One side of an expression can be less
equal to than or equal to the other to return an
overall value of true.
&& Logical Logical And All elements of an expression must be
true in order to return an overall value
of true.
|| Logical Logical Or One side of an expression must be true
in order to return an overall value of
true.
! Logical Logical Not (or This will invert (or negate) a piece of or
Negate) the entire expression, turning true to
false and false to true.
+= Compound Plus Equals Performs the addition of an expression
Assignment/ or concatenation of String objects and
Compound then assigns that value to the variable.
Concatenation
20
-= Compound Minus Equals Performs the subtraction of an
Assignment expression and then assigns that value
to the variable.
*= Compound Multiply Performs the multiplication of an
Assignment Equals expression and then assigns that value
to the variable.
/= Compound Divide Equals Performs the division of an expression
Assignment and then assigns that value to the
variable.
%/ Compound Mod Equals Performs the modular division of an
Assignment expression and then assigns that value
to the variable.
Assignment Operators
= Assignment
This operator assigns a value to a variable(s).
//declare two String variables fname and lname and assign values
String fname, lname;
fname = "Alex";
lname = "Maureau";
21
x = y = 5;
Arithmetic Operators
+ Addition
Performs the addition of a variable(s).
- Subtraction
Performs the subtraction of a variable(s).
* Multiplication
Performs the multiplication of a variable(s).
/ Division
Performs the division of a variable(s).
//finds the sum of the variables named x and y and assigns the value to
//the sum variable
sum = x+y;
//finds the difference of the variables named x and y and assigns the
//value to the diff variable
diff = x-y;
//multiplies the variables named x and y and assigns the value to the
//prod variable
prod = x*y;
22
There are also times when you may want to perform modular division. This can be
represented as follows:
% Modular Division
The modulo division of two numbers is the remainder when the number on
the left is divided by the number on the right.
3 % 5
Evaluates to 3 as 5 goes into 3 ZERO times, with a remainder of 3.
19 % 10
Evaluates to 9 as 10 goes into 19 ONE time, with a remainder of 9.
7 % 3
Evaluates to 1, since 3 goes into 7 TWO times, with a remainder of 1.
15 % 1
Evaluates to 0, since any number MOD 1 is 0 as 1 goes into that number
fully.
12 % 0
This will evaluate to a compiler error, since you cannot divide by 0.
4 % 4
This will evaluate to 0, since any number MOD itself goes into itself
fully with no remainder.
23
Relational/Equality Operators
== Logical Equals
Both sides of a statement must have the EXACT same value in order to
return an overall value of true.
(7 == 5)
Evaluates to FALSE as 7 does not equal the value of 5.
((4 + 5) == (5 + 3 + 1)
Evaluates to TRUE, since 9 is equal to 9. This performs the operations
inside the parentheses first and then evaluates the logic.
(5 % 2 == 1)
Evaluates to TRUE, since 5 MOD 2 is 1. This first evaluates the modular
division and then evaluates the logic.
(9 > 12)
Evaluates to FALSE, since 9 is not strictly greater than 12.
24
(9 >= 9)
Evaluates to TRUE, since 9 is greater than or equal to 9.
(12 – 4 <= 7 * 2)
Evaluates to TRUE, since 8 is less than or equal to 14.
(4 != (3 + 1))
Evaluates to FALSE as 4 is, in fact, equal to 4. This performs the
action inside the parentheses first and then evaluates the expression.
Logical Operators
|| Logical Or
One or more elements of the statement must be true in order to return
an overall value of true.
! Logical Not
This will “invert” or “negate” a piece of the expression. In other
words, if a piece of the expression evaluates to true, this will invert
that to false and vice versa.
((4 != 3) || (5 != 5))
Evaluates to TRUE, since one side of the expression evaluates to true.
With the logical || operator, only one side needs to have a truth value
of true in order for the entire statement to be true.
25
5. The logical OR only requires one side of the expression to be true
in order to return the overall value of true.
!(7 == 5)
Evaluates to TRUE as 7 does not equal the value of 5 however, we are
inverting the overall value by use of the ! operator.
Increase/Decrease Operators
++ Pre/Post Increment
Increase the value of a variable by 1. If the ++ comes before the
variable you want to increment, it will increase the value FIRST before
using it. If it comes AFTER the variable, the program uses the current
value of the variable first, THEN increases it.
-- Pre/Post Decrement
Decrease the value of a variable by 1. If the -- comes before the
variable you want to decrement, it will decrease the value FIRST before
using it. If it comes AFTER the variable, the program uses the current
value of the variable first, THEN decreases it.
+= Plus Equals
Shorthand operator for adding and then assigning a value to a variable.
This can be translated to something similar to the below:
a += 3 MEANS a = a + 3;
x += x MEANS x = x + x;
-= Minus Equals
Shorthand operator for subtracting and then assigning a value to a
variable. This can be translated to something similar to the below:
a -= 3 MEANS a = a - 3;
x -= x MEANS x = x - x;
*= Multiply Equals
26
Shorthand operator for multiplying and then assigning a value to a
variable. This can be translated to something similar to the below:
a *= 3 MEANS a = a * 3;
x *= x MEANS x = x * x;
/= Divide Equals
Shorthand operator for dividing and then assigning a value to a
variable. This can be translated to something similar to the below:
a /= 3 MEANS a = a / 3;
x /= 8 MEANS x = x / 8;
%= Mod Equals
Shorthand operator for performing modular division and then assigning a
value to a variable. This can be translated to something similar to the
below:
a %= 3 MEANS a = a % 3;
x %= 2 MEANS x = x % 2;
Each operator above may have different meanings when dealing with different topics.
For example, the + operator relates to addition, but it can also concatenate strings. More
on those scenarios as the book progresses.
OPERATOR EXERCISES
DIRECTIONS: Answer each question below to the best of your ability. Solutions on page 588.
Problem 1:
Identify each of the following operators and briefly explain what it does:
a. &&
b. ||
c. =
d. +=
e. %
f. ++
g. %=
h. *
i. <
j. >=
k. ==
27
Problem 2:
Given the following examples, answer to the best of your ability:
a. 12 % 3 ___________
b. 4 % 7 ___________
c. 6 % 3 ___________
d. 77 % 10 ___________
e. 100 % 100 ___________
f. 99 % 1 ___________
g. (9 % 9) % 9 ___________
h. (((44% 10) % 10) % 10) ___________
Problem 3:
Given the following snippets, what will be produced as the truth value:
EXAMPLE PROGRAMS
Below are some examples that show the use of most of the above operators. Each
example is explained in detail following the code. NOTE: Some of these programs will be
modified later in the book when dealing with wrapper classes and objects.
This program will perform addition, subtraction, multiplication, division, and modular
division on two integers.
28
//addition
System.out.println("The sum is: " + (a+b));
//subtraction
System.out.println("The difference is: " + (a-b));
//multiplication
System.out.println("The product is: " + (a*b));
//division
System.out.println("The quotient is: " + (a/b));
//modular division
System.out.println("The a mod b is: " + (a%b));
} //main
} //class
This program will calculate the change needed in the number of quarters, dimes,
nickels and pennies.
q = x / 25;
x = x % 25;
d = x / 10;
29
x = x % 10;
n = x / 5;
c = x % 5;
Say that the user needs 90 cents in change. The first thing that the program needs to do
is calculate the quarters. Here, 90 divided by 25 is 3. Note that the int DOES NOT
handle decimals and only looks at whole numbers. It then stores 3 into the variable q.
Then, the new value of x is calculated by placing the remainder when 90 is divided by
25. Here, it is 15.
Now, the dimes are calculated by taking 15 (since that is current value of x) and
dividing it by 10 which produces 1 (again, the int ignores the decimals). Now, the new
value of x is 15 mod 10, which is 5.
The program will then calculate the nickels and cents accordingly.
EXAMPLE 3: Incrementing/Decrementing
This program will show the use of the operators for incrementing and decrementing a
number. This also shows the order of the operators.
30
System.out.println("The number 5:");
//"pre" increment:
System.out.print(++num);
//"post" decrement:
System.out.print(num--);
//"pre" decrement:
System.out.print(--num);
} //main
} //class
Let’s see why the output is this way. First, the value of the variable num is 5. The first
operator that is used on the variable is the "post" increment operator. This uses the
variable first (for output) THEN increments it. So the output is 5, BUT THE VARIABLE
HOLDS THE VALUE 6.
The number 5:
5775
TYPES OF VARIABLES
While we have a basic understanding of variables and operators, we need to know that
there are different categories of variables used in this language. Those are local
variables, static variables, and instance variables. But first, we must learn about access
levels.
Access Levels
31
[identifier] type var_name;
Where identifier can be either public, private or protected, or nothing; type is the data
type of the variable; and var_name is a useful name of the variable.
Access levels determine whether or not other classes can see and use a particular
method or variable. There are 4 types of access levels as can be declared:
Public
A class, variable, or method can be declared public, in which case it
is visible to all classes everywhere.
Private
A variable or method can be declared private, but they cannot be
accessed outside the class in which they appear. A class cannot be
declared private.
Protected
Methods or data members declared as protected are accessible within the
same package or subclasses in a different package.
Local Variables
Local variables are just as they sound; they are only able to be accessed & used within
the method or block of code in which they are declared. For example, see the program
below:
32
The int variable x and the char variable c are local to the main() method in the Example
class. They can not be accessed or used anywhere else in the program. The output from
above will simply be 4, since that is the variable’s initial value.
Instance Variables
A class or object can have its own variables. These are what’s called instance variables.
By its definition, an instance variable is unique to each instance of the object; so in
general, each time a class is constructed, there is another instance of the variable
associated with it.
These variables are declared outside any methods you may have, including main().
These variables are declared either public, private, protected, or with no identifier, as
mentioned earlier. They are global to the class or object in which they appear. Let's see a
small example.
//code
}
} //class
Static Variables
Static variables are quite a bit harder to understand. Do not be confused with a static
variable from C++. They are very different.
In Java, a static variable (also called a class variable), is a variable that is given a fixed
block of memory. The static keyword tells the compiler that there is exactly one copy of
this variable in existence, no matter how many times the class has been constructed.
Let's just think of a real world example. Say you own a car. The car will always have
four wheels. If you made a class in Java called Car, a variable called numWheels can be
33
made static, since it will be the same for every car. Similarly with fruit, an orange will
always be an orange color, so a color variable in an Orange class can be static.
Final Variables
In C++, we can declare variables constant if we know their values will not change. In
Java, we do not use the keyword const, but we use the keyword final. Final variables
cannot be changed and are made constant. They can be either instance, static or local
variables or even local to a method.
A common practice is to make the final variable’s name all capital letters. So here is
what something may look like:
TYPE CASTING
In Java, we can allow a variable to change its current data type by casting it to another
data type. There are two types of casting: implicit and explicit.
Implicit Casting
Implicit casting is when the data type is changed automatically in the program. We do
not need to explicitly tell the program to cast.
Automatic casting
This occurs in the compiler as it tries to compile your program:
int x = 5.667; //automatically changed to 5
float f = 7; //automatically changed to 7.0
“Promotion” casting
This occurs when more space is given to a number (i.e. short to int or int to long):
int I = 6;
long u = I; //promoted here to long.
34
“Demotion” casting
This occurs when less space is given to a number (i.e. int to short):
double d = 8.9;
float f = d; //demoted here from double.
Explicit Casting
Explicit casting is when we need to tell the program to change the type. This is done by
placing the data type in parentheses next to the expression.
Say we wanted to compute the average of some integers, and just wanted to output the
whole number from the average, ignoring the decimal places. Here is a program that
will do this:
We cast in two places with the above program. First, we cast the sum of the 3 integers
to a double precision value and divide by 3.0. We need to do this, otherwise we get
incorrect division.
We also cast in the final result changing the answer from the double precision value to
an int value. This program will output 7 when run, but note that the real average is
7.333333333333333.
OVERFLOW
In Java, variables can overflow their capacity. For instance, if you were to declare the
following piece of code:
short z = 10000;
z = z + 40000;
35
System.out.println( z );
-15536
The reason behind this is that you ran out of room to represent the number in its binary
form. That is a bit technical to discuss here, but just know that if you see a negative
number when it is supposed to be positive, you overflowed the number!!! The solution
is to use a bigger data type.
10000
-32536
10000000
123456789
-714149102
1569325055
NOTE: Depending on the compiler you have, it may not even compile (for instance in
Eclipse). If you use command line Java, it may work out to the output above.
36
The first number will work just fine (being the short(10000)), since that is in range. The
following short(33000) is just a bit out of range, so it will give you the -32536 you see on
screen.
Then, both the int values are still in range, so they will be just fine, however both the
long values are not! It may appear that a long holds more numbers, but certainly not
numbers that big!!!
CASTING EXERCISES
DIRECTIONS: Answer each question below to the best of your ability. Solutions on page 589.
Problem 1:
Observe each type of casting and explain what will be printed on screen with the
println statement:
a.
int x = 99;
short xx = x;
System.out.println( xx );
b.
double c = 55.344;
System.out.println( ((int) c) );
c.
long n = 9999.999;
double nn = n;
System.out.println( nn );
d.
int q = 499;
double x = 2.1;
long qq = q + ((int) x);
System.out.println( qq );
Problem 2:
Identify which of the following values are out of range (or in other words, overflow) for
the following lines of println statements:
37
d. System.out.println( (long) 44444444444 );
e. System.out.println( (char) 257 );
f. System.out.println( (double) 999999.9999999 );
g. System.out.println( (float) 43*100+7 );
h. System.out.println( (double) 777*777*10 );
i. System.out.println( (short) -40000 );
j. System.out.println( (int) -99955533322 );
38
CHAPTER 3
Wrapper Classes & Parsing
TOPICS
1. Wrapper Classes 40
2. Character Wrapper Class 44
3. Defining Numbers 44
39
Each primitive data type in Java (int, short, long, float, double, char, and boolean) has
its own wrapper class. But what is a wrapper class?
WRAPPER CLASSES
Integer
Methods for an int data type.
Short
Methods for a short data type.
Long
Methods for a long data type.
Double
Methods for a double data type.
Float
Methods for a float data type.
Character
Methods for a char data type.
Boolean
Methods for a boolean data type.
Each of the above wrapper classes contains a very important method that will parse (or
convert) any String, either a command line argument or a String object, into the
appropriate data type. Those methods are defined below:
Integer.parseInt(String val)
Returns an int value from a String representation of a number. A
NumberFormatException is thrown if the argument is not a String
representation of a number.
Short.parseShort(String val)
Returns a short value from a String representation of a number. A
NumberFormatException is thrown if the argument is not a String
representation of a number.
40
Long.parseLong(String val)
Returns a long value from a String representation of a number. A
NumberFormatException is thrown if the argument is not a String
representation of a number.
Double.parseDouble(String val)
Returns a double precision value from a String representation of a
number. A NumberFormatException is thrown if the argument is not a
String representation of a number.
Float.parseFloat(String val)
Returns a float value from a String representation of a number. A
NumberFormatException is thrown if the argument is not a String
representation of a number.
This program will perform addition, subtraction, multiplication, division, and modular
division of two integers. This is the modified version of the program from the previous
chapter. This one uses two command line arguments and parses them accordingly to
perform the arithmetic.
//addition
System.out.println("The sum is: " + (a+b));
//subtraction
System.out.println("The difference is: " + (a-b));
//multiplication
System.out.println("The product is: " + (a*b));
41
//division
System.out.println("The quotient is: " + (a/b));
//modular division
System.out.println("The a mod b is: " + (a%b));
} //main
} //class
The difference between this program and the previous chapter is the fact that you are
now using command line arguments.
A sample run of the program will produce the following output (with command line
arguments 5 4:
This program will calculate the change needed in the number of quarters, dimes,
nickels, and pennies. The value is entered from the command line and will be parsed to
an int.
q = x / 25;
x = x % 25;
d = x / 10;
x = x % 10;
n = x / 5;
c = x % 5;
42
System.out.println("Quarters: " + q + "\nDimes: " + d +
"\nNickels: " + n + "\nCents: " + c);
} //main
} //class
Running it off the command line and giving it the command line argument of 90, a
sample run of this program from the above is:
This program will take 3 command line arguments and calculate the average of those
values. It makes use of the Double wrapper class to do the calculations as needed.
43
CHARACTER WRAPPER CLASS
An important class that contains some useful methods is the character wrapper class.
There are methods that will check if a character is a digit, letter, etc… as well as
uppercase, lowercase, etc…
boolean isDigit(char c)
This method will return true if the character argument is a digit from
0 to 9. Else, it will return false.
boolean isLetter(char c)
This method will return true if the character argument is a letter
from, EITHER UPPERCASE OR LOWERCASE. Else, it will return false.
boolean isUpperCase(char c)
This method will return true if the character argument is an uppercase
letter. Else, it will return false.
boolean isLowerCase(char c)
This method will return true if the character argument is a lowercase
letter. Else, it will return false.
boolean isWhiteSpace(char c)
This method will return true if the character argument is a white space
character. Else, it will return false.
As seen in the program, these methods are utilized to keep track of the different types
of characters in the String argument.
DEFINING NUMBERS
Each respective numeric wrapper class (Short, Integer, Long, Float, and Double), have
methods that return its value as a primitive data type (short, int, long, float, and
double). They are defined below and can be accessed from the respective wrapper class:
short shortValue()
This method will return a short value representing the numeric value of
the object.
44
int intValue()
This method will return an int value representing the numeric value of
the object.
long longValue()
This method will return a long value representing the numeric value of
the object.
float floatValue()
This method will return a float value representing the numeric value of
the object.
double doubleValue()
This method will return a double precision value representing the
numeric value of the object.
So far, we have just used primitive data types for our desired numeric variables.
However, it is perfectly acceptable to do something like this:
Etc…
It is also acceptable to do the following (good practice is to be sure the values will not
overflow):
Etc…
The below program will showcase the numerous value methods as described above.
45
Double n1 = new Double("4.59234");
Integer n2 = 5;
current value: 5
short value: 5
int value: 5
long value: 5
float value: 5.0
double value: 5.0
This program will again calculate the change needed in the number of quarters, dimes,
nickels, and pennies. The value is entered from the command line.
46
public class Example5{
public static void main(String args[]){
//convert the command line argument here
Integer x = new Integer(args[0]);
q = x / 25;
x = x % 25;
d = x / 10;
x = x % 10;
n = x / 5;
c = x % 5;
Running it off the command line and giving it the command line argument of 90, a
sample run of this program from the above is:
This program will take 3 command line arguments and calculate the average of those
values. It makes use of the Double wrapper class to do the calculations as needed.
47
n3 = new Double(args[2]);
//display result
System.out.println("The average is: " + avg);
} //main
} //class
The output is the same as example 3 above. This was just another way of writing the
code.
48
CHAPTER 4
Input/Output Techniques
TOPICS
1. Scanners 50
2. JOptionPanes 55
49
As mentioned in the first chapter, there are some different types of input and output
techniques. There is the console technique using a Scanner object, and the graphical
technique using a JOptionPane. When deciding on which one to use, it will depend on
the type of Operating System you are using, since a JOptionPane will not work on a
UNIX/LINUX environment.
SCANNERS
A Scanner will allow you to input data from the console at some point(s) in a program.
A Scanner is part of the java.util library, so this needs to be imported in order to be
used.
import java.util.Scanner;
Where in the above, var_name is a useful name for the Scanner object.
The Scanner class has some methods associated with it to gather input from a user:
nextInt()
Reads an int value from the user.
nextShort()
Reads a short value from the user.
nextLong()
Reads a long value from the user.
nextDouble()
Reads a double value from the user.
nextFloat()
Reads a float value from the user.
nextBoolean()
Reads a boolean value from the user.
50
Another Random Scribd Document
with Unrelated Content
“Wait,” he said.
He raised his head to listen. The night was still as a tomb. A cry
even from the most distant corner of the city, it seemed to him,
must carry to this open square of darkness above them. He had
time. “Yes, wait,” he repeated, and he went apart into the shadowy
patio. Never had he been set to face so tragic a dilemma. He knew
Si El Hadj Arrifa too well to doubt him. Nor indeed had he any real
doubt as to the choice which he himself would make. The choice
was in truth made, had been made from the moment he was sure
that torture and massacre threatened those who remained in Fez as
much as those who marched to Rabat. But he stood in that shadowy
court of marble and tiles, gazing with a great sorrow upon many
lovely cherished things which he was now forever to forego, his own
hopes and ambitions, a little circle of good friends, honour and good
report, a career of active service and study well-applied, and at the
end of it all a name cleansed of its stain, and—even now the picture
rose before his mind—a dreamlike high garden fragrant with roses,
from which one looked out over moonlit country to the misty barrier
of the Downs. It was such a farewell as he had never thought to
make and when he turned back into the room his face was twisted
as with a physical pain and anguish lay deep in his brooding eyes.
He took the envelope from his breast.
“I shall trust you with more than my life,” he said.
“Your Excellency has honoured me with his friendship. I am his
servant in all things.”
“I have been for three nights writing this letter. I had it in my
mind to open it here and read it to you. But the bad news you have
given me points to another way. It may be that there will be no need
to use it. I give it into your hands and I beg you to keep it sealed as
it is, until you are certain of my death. If I am alive I shall find a
means to let you know. If I am dead, I pray you to do all that I have
written here.”
Si El Hadj Arrifa took the letter and bowed his forehead upon it,
as though it carried the very Sultan’s seal.
“With God’s will, I will do as you direct.”
Paul took his friend by the hand, and looked him in the eyes.
“I could not rest quiet in my grave if my wishes written there
were not fulfilled—if misfortune struck where there is no need that it
should strike. A voice would call to me, in sorrow and distress, and I
should hear it and stir in my grave though I was buried metres deep
in clay. It is a promise?”
“Yes.”
Si El Hadj Arrifa struck a bell and a man came out to him from
the servants’ quarters.
“All is quiet, Mohammed?”
“Up till this hour.”
“His Excellency’s horse then! You will go in front of him with a
lantern as far as the Bab Segma. His Excellency returns to the camp
at Dar-Debibagh.”
The servant’s eyes opened wide in fear. He looked from his
master to his master’s guest, as though both of them had been
smitten with madness. Then he went out upon his business, and the
two men in the court heard the fall of the bars and the grinding of
the lock of the door.
“I will put this away,” said Si El Hadj Arrifa, balancing the letter in
his hands; and he went upstairs to his own room. When he came
down Paul was standing in the patio, with his cap upon his head.
“I will bid you good-bye here my friend,” said Paul, but his host,
terrified though he was, would not so far fall short of his duties. He
went out with Paul Ravenel to the street. The city all about them
was very quiet. There was no light anywhere but the light in the big
lantern which Mohammed was carrying in one hand whilst he held
the bridle of Paul’s horse with the other. Paul mounted quickly and
without a word. Si El Hadj Arrifa stood in the doorway of his house.
He watched the lantern dwindle to a spark, he heard the sharp loud
crack of the horse’s shoes upon the cobbles soften and grow dull. He
waited until the spark had vanished, and, a little time afterwards, the
beat of the hoofs had ceased. And still there was no sign of any
trouble, no distant clamour as of men gathering, no shrill cries from
the women on the roofs. He went back into his house.
ebookgate.com