(Ebook) Practice Your Java Level 1 by Ayo Agboola ISBN 9780996133814, 099613381X
(Ebook) Practice Your Java Level 1 by Ayo Agboola ISBN 9780996133814, 099613381X
(Ebook) Level 1 Practice exams for the 2010 CFA exam. Volume 1 by
Kaplan Schweser ISBN 9781427794734, 1427794731
https://ebooknice.com/product/level-1-practice-exams-for-the-2010-cfa-
exam-volume-1-1921028
ebooknice.com
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
ebooknice.com
(Ebook) A-Level Physics: AQA Year 1 & 2 Exam Practice Workbook ISBN
9781782949169, 178294916X
https://ebooknice.com/product/a-level-physics-aqa-year-1-2-exam-
practice-workbook-25592002
ebooknice.com
https://ebooknice.com/product/a-level-chemistry-edexcel-
year-1-2-complete-revision-practice-with-online-edition-cgp-a-level-
chemistry-33969770
ebooknice.com
(Ebook) Cambridge IGCSE and O Level History Workbook 2C - Depth Study:
the United States, 1919-41 2nd Edition by Benjamin Harrison ISBN
9781398375147, 9781398375048, 1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044
ebooknice.com
https://ebooknice.com/product/eyes-open-level-1-workbook-with-online-
practice-55512334
ebooknice.com
(Ebook) 2020 CFA Program Exam Prep Level 1: 2020 CFA Level 1, Book 2:
Economics (2020 CFA Level 1 Exam Prep) by Havels Learning System ISBN
9781694233448, 1694233448
https://ebooknice.com/product/2020-cfa-program-exam-prep-
level-1-2020-cfa-level-1-book-2-economics-2020-cfa-level-1-exam-
prep-10870098
ebooknice.com
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master the SAT
Subject Test: Math Levels 1 & 2) by Arco ISBN 9780768923049,
0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094
ebooknice.com
https://ebooknice.com/product/static-1-flight-29-down-51056340
ebooknice.com
Practice Your Java Level 1 1st Edition Ayo Agboola
Digital Instant Download
Author(s): Ayo Agboola
ISBN(s): 9780996133814, 099613381X
Edition: 1
File Details: PDF, 7.40 MB
Year: 2016
Language: english
Practice Your Java TM
Level 1
First Edition
Kindle Edition
To report any errors found in this book, please email the publisher at
[email protected].
Sales Information
For bulk purchases or for customized variants, please contact the publisher at
[email protected].
Trademarks
Java is a trademark of Oracle Corporation and/or its affiliates.
Microsoft, Windows®, Notepad® and C# are either registered trademarks or trademarks of
Microsoft Corporation in the United States and/or other countries.
All other trademarks remain the property of their respective owners.
Disclaimer
Care has been taken in the preparation of this book; however, no warranty express or implied of
any kind is made for the content thereof or for errors or omissions herein. No liability is assumed
by the author, publisher or seller for any damages in connection with or arising out of the use of
any of the content of this book.
Rights
All rights reserved. No part of this publication may be reproduced, stored or transmitted in any
form without the express written permission of the publisher.
Introduction
Welcome to Practice Your Java Level 1! This is a book designed to, through practice, improve the knowledge,
skill and confidence of the reader in Java programming. Over 1000 carefully designed exercises along with
their solutions are presented in this book to help achieve this end.
On the back cover of the print version of this book, we presented four important objectives that this book is
designed to help you achieve. We want to help you quickly achieve the following:
(1) Attain a firm understanding of the foundations of this language
(2) Have high retention of the knowledge presented in this book,
thus increasing your (3) skill and (4) confidence in your ability to program in Java at this level and to
pursue higher levels of study of this language.
There are two main means by which this book helps achieve these objectives; first by properly ordering the
chapters and the contents therein and also, by our unique question structure. We explain these below.
The reader is often presented with direct hints for programming questions
This is a very important feature of the exercises in this book. We explain why.
You see, if an exercise is presented on a topic with which a reader is unfamiliar or peripherally
familiar, the reader will search (likely on the internet) for possible solutions. This takes time. This
v
Practice Your Java Level 1
wastes time. In fact, for more complex topics, a reader many end up spending so much time reading
potential solutions, that when he finally finds a solution he has actually forgotten how he got there and
is too fatigued to actually remember the solution! It is better, as is done in this volume, to have “hints”
which specify the exact Java methods that feature in the solution to the problem so that the reader can
spend his time profitably studying the exact methods/language features that pertain to solving the
problem at hand and implementing the solution. This focus also aids retention.
The astute reader will actually observe that while indeed this is called a practice volume, the structure of many
of the solutions is as one actually teaching the Java topics presented.
For the individual without previous experience in Java, this book is intended as a companion text to a
Java programming volume to help the reader broaden and solidify their understanding, retention, skill
and confidence in Java by way of practice exercises.
For the returning Java programmer at this level, working through the exercises in this book may
suffice as a text, given the depth and extent of the exercises and presented solutions.
The programmer who prefers to learn by practice exercises will find this to be an appropriate volume.
The classroom instructor, who will be delighted to find that this book is a robust tool for ensuring that
their students are well versed in and have proper depth in Java programming.
Intended Audience
The primary audience for this volume is the Java beginner up to the early intermediate Java programmer.
Toolset
The coding solutions in this book were implemented in Java 8 using version 4.4 of the Eclipse IDE. There are
no IDE specific exercises in this volume. The reader is encouraged to use any IDE of their choosing.
vi
Structure of Contents
This book is structured in chapters, with each chapter covering a major topic (or part thereof). Overlap
between topics is covered in the appropriate chapter for such.
Chapter Legend/Structure
Exercises are numbered sequentially. The question numbers are uniformly on the left-hand side of the
page. The solution to each exercise appears beside or immediately below the exercise.
An M appearing in the question number column indicates an action which must be performed manually;
for example, an instruction to insert a USB stick/drive into the computer.
An E followed by a number in the question number column indicates that this is an extra unsolved
exercise given to you the reader to solve. Where these appear, they are at the end of the chapter.
The user will also need access to the freely available official Java online documentation supplied by Oracle.
The code for this book is downloadable from the publishers’ website.
vii
Acknowledgements
And to all the people whose shared knowledge has contributed to this.
ix
Table of Contents
Chapter 1. For Starters .................................................................................................................................... 1
Chapter 2. Console Handling I: Basic Output ................................................................................................7
Chapter 3. Number Handling I – Numerical Primitives .............................................................................. 11
Chapter 4. Boolean operations - The boolean Primitive ............................................................................. 41
Chapter 5. Strings: Basic Handling ............................................................................................................. 47
Chapter 6. Conditional Processing .............................................................................................................. 55
Chapter 7. Arrays .......................................................................................................................................... 61
Chapter 8. Iterations/Loops ........................................................................................................................ 69
Chapter 9. Number Handling II – Numeric Wrapper Classes .....................................................................81
Chapter 10. The Boolean Wrapper Class .................................................................................................... 89
Chapter 11. Enumerations I .......................................................................................................................... 91
Chapter 12. Number Handling III – BigInteger & BigDecimal ................................................................... 95
Chapter 13. Number Handling IV – strictfp & StrictMath.................................................................... 109
Chapter 14. Number Handling V – Unsigned Integers ............................................................................... 111
Chapter 15. Date/Time Handling – Foundation ........................................................................................ 117
Chapter 16. Exceptions ............................................................................................................................... 137
Chapter 17. Console Handling II: Console Input........................................................................................ 147
Chapter 18. Console Handling III: Command Line Input .......................................................................... 155
Chapter 19. The char primitive & the Character Wrapper Class ............................................................. 157
Chapter 20. Random Numbers................................................................................................................... 163
Chapter 21. StringBuffer & StringBuilder ................................................................................................... 167
Chapter 22. Classes I .................................................................................................................................. 175
Chapter 23. Object References & Primitive Type Variables: A Deeper Understanding ............................ 201
Chapter 24. Classes II: Nested Classes, Local Classes, Anonymous Classes ............................................. 209
Chapter 25. Collections I: Collections with Generics ................................................................................. 219
Chapter 26. Interfaces ................................................................................................................................ 231
Chapter 27. Collections II: Collections using Interfaces, along with Iterators .......................................... 241
Chapter 28. Properties, Computer Environment & Computer Information ............................................. 247
Chapter 29. File System I: Path, Directory and File Handling using NIO/NIO.2 .................................... 253
Chapter 30. File System II: File Input & Output ........................................................................................ 277
Chapter 31. Enumerations II ..................................................................................................................... 285
Chapter 32. Graphical User Interfaces using Swing .................................................................................. 289
Chapter 33. Applets – a brief look ............................................................................................................. 305
xi
Practice Your Java Level 1
Appendix A. Classes, Objects & Methods: An Introduction ...................................................................... 307
Appendix B. Project .................................................................................................................................... 311
Index ...........................................................................................................................................................313
xii
Chapter 1. For Starters
The intent of this chapter is largely to provide a quick overview of introductory topics with which the reader may
already be fully acquainted; these topics pertain to the basic structure of Java applications as well as a cornucopia of
basic Java programming topics and concepts. Again, as previously stated, the exercises in this chapter are presented as a
quick overview.
Note: The reader who needs an introduction to the concepts of classes, objects and methods should first read Appendix
A.
First, we present a sample program below; we will reference it in some of the exercises in this chapter.
package practiceYourJava;
import java.util.*;
import java.time.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
}
}
1. With respect to the code block shown above, what does the statement package practiceYourJava; mean?
This means that we want the program that we are writing to be placed in a “package” which we named
practiceYourJava (the concept of packages is elucidated upon in the next exercise).
2. With respect to the code block shown above, give a very brief explanation of what the meaning of the
statements
import java.util.*; import java.time.*; import java.io.*; import java.nio.file.attribute.*;
Each of these statements refers to our intent to import a package; by “import” we mean that we are informing
the compiler that we intend to use part of the contents of the stated package(s) in our program. Our final
compiled program will be whatever program we write plus the particular components of the noted packages that
use in our program.
3. What is a “package” in Java?
A “package” is a grouping of Java types (by types here we mean classes of various sorts, including enumeration
classes, exception classes and interfaces; we will look at each of these in later chapters). It is up to the developer
of the package to group whatever types they want into a given package. An example of a package is the
java.nio.* package which contains java classes that pertain to certain aspects of file I/O. We have to import
this package for use in our program in order to use the classes and methods with which we perform file I/O.
So, why do you have to inform the compiler that you want to import particular packages into your program?
The reason is so that the compiler knows where to find the previously built types that you want to use in your
program for the following two reasons: (1) so that it can ensure that you are referring to the types correctly and
(2) so that it can compile those previously existing types along with your program. The package content that you
reference via import statements is in effect a part of your program (note though, when you reference standard
Java libraries in your program their content is not compiled with your program because those packages are
already present in the JVM; at run-time whenever the JVM sees a reference in your code to a component of a
standard Java library it simply links to the version/copy of the library code that it already has).
Now what does the “*” mean in the package name? It indicates to the compiler that we want every top-level type
that appears in the package in question to be made visible for potential use in our program. For example, in the
package java.util there are a number of classes; these include the classes Random, LinkedList, HashMap and
1
ArrayList, to name a few. Using a “*” (i.e. java.util.*) lets the compiler see all of these types for potential
compilation with our application code.
You are also free to specify the individual types that you want to use directly in an import statement; for example
you can write import java.util.HashMap; instead of import java.util.*; if you know that the HashMap class
is the only item in the package java.util that you want to use in your program. Such precise selection only
makes compilation faster, it doesn’t have any impact on the size of your program.
You too can create your own packages. In the code example presented above, we are putting the contents of the
program in this example into a package named practiceYourJava. In fact, your IDE might prompt you to
specify a package name when you try to create a class. If you do not define a package, the IDE might use the
“default package”, which doesn’t have a name and thus its contents cannot be referenced from other packages.
We also see in our sample code the importation of the packages java.nio.file.attribute.* and
java.nio.file.*, where on observation of the names we see that the first package name appears to be a subset
of the first. This is not so; the concept of nested or sub-packages does not exist in Java. They are different
packages whose names have been made similar just to show the relationship between their contents.
Default imports
Java by default automatically imports the following:
(1) the package java.lang.* which contains a lot of useful classes such as the class Math
(2) the other types of the package that your program is code is a part of
In summary: a package is a grouping of types. You must state in your program that you want to import any
package whose contents you use in your application.
Note: A good IDE will inform you as to the need to import a given built-in package once it sees you referring in
your code to any of the contents of the package in question.
4. In the code block presented at the beginning of the chapter, we see the following statement:
public class PracticeYourJava {
What does it mean?
It means that we are creating our own class that we have named PracticeYourJava.
All code in Java applications is always in a class.
The keyword public means that this class is accessible by any other class.
In this book, we will use a good number of built-in classes and also eventually create our own.
5. True/False: In Java, should each type (class, interface, enumeration, etc) that you create be in its own file?
True. The file name should also be the name of the contained type, with the extension .java applied to it. For
example, the class PracticeYourJava should be in a file named PracticeYourJava.java.
6. What is the concept of a “classfile” in Java?
In Java, a classfile is the result of the Java compilation process applied to a .java file. The content of this file is
the compiled bytecode that the Java Virtual Machine (JVM) runs. The output file has the same name as the input
file, however now with an extension of .class instead of the extension .java.
This bytecode is unique to the language Java itself. You can think about it as “Java machine code”.
7. What is the Java Virtual Machine (JVM) ?
The Java Virtual Machine (JVM) is the software in which your Java application runs, as Java programs do not run
directly on the processor like say a program written in C will. The JVM interprets your classfiles (which contain
Java bytecode) and translates their contents to instructions for the particular environment (Windows, UNIX,
Linux, etc) that the JVM is running on.
The JVM itself runs directly on the processor. The existence of the JVM concept is what facilitates Java’s “write
once run anywhere” mantra, as the bytecode in the classfile can be understood as Java’s “machine code” which
all JVMs, irrespective of the operating system or microprocessor that they are running on, understand and
translate for their own particular environment.
8. What is the name of the method for which the compiler looks in a classfile to invoke/execute when you direct
that your program be run?
The method main.
Every class that you want to run directly must always have a method named main (method names are case-
2
sensitive). Classes which do not have a method main defined in them cannot be run directly; they can only
be used by other classes as components.
9. What are the implications if your .java file does not contain a method main?
Hint: See preceding exercise
By not putting a method main into the .java file in question, we are saying that we do not want its resulting
classfile to be directly runnable. This is very common, as most .java files simply contain type definitions that
other programs use as components.
10. Write out the different possible method declarations that a given method main that we want to be
callable/invokable directly by the JVM can have.
The only possible method declaration that fits the noted criteria for method main is as follows:
1. public static void main(String[] args)
The access modifier public gives the method the visibility for it to be seen and thus be invokable by the JVM. The
method main cannot return a value to the operating system directly (there are other methods such as
System.exit with which it can if it wants to) and therefore it is assigned a return type of void. The method main
must always be ready to receive an array of type String as can be seen in the input type. Also, main always has
the modifier static applied to it (We discuss this modifier in Chapter 22 entitled Classes I).
11. Apart from the method type modifier static, what other method type modifier can be used for the method
main?
No other. The method main is always a static method.
Method modifiers (such as static) are covered in Chapter 22, entitled Classes I.
12. In the code snippet below, we have the keyword return. What does this keyword do?
public static void main(String[] args){
return;
}
The keyword return, when executed, causes the immediate termination of the method in which it is
invoked/called and returns control to the calling method. In the case of the method main which is called by the
operating system, a return statement in main exits the program and returns control to the operating system.
In summary, we can say that return means “exit the method that you are running now and return control back
to whoever called this method”.
13. Contrast the use of the keyword return in this program with its use in the preceding exercise.
public int doSomething(){
return(5);
}
The return statements in this and the prior exercise have the same basic effect in that they return control to the
method that invoked the method that invoked the return statement, however, in this exercise, the return also
“returns” a desired value to its calling method (in this example it is returning the value 5). A very important point
to note is that the ability of the statement return to return anything is linked to the return type specified in the
method definition in which the return statement appears. This particular example says that we are returning a
value of type int and that declaration makes it legal for us to return the int value 5.
14. Explain why the following code is invalid:
public String void main(String[] args){
return("finished");
}
It is invalid because the method main can cannotreturn anything directly; its return type should always be void.
Comments
15. What does the string sequence // mean when it appears on a line in a program?
This double forward slash indicates that whatever text comes after it on the same line is a comment, therefore
the compiler should ignore it.
16. What is the output of the following code fragment?
/*
3
System.out.println("Hello");
System.out.println();
*/
4
For example, for a public method named addIntegers which adds two integers passed to it and returns a type
of long, the method signature is:
addIntegers(int, int);
21. What is meant by the term “method declaration” ?
Method declaration means the following: the method name, its access scope (whether public, private, etc.) the
input types and parameter names in the order in which they are sent to the method and the output type of the
method.
For example, for a public method named addIntegers which adds two integers x and y passed to it and returns
a type of long, the method declaration is:
public long addIntegers(int x, int y);
22. What kind of types can be returned by a method using a return statement?
Any type can be returned by a method, whether a user defined type or a built-in type (the method main is a
special case method which cannot use return to return anything).
23. What is meant by the term method overloading ?
This means that for a given method name, there can be different versions of it with different input types and it is
up to the Java compiler to call the correct one (the compiler determines which one to invoke by looking at the
types of the parameters that you pass to it).
For example, if I have the following methods which have the same name but different input parameters:
addIntegers(int, int);
addIntegers(int, int, int);
then if another method invokes addIntegers passing three integer values to it, the compiler knows that I mean
to call the second version of addIntegers indicated above; if I invoke addIntegers passing only two integers to
it, the compiler knows to invoke the first version of addIntegers shown above.
Note however, that a method cannot be overloaded only with respect to the return type, for example the
following pair cannot jointly appear in the same class:
long addIntegers(int, int);
int addIntegers(int, int);
The compiler would not know which of the two methods to call since both have the same input parameters.
You will come across a number of overloaded methods in the built-in Java classes.
24. In a class named PracticeYourJava, create a static method named greet which does not return anything and
does not take any parameters. All it should do is print out the statement “Hello, how are you?” and then return to
its caller. Call this method from the method main.
public class PracticeYourJava{
static void greet(){
System.out.println("Hello, how are you?");
}
public static void main(String[] args) {
greet(); //calling the method hello
}
}
5
Variable number of Arguments (varargs)
Note: While this topic is more advanced than a first chapter topic, it is placed here for consistency. The reader is free
to peruse this topic lightly and then come back to it when a need for the feature arises in later chapters.
26. What is the concept of a variable number of arguments (varargs)?
This is a mechanism by which we can pass a variable number of arguments of a given type to a method designed
to receive a variable number of arguments. For example, we can have a method which we use to calculate and
return the sum of a variable number of integers passed to it; i.e. any method calling such a method can put any
number of integers in the parameter list that they send to this method. The called method would simply note the
number of items passed to it and add them up using a loop.
The variable that receives a variable number of arguments must be the last parameter in the method declaration.
Also, there can only be one variable that can receive a variable number of arguments in a method declaration and
it must be the last variable in the method declaration.
It should be noted that for general intents and purposes the variable that receives a variable number of
arguments has the behavior of an array.
27. Write a static method, that can add public class PracticeYourJava {
any number of integers passed to it and static long addIntegers(int... intArray) {
returns a long as the result. if (intArray.length == 0) return (0);
Call this method from main, testing it long total = 0;
for (int i = 0; i < intArray.length; i++)
with the following sets of data: total += intArray[i];
1. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 return (total);
2. 55, 76, 88, 13 }
3. 3, 7 public static void main(String[] args) {
4. An integer array long result1 = 0, result2 = 0, result3 = 0, result4 = 0;
containing the values result1 = addIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
result2 = addIntegers(55, 76, 88, 13);
1, 5, 15, 19 result3 = addIntegers(3, 7);
int[] intArray01 = { 1, 5, 15, 19 };
result4 = addIntegers(intArray01);
}
}
Note: Until we get to the chapter on Classes, any method that we create will be a static method just as main is, that is,
methods that are not tied to a particular object but rather to the class (non-static methods will be dealt with later when
we deal directly with classes).
Due to the interrelationship between methods and classes, the concept of methods is further enhanced and refined in
Chapter 22 which covers Classes.
6
Chapter 2. Console Handling I: Basic Output
A significant part of many programs is the ability to present output to the user, via the interface with which the user is
interacting with the program. This can be textual output to the console. In this chapter, exercises are presented with
which the reader can practice and sharpen their skills in basic and formatted console output, using in particular the
methods System.out.printf, System.out.println and System.out.print. Also, the basic use of string, integer and
floating point variables appears in this chapter as the presented exercises pertain to outputting data of such types.
7
“My friend!” followed by whatever variable is substituted for the first %s and then a space (as seen in parameter
1) and then the value of whatever variable is to be substituted for the second %s.
It should be explicitly stated that the order of replacement of formatting strings in parameter 1 is the order in
which parameters 2…n appear, i.e. the first formatting string is replaced by the value of parameter 2, the 2nd
formatting string is replaced by parameter 3 the 3rd formatting string is replaced by parameter 4 and so on.
The resultant output is as noted above.
4. Predict the output of this program. Also explain the code.
public class FormattingExercises{
public static void main(String[] args){
String var01 = "Hello!";
System.out.printf("%s %s", var01, var01);
}
}
Output: Hello! Hello!
Code Explanation: The explanation of this code is essentially the same as that for the preceding exercise; only in
this case we have chosen to have the same variable repeated for each of the two string formatting elements %s
and %s in our 1st parameter.
5. Predict the output of this program. Also explain the code.
public class FormattingExercises{
public static void main(String[] args){
String var01 = "Hello!";
String var02 = "How are you?";
System.out.printf("%s\n%s", var01, var02);
}
}
Output: Hello!
How are you?
Code Explanation: We see that the output is on two lines. This is due to the effect of the formatting parameter \n
which we put between the two formatting placeholders in the first parameter. \n essentially means “put a newline
here”. This is the effect that we have seen in our output.
6. Predict the output of this program. Also explain the code.
public class FormattingExercises{
public static void main(String[] args){
String var01 = "Hello!";
String var02 = "How are you?";
System.out.printf("%s\t%s", var01, var02);
}
}
Output: Hello! How are you?
Code Explanation: We see that the output has a tab between the two strings that have been output. This is due to
the effect of the formatting parameter \t which we put between the two formatting placeholders in the exercise. \t
means “put a tab here”. This is the effect that we have seen in our output.
I have two hardcoded String variables defined as
follows: public class FormattingExercises {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe"; String firstName = "John";
7. String lastName = "Doe";
Write a program which will use a printf statement
System.out.printf("%s %s",firstName, lastName);
to output these two String variables to the console }
on the same line with a single space in-between }
them.
Predict the output of this program. Also explain the Output: 2
8. code. Code Explanation: We are introduced here to a new
public class FormattingExercises{ formatting parameter, %d. The parameter %d is used for
8
public static void main(String[] args){ integer values. In all other aspects, the description of the
int var01=2; functioning of the printf method is the same as in the
System.out.printf("%d", var01); preceding exercises.
}
}
Output: 2.550000
Predict the output of this program. Also explain the Code Explanation: We see here the formatting parameter,
code. %f. The parameter %f is used for floating point values. In
public class FormattingExercises{ all other aspects, the description of the functioning of the
9. public static void main(String[] args){ printf method is the same as in the preceding exercises.
double var01=2.55; Observe that the output is written to 6 decimal places. This
System.out.printf("%f", var01); is the default output format of the %f formatting
}
}
parameter. We see in a later chapter how to modify the
precision of the output.
Predict and explain the output of this program. Output: 2.123457
public class FormattingExercises{ Explanation: While we did indeed enter a number which
public static void main(String[] args){ has 9 decimal places, as previously stated, the printf
10. double var01=2.123456789; method by default only prints values out to 6 decimal
System.out.printf("%f", var01); places, rounding the last digit if necessary. In a later
}
}
chapter, we see how to modify the precision of the output.
Hint: use the \ escape sequence. Note: See the escaping of each double quote using the \ in each instance.
public class FormattingExercises {
Write a program which outputs public static void main(String[] args) {
13. the exact phrase "Hello World\n" System.out.println("Hello World\\n");
inclusive of the "\n". }
}
Outputting from a variable using System.out.println
14. I have two hardcoded String variables defined as public class FormattingExercises {
follows: public static void main(String[] args) {
String firstName = "John"; String firstName = "John";
String lastName = "Doe"; String lastName = "Doe";
Write a program which will use a println System.out.println(firstName + " " + lastName);
statement to output these two String variables to }
the console on the same line with a single space }
9
in-between them.
15. I have two String variables defined as follows: public class FormattingExercises {
String firstName = "John"; public static void main(String[] args) {
String lastName = "Doe";
String firstName = "John";
Concatenate these strings, with a space in- String lastName = "Doe";
between them, putting the resulting String fullName = firstName + " " + lastName;
concatenation into a single String variable System.out.println(fullName);
named fullName and then output the }
concatenated string to the console. }
The reader should study the class DecimalFormat to see how numerical formatting rules can be applied to the
E1
methods System.out.println and System.out.println.
10
Chapter 3. Number Handling I – Numerical
Primitives
This chapter offers extensive coverage of the topic of number handling in Java. Your knowledge of numerical types in
Java and operations thereon is exercised and enhanced by the wide-ranging set of exercises that are presented in this
chapter.
Key topics on which exercises are presented in this chapter include: knowledge of the primitive numerical types,
appropriate selection of numerical types, computation exercises with built-in numerical operators as well as with the
methods of the class Math.
Beyond the topics noted above, exercises on the usage of numerical constants from the numerical wrapper classes,
overflow conditions, the Exact methods, infinity handling, hexadecimal numbers, number base conversion, logical and
bitwise operations, increment, decrement and shorthand numerical operators are also included. A robust set of exercises
on the formatting of numerical output is also presented.
The topic of number handling in Java is extensive and thus is not limited to the topics in this chapter; this chapter is the
first of five chapters in this book on the topic of number handling in Java.
11
of an int variable named firstInteger with the value 5.
10. Write a program, using the built-in constants in the class Integer, which writes out the minimum and maximum
values supported by the int type; also print out the size in bits that an int occupies.
Hint: constants Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.SIZE
public class PracticeYourJava {
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.SIZE);
}
}
Note: As can be observed in this solution, the constants that refer to the primitive int are stored in its related
wrapper class Integer. Recall that in the solution to exercise 3 it was stated that the corresponding wrapper class
for each primitive type contains methods and other data (constants for example) that pertain to it and its
corresponding primitive type.
It should be pointed out that the range of values supported by a primitive and its corresponding class are the
same. However, the size of an int (which is represented by the constant Integer.SIZE) is not the size of an
Integer object, that constant only refers to the size of an int.
The same logic above applies to all of the primitive types and their respective related classes.
byte
11. Describe the byte type. In particular describe the number of bits/bytes required to contain a byte, as well as the
range of values that an byte can represent in Java.
A byte in Java is an integer type which occupies a single byte (8 bits) and thus can represent a range of
28 = 256 numbers; the range of values that it represents is -128 to 127.
12. Write a program which declares and initializes a byte variable named firstByte to the value -115 and then prints
the variable to the console, stating “The value of firstByte is <value>”.
public class PracticeYourJava {
public static void main(String[] args) {
byte firstByte = -115;
System.out.println("The value of firstByte is " + firstByte);
}
}
13. What is the minimum value supported by the byte type? -128
14. What is the maximum value supported by the byte type? 127
15. Write a program, using the appropriate built-in constants in the class Byte, which writes out the minimum and
maximum values supported by the byte type; also print out the size in bits that a byte occupies.
public class PracticeYourJava {
public static void main(String[] args) {
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Byte.SIZE);
}
}
short
16. What is the minimum value supported by the short integer -32,768
(short) type?
17. What is the maximum value supported by the short type? 32,767
18. How many bits/bytes are used to represent a short? 16 bits/2 bytes
19. Write a program which declares and initializes a short variable named firstShort to the value 10,000 and then
prints the variable to the console, stating “The value of firstShort is <value>”.
public class PracticeYourJava {
public static void main(String[] args) {
12
short firstShort = 10000;
System.out.println("The value of firstShort is " + firstShort);
}
}
20. Write a program, using the built-in constants in the class Short, which writes out the minimum and maximum
values supported by the short type; also, print out the size in bits that a short occupies.
public class PracticeYourJava {
public static void main(String[] args) {
System.out.println(Short.MIN_VALUE);
System.out.println(Short.MAX_VALUE);
System.out.println(Short.SIZE);
}
}
long
What is the minimum value supported by the Java long integer -9,223,372,036,854,775,808
21.
(long) type? (This is the value -263).
22. What is the maximum value supported by the Java long type? 9,223,372,036,854,775,807 (This is 263 – 1)
23. How many bits/bytes are used to represent a long? 32 bits/4 bytes
24. Write a program which initializes a long variable named firstLong with the value 7,000,000,000 and then prints
the variable to the console, stating “The value of firstLong is <value>”.
public class PracticeYourJava {
public static void main(String[] args) {
long firstLong = 7000000000L;
System.out.println("The value of firstLong is " + firstLong);
}
}
25. Explain the reason for the postfix L at the end of the numerical value in the preceding exercise.
The reason for the postfix is because by default Java sees integer literals as values of type int; if the integer literal
presented is greater than Integer.MAX_VALUE then Java sees it as an invalid value because in a sense it sees it as an
integer that is out of bounds. However when it sees the postfix, Java evaluates the value as the type that the
postfix implies.
26. What is the difference between the following declarations of the variable firstLong?
long firstLong = 7000000000L;
and
long firstLong = 7000_000_000L;
and
long firstLong = 7_000_000_000L;
and
long firstLong = 7_000_000___000L;
There is actually no difference between any of the declaration styles. Java allows you to put the underscore
character in number literals as adds clarity for human viewers of the numerical value. The number of underscores
does not matter either (see the 4th example). However, the underscore character cannot be put at the beginning
or the end of the number.
27. Write a program, using the built-in constants in the class Long, which writes out the minimum and maximum
values supported by the long type; also print out the size in bits that a long occupies.
13
floating point types (float, double)
28. What is the minimum value supported by the float type? -3.4028235 x 1038
29. What is the maximum value supported by the float type? -3.4028235 x 1038
30. How many bits/bytes are used to represent a float? 32 bits/4 bytes
What is the precision of a float?
6-7 significant digits (that includes the digits both before and behind the decimal point).
You know that integer values are discrete values with a deterministic integer distance of 1 between each point on
the integer number scale. With floating points numbers it is not so; there are an infinite number of floating point
numbers possible, even between two adjacent integers (for example between 0 and 1). Therefore it is impossible
to write down all floating point numbers even within a small range, nor is it possible for a computer to represent
the infinite number of points of even a small range on the floating point number scale. Therefore it has been
31.
decided that the float type will have a given maximum precision that it can represent. Any attempt to use the
float type to represent a number with a precision higher than 6-7 digits will be unsuccesful.
Even within the specified range of 6-7 digits, there are some numbers which cannot be represented exactly due
to the way in which floating point numbers are stored in computers. Any decimal number that requires
maintenance of precision (such as currency calculations) should only use the type BigDecimal.
The reader is urged to investigate appropriate sources which describe how floating point numbers are
represented in computers.
-45
~1.4 x 10
What is the smallest possible positive value that a
32. Think of the number as the smallest step away from 0 that the
float can represent?
Java float type can make.
float really refers to what is called a “single precision floating
point number”, which is a floating point number format that
33. Why is a float also described as a single?
is designed to occupy only 4 bytes. This nomenclature is an
IEEE standard.
34. Write a program, using the built-in constants in the class Float, which writes out the minimum and maximum
values supported by the float type. Also print out the size in bits that a float occupies.
public class PracticeYourJava {
public static void main(String[] args) {
System.out.println("Mininum value = %f\n" + (-1 * Float.MAX_VALUE));
//there is no constant for minimum value
System.out.println("Maximum value = " + Float.MAX_VALUE);
System.out.println("Bits occupied = " + Float.SIZE);
}
}
35. Write a program which prints out the smallest positive float that Java supports.
public class PracticeYourJava {
public static void main(String[] args) {
System.out.printf("Smallest positive float = %f", Float.MIN_VALUE);
}
}
36. Why does java require that there a suffix/postfix F applied to the value assigned to a variable of type float?
The reason is because Java presumes that any floating point literal entered is of type double (double means “double
precision floating point number”, a type which we will see shortly) unless the number is explicitly indicated to be a single
precision number as indicated by the postfix F.
37. Write a program which initializes a single precision floating point variable named firstFloat with the value
7.919876542 and prints its value out to the console using System.out.println.
Note and explain the difference between the initialized value and the value that is printed out.
public class PracticeYourJava {
public static void main(String[] args) {
float firstFloat = 7.919876542F; // Note the F at the end
System.out.println(firstFloat);
}
14
}
Observation/Explanation: The output is 7.9198766 not the 10 digit number 7.919876542 that was input! The
reason is that the float type officially only has a precision of 6-7 significant digits and so we should not have
attempted to assign it a value of higher precision. Yes indeed there are 8 significant digits in the output, however
the last digit was the result of rounding. There are times when the value of the rounded up digit is acceptable and
times when it is not.
Also note that the value that was input was rounded (not truncated). There are different rounding modes
available in Java; exercises on these are presented in Chapter 12, entitled Number Handling III.
38. Write a program which will assign the value 1768000111.77 to a variable of type float. Print the value out using
the %f specifier of the printf method. Note the output and present your observations on it.
public class PracticeYourJava {
public static void main(String[] args) {
float f1 = 1768000111.77F; // Note the F at the end
System.out.printf("f1 = %f\n", f1);
}
}
Output: f1 = 1768000128.000000
Observations: The output is quite different from the input! In fact, even if the input variable was manually
rounded to the nearest decimal position, the value obtained would be be closer to the original number than what
the computer has determined the float to be!
As in the preceding exercise, the error was that the number entered was beyond the stated precision of a float
(which is 6-7 significant digits). Java did indeed retain the integrity of at least the first 6-7 digits.
Conclusion(s): Do not attempt to apply to a floating point variable a value beyond its stated precision.
double
39. What is the minimum value supported by the type
-1.7976931348623157 x 10308
double?
40. What is the maximum value supported by the type
1.7976931348623157 x 10308
double?
41. How many bits/bytes are used to represent a double? 64 bits/8 bytes
What is the smallest possible positive value that a
42. 4.9 x 10-324
double can represent?
15-17 significant digits.
43. What is the precision of a double?
(contrast this with the precision of a float/single).
Write a line of code that shows the declaration and
initialization of a double precision floating point
44. double firstDouble = 5.4857990943E-4;
variable named firstDouble with the value
5.4857990943 x 10-4.
45. Write a program, using the built-in constants in the class Double, which writes out the minimum and maximum
values supported by the double type. Also print out the size in bits that a double occupies.
public class PracticeYourJava {
public static void main(String[] args) {
System.out.println("Mininum value = " + (-1 * Double.MAX_VALUE));
//there is no direct constant for this
System.out.println("Maximum value = " + Double.MAX_VALUE);
System.out.println("Bits occupied = " + Double.SIZE);
}
}
Assessing the Precision of type double
46. Write a program which will assign the 12 digit number 1768000111.77 to a variable of type double and print it
out using the %f specifier of the printf method and also using the method println. Note the output and present
your observations on it.
(This input value is the same attempted with a float in question 38).
public class PracticeYourJava {
15
public static void main(String[] args) {
double d1 = 1768000111.77;
System.out.printf("d1 = %f\n", d1);
System.out.println(d1);
}
}
Output: d1 = 1768000111.770000
d1 = 1.76800011177E9
Observations: The output matches the input, for the precision of the input value is 12 significant digits, which is
within the supported range of a double. We observe that println output the number in exponential format.
47. Write a program which will assign the 16 digit value 17680001118938.77 to a variable of type double and print it
out using the %f specifier of the printf method. Note the output and present your observations on it.
Solution: modify the code in the preceding exercise to use the number in this exercise.
Output: d1 = 17680001118938.770000
Observations: The output matches the input exactly, for the precision of the input value has 15-17 significant
digits which is within the supported range of a double.
48. Write a program which will assign the 17 precision place value 176800011189387.35 to a variable of type double
and print it out using the %f specifier of the printf method. Note the output and present your observations on
it.
Solution: modify the code in the preceding exercise to use the number in this exercise.
Output: d1 = 176800011189387.340000
Observations: As can be seen, the last digit of the entered number is distorted. This should be expected as the
double supports only at best a 15-17 precision place number.
Summary: You should carefully consider whether or not you should use the type double for values with
precision greater than 15 places.
49. Write a program which will assign the 18 precision place value 123456789012345678.0 to a variable of type
double and print it out using the %f specifier of the printf method. Note the output and present your
observations on it.
Solution: modify the code in the preceding exercise to use the number in this exercise.
Output: d1 = 123456789012345680.000000
Observations: As can be seen, digit 18 is rounded up and that affects the value of digit 17. This should be
expected as the type double supports at best only a 15-17 precision place number.
50. IMPORTANT
Print out the value Float.MIN_VALUE, using printf and then println. Comment on your observations.
public class PracticeYourJava {
public static void main(String[] args) {
double d1 = Double.MIN_VALUE;
System.out.printf("d1 = %f\n", d1);
System.out.println("d1 = " + d1);
}
}
Output
d1 = 0.000000
d1 = 4.9E-324
Clearly the 1st output, using printf is wrong! This occurrence is because of the default way in which printf
formats floating point numbers; it will by default print at most 6 digits after the decimal point and will not by
default attempt to print the value out in exponential format as println does.
Later in this chapter, exercises on formatting of numerical output are presented.
For further experimentation along this line, print out the double value -1.0011596521859 using printf and
println.
51. IMPORTANT
Print out the value to at least 15 places of the result of the computation 1/10. Comment on the output.
public class PracticeYourJava {
16
public static void main(String[] args) {
double x = 1.0f/10.0f;
System.out.printf("%.15f\n", x);
}
}
Output
z = 0.100000001490116
The value is not exactly 0.1! The computation 1/10 is supposed to yield a very specific rational result. This error
occurs in some floating point calculations because of the way that computers handle/store floating point
numbers. Clearly, this is not a good thing when we need exact precision; imagine scenarios where we have a
financial application which computes values ranging into the billions of currency units; this error will definitely
show up in such sensitive computations. Another example where precision is required is in scientific calculations;
this imprecision in handling would also show up then. We see in the next section and in the chapter Number
Handling III how to achieve the desired precision for floating point numbers by using the type BigDecimal.
Numerical suffixes
Decide which number type best represents the kind of number indicated in the question.
The type BigDecimal. The reasons is because monetary
Which type would be best to represent the salary of values are always best represented by variables of type
54.
an individual? BigDecimal as BigDecimal represents decimal numbers
accurately.
55. Which type would be best to represent the aggregate The type BigDecimal would be best because we are
salary over 20 years of the salaries of a company representing a monetary value which requires precise
which has 50,000 employees? representation.
Which type is sufficient to handle the age of a The type byte is sufficient and safe (unless you are
56.
person? interested in fractions of years as well). The type byte has
17
a maximum of 127 which is about as high as people live
these days.
The type long is an appropriate type in this case. The
reasons for this are:
The population of the world is currently ~7.2 billion
57. 1. Human beings are integral units.
people. Which type should be used to represent this?
2. This is the closest type that can contain at least that
number of people.
A byte will do. The reasons for this are:
To count the number of siblings you have, which
58. 1. Human beings are integral units.
type would be the most likely candidate?
2. Chances are no one has up to 127 siblings!
The type BigDecimal because although this number has
Which type is best to represent the Planck constant only 11 significant digits which can be represented in a
59.
which has a value of 6.626 068 9633 × 10–34 ? double we would be safe with the precision of the
BigDecimal type when using this constant in calculations.
60. The speed of light is precisely defined as An int, because this number is an integer of value
299 792 458 m/s. Which type would be sufficient to approximately ~300 million which is less than the ~2.1
represent it? billion that an int supports.
The type BigDecimal because although this number has
The Rydberg constant has a value of
7 only 14 significant digits, we would be safe with the
61. 1.0973731568539 x 10 . Propose which type is best
precision of the BigDecimal type when using this
to represent it.
constant.
The electron magnetic moment to Bohr magneton
62. ratio has a value of -1.001 159 652 1859. Which type The type BigDecimal.
best represents it?
The electron g factor is -2.002 319 304 3718. Which
63. The type BigDecimal.
type best represents it?
Electron g factor uncertainty is 0.000 000 000 0075.
64. The type BigDecimal.
Which type best represents it?
The value of Coulomb’s constant is
A BigDecimal. Not only for its accuracy, but also because
65. 8.9875517873681764×109. Which type best
this number has 17 significant digits.
represents it?
A general note on the choice of BigDecimal for exercises 59 to 64: Really, a double may suffice in these cases for
general computation scenarios (perhaps, for example, in writing examinations).
Casting
66. Explain the concept of casting.
Casting is a language feature wherewith you can force the compiler to take a copy of the contents of a variable
and convert the copy to the format of another type.
For example, I can do the following:
int a = 50;
short b = (short)a;
The second line of which means, give me a copy of a that has been converted into the internal format and space of a short
and put it into the short variable b (note that a itself is not changed).
We elucidate further using short and int; a short is represented in 2 bytes and an int in 4 bytes. It is reasonable
to say that any int value which is less than or equal to the width of a short (i.e. an int whose actual value is
between -32,768 and 32,767) can legally fit into a short. However, we have to explicitly inform the compiler that
we do indeed want to copy the contents of the int in question into a short.
Note that you can actually still cast the value of a higher width type whose contents are greater than the width of
a lower width type into the lower width type; for example you can cast an int whose value is greater than 32,767
into a short; while indeed the value in question cannot actually fit into the space of a short, the compiler will still
do its best to cast the value, however the value will be distorted, i.e. wrong, since you cannot fit something of a
higher actual width into a smaller space properly.
18
Casting also pertains to objects; you can cast an object of a given class into a variable of any of its ancestor
classes. This ability is facilitated by the concept of polymorphism. We see examples of this in the chapter on
classes.
The concepts of boxing and unboxing can be seen as a special type of casting. We address the topic of boxing and
unboxing in a later chapter.
67. Why would you want to cast variables?
You would want to cast variables in scenarios where you want the contents of a casted variable to be put into a
variable of a different type.
For example, if I have an int a=10 and given how small its value is, I want to put it into a variable of type byte
(which supports values from 0 to 255), I would cast it as follows:
byte c=(byte)a;
This line is saying take a copy of the contents of int a and stuff them into the format of a byte as best as you can.
If for example I have to add an int and a long and want the resultant value to be put into an int, due to the fact
that the target variable has a smaller width than at least one of the input variables, the input variables that are
larger than the output variable have to be cast to the width of the target variable. See the following example:
long a=10; int b=50;
int result = (int)a + b;
Some casts are more dramatic. For example, the char type (which represents characters) can be cast into an
integer representation. For example:
char letter = 'A';
int integerEquivalent = (int)letter;
With this cast, you are now able to facilitate the sorting of characters because they have an explicit numerical
representation, which lends itself to ordering by magnitude.
You can also cast objects. For example, if I have the following object of a class named Road:
Road x = new Road();
I can, if I desire, cast the object x to an object of the ultimate ancestor class Object as follows:
Object y = (Object)x;
(The casting of an object to any of its ancestor classes is made feasible by the concept of polymorphism)
I can cast y back to an object of class Road as follows:
Road z = (Road)y;
As previously stated, for numerical values you will lose data in casting if you try to cast a variable which contains
a higher value than what the type of the target variable can support. For example if we have the following
scenario:
int var01 = 75000;
short var02 = (short)var01;
Because the value of the variable var01 exceeds the maximum for a short, var02 definitely will not contain the
value 75,000, but rather a distorted value.
68. What is implicit casting?
Implicit casting is a scenario where, given the operation at hand, the compiler sees it fit to silently cast the
contents of a variable of a given type to a more appropriate type that it is safe to cast the given type to.
For example, if I wanted to add an int to a long and put the result into a long, the code would look like the
following:
long a=10; int b = 50;
long result = a + b;
In order to perform this computation, the compiler has to make the contents of both a and b the same type; in
this case the compiler will simply silently cast b to the wider type long (note that it doesn’t change b itself it just
19
takes a casted value of b) and adds it to a to obtain result.
There will not be any ill-effects since an int is of smaller range than the target output variable (a long in this
case).
Now, if I had the following scenario where result is an int:
long a=10; int b=50;
int result = a + b;
The compiler will not implicitly cast the variable a to an int. Why not? Because casting a given type (long in this
case) to a smaller type can potentially result in the loss of data. Therefore, in this case, the compiler will insist that
you do the casting of the variable a yourself if that is what you really want, requiring you to explicitly write the
following:
int result = (int)a + b;
69. Explain the result of compiling and running the program below.
public class PracticeYourJava {
public static void main(String[] args) {
short a = 5;
short b = 2;
short result;
result = a + b;
System.out.println("result = " + result);
}
}
It will not compile. The reason for the non-compilation is that in Java, computations done with respect to short
or int values result in an int. Therefore Java holds the value of a + b as an int, even though both input values
are of type short. Us trying to put the resulting int value into a short is illegal unless we explicitly cast the value.
To get this to compile, you have to do either of the following:
(1) result should be declared as an int
or
(2) result = (short)(a+b); that is, you have to cast the result of the computation to the desired type (in
this case, a short).
70. Write a program to add the following two short values (i=250; j=3). Put the result into a short and print the
result out to the console.
public class PracticeYourJava {
public static void main(String[] args) {
short i = 250;
short j = 3;
short result;
result = (short)(i + j);
System.out.println("result = " + result);
}
}
71. Write a program which multiplies the following two short values (i=250; j=300), puts the result into a short
and prints the result out to the console.
public class PracticeYourJava {
public static void main(String[] args) {
short i = 250;
short j = 300;
short result;
result =(short)(i * j);
System.out.println("result = " + result);
}
}
Note: This will print out a value of 550 instead of 75000! The reason is because the resultant value is greater than
Short.Max (which = 32767) and thus the result of casting a 4 byte integer value of 75000 to a short (which has a
20
width of 2 bytes) yields 550 which is not want we want at all. We have two options to avoid such behavior. These
are:
1. Always use the appropriately sized type for your calculations.
or
2. Use the Exact methods of class Math to ensure that an exception is triggered when a computation goes
out of bounds. We will look at the Exact methods later in this chapter.
72. Write a program to multiply the following two short variables (i=250; j=300). Put the result into an int and
print the result out to the console.
public class PracticeYourJava {
public static void main(String[] args) {
short i = 250;
short j = 300;
int result;
result = i * j;
System.out.println("result = " + result);
}
}
constants
73. What is a constant (final) in Java?
A constant is a variable with a hardcoded and immutable value. For example, in the class Math, there are the
constants PI and E.
You define constants using the keyword final (indicating that this is the “final value” of this variable). A variable
labeled as being final can only be assigned to once! That assignment might be hardcoded in the code itself, or
for constants in individual objects or in methods it can be at any time during the running of the code, only that it
can only be done only once.
Again, a constant can be declared at the class level, or at the instance level, or inside a method. The declaration
for a class level constant has the following structure:
class <class name>
{
<access level> static final <field type> <field name> = <value>;
}
In the class Math for example, the constants PI and E are class level constants and are declared as:
class Math
{
public static final double PI = 3.141592653589793; // See the use of the keyword final
public static final double E = 2.718281828459045;
}
(The keyword static is what makes these constants class constants, thus making them directly accessible by any
object that can access the fields of this class; for example you can simply access the field PI in any of your code
directly as Math.PI. We will look closer at the keyword static the chapter entitled Classes I).
The declaration for an instance/object level constant is as follows:
class <class name>
{
<access level> final <field type> <field name> = <value>; // No keyword static
}
Method constants are declared within methods in the following manner (using main as an example):
public static void main(String[] args){
final double ten = 10.0;
final int DaysInWeek = 7;
final int MonthsInYear = 12;
final String MetricOrImperial; // We can assign to this later in our code, perhaps it is
// a field we get from the user.
}
21
Accessing constants
Class constants are accessed using the class name as the prefix to the constant name. Therefore, for example, you
access the constant PI of the class Math as Math.PI in your code.
Instance constants are accessed using the name of the object as the prefix to the constant name.
Method constants are accessed using only their name (since a method constant is only accessed from within the
method in which it is declared).
74. What
A is a blank final?
A blank final is a final variable that is not assigned at compile time.
Write a program to print out the public class PracticeYourJava {
value of the built-in mathematical public static void main(String[] args) {
75. System.out.println(Math.PI);
constant π. }
Hint: Math.PI }
public class PracticeYourJava {
Write a program to print out the public static void main(String[] args) {
76. value of the built-in mathematical System.out.println(Math.E);
constant e. }
}
77. Write a line of code to show the implementation of the Rydberg constant as a public class constant.
public static final double rydberg = 1.0973731568539e7;
78. Write a line of code to show the implementation of the Rydberg constant as a public instance constant.
public final double rydberg = 1.0973731568539e7;
Built-in mathematical operators and methods
In this section, exercises on the usage in Java of standard mathematical operators, constants and methods of the class
Math are presented.
public class PracticeYourJava {
Write a program which adds the public static void main(String[] args) {
following two int variables; i=5; int i = 5; int j = 9;
79. int result = i + j;
j=9; and prints the result out to
System.out.println("The sum is: " + result);
the console. }
}
public class PracticeYourJava {
Given two int variables i=5; j=9; public static void main(String[] args) {
write a program which subtracts int i = 5; int j = 9;
80. the latter from the former and int result = i - j;
prints the result out to the System.out.println("The sum is: " + result);
console. }
}
Write a program to calculate and public class PracticeYourJava {
public static void main(String[] args) {
print out the remainder of 55 int rem = 55 % 22;
81. divided by 22. System.out.println("The remainder is: " + rem);
}
Hint: Use the % operator }
82. Write a program to calculate and print out the square root of 81.39.
Hint: Math.sqrt
public class PracticeYourJava {
public static void main(String[] args) {
float x = 81.39f;
double result;
result = Math.sqrt(x);
System.out.println("The square root of " + x + " is: " + result);
}
}
83. Print out the value of 79.34 raised to the power of 12.
22
Hint: Math.pow
public class PracticeYourJava {
public static void main(String[] args) {
float x = 79.34f;
double result;
result = Math.pow(x, 12);
System.out.println(x + " to the power of " + 12 + " is: " + result);
}
}
84. Print out the cube root of 89.
Hint: Math.cbrt
public class PracticeYourJava {
public static void main(String[] args) {
float x = 89.0f;
double result;
result = Math.cbrt(89);
System.out.println("The cube root of " + x + " is: " + result);
}
}
85. Print out the fifth root of 89.
public class PracticeYourJava {
public static void main(String[] args) {
float x = 89.0f;
double result;
result = Math.pow(x,(1.0/5.0));
System.out.println("The 5th root of " + x + " is: " + result);
}
}
86. Print out the 7th root of 121.
public class PracticeYourJava {
public static void main(String[] args) {
float x = 121.0f;
double result;
result = Math.pow(x,(1.0/7.0));
System.out.println("The 7th root of " + x + " is: " + result);
}
}
87. Write a program to calculate and print out the cosine of 180o.
Hint: Methods Math.Cos and Math.toRadians
public class PracticeYourJava {
public static void main(String[] args) {
double degrees = 180;
double radians = Math.toRadians(degrees);
double cosine = Math.cos(radians);
System.out.printf("The cosine of %f degrees = %f\n",degrees,cosine);
}
}
88. Write a program to calculate and print out the tangent of 30o.
public class PracticeYourJava {
public static void main(String[] args) {
double degrees = 180;
double radians = Math.toRadians(degrees);
double tangent = Math.tangent(radians);
System.out.printf("The tangent of %f degrees = %f\n",degrees,tangent);
}
}
23
89. Write a program to calculate and print out the tangent of 60o.
public class PracticeYourJava {
public static void main(String[] args) {
double degrees = 60;
double radians = Math.toRadians(degrees);
double tangent = Math.tangent(radians);
System.out.printf("The tangent of %f degrees = %f\n",degrees,tangent);
}
}
90. Write a program to calculate and print out the sine of 75o.
Hint: Math.toRadians, Math.sin
public class PracticeYourJava {
public static void main(String[] args) {
double degrees = 75;
double radians = Math.toRadians(degrees);
double sine = Math.sin(radians);
System.out.printf("The sine of %f degrees = %f\n",degrees,sine);
}
}
91. The sine of a given angle is .8660254037. Write a program to calculate and print out in degrees and in radians the
angle that this value corresponds to.
Hint: Math.asin, Math.toDegrees
public class PracticeYourJava {
public static void main(String[] args) {
double sine = .8660254037;
double degrees, radians;
radians = Math.asin(sine);
degrees = Math.toDegrees(radians);
System.out.printf("%f is the sine of %f degrees (or %f radians).\n", sine, degrees, radians);
}
}
92. The cosine of a given angle is .8660254037. Write a program to calculate and print out in degrees and in radians
the angle that this value corresponds to.
public class PracticeYourJava {
public static void main(String[] args) {
double cosine = .8660254037;
double degrees, radians;
radians = Math.acos(cosine);
degrees = Math.toDegrees(radians);
System.out.printf("%f is the cosine of %f degrees (or %f radians).\n", cosine, degrees,
radians);
}
}
93. The tangent of a given angle is .8660254037. Write a program to calculate and print out in degrees and in radians
the angle that this value corresponds to.
public class PracticeYourJava {
public static void main(String[] args) {
double tangent = .8660254037;
double degrees, radians;
radians = Math.atan(tangent);
degrees = Math.toDegrees(radians);
System.out.printf("%f is the tangent of %f degrees (or %f radians).\n", tangent, degrees,
radians);
}
}
94. Write a program to print out the area of a circle of radius 7.
public class PracticeYourJava {
24
public static void main(String[] args) {
double radius = 7.0;
double area;
area = Math.PI * Math.pow(7,2);
System.out.printf("The area of a circle of radius %f = %f.\n", radius, area);
}
}
95. Write a program to print out the absolute value of the following values: -743.8, 525.3 and 1501.
Hint: Math.abs
public class PracticeYourJava {
public static void main(String[] args) {
double value01 = -743.8; double abs01;
double value02 = 525.3; double abs02;
int value03 = 1501; int abs03;
abs01 = Math.abs(value01);
abs02 = Math.abs(value02);
abs03 = Math.abs(value03);
System.out.printf("The absolute value of %f is %f\n", value01, abs01);
System.out.printf("The absolute value of %f is %f\n", value02, abs02);
System.out.printf("The absolute value of %d is %d\n", value03, abs03);
}
}
public class PracticeYourJava {
public static void main(String[] args) {
Calculate the logarithm to base 10 double d01 = 7;
of 7 and the logarithm to base 10 double d02 = 22;
of 22. Add the resulting values, double logOfd01 = Math.log10(d01);
96. putting the sum thereof into a double logOfd02 = Math.log10(d02);
variable x. Then compute and
double x = logOfd01 + logOfd02;
print out the value of 10x. double result = Math.pow(10, x);
Hint: Math.Log10, Math.pow System.out.printf("result = %f\n", result);
}
}
public class PracticeYourJava {
public static void main(String[] args) {
Calculate the logarithm to base e double d01 = 7;
of 7 and the logarithm to base e of double d02 = 22;
22. Add the resulting values, double logOfd01 = Math.log(d01);
97. putting the sum thereof into a double logOfd02 = Math.log(d02);
variable x. Then compute and
double x = logOfd01 + logOfd02;
print out the value of ex. double result = Math.exp(x);
Hint: Math.Log, Math.exp System.out.printf("result = %f\n", result);
}
}
Pythagoras’ theorem states that for
a given right-angled triangle with
sides a, b and c where c is the public class PracticeYourJava {
public static void main(String[] args) {
hypotenuse, if you have the values float a = 3;
a and b, the value for c can be float b = 4;
98. determined as follows: double c; // this is for the hypotenuse
c = √(a2 + b2). c = Math.hypot(a, b);
So given a triangle where a=4 and System.out.printf("hypotenuse = %f\n", c);
b=3, write a program to calculate c }
and print it out. }
Hint: Math.hypot
25
Given two numbers, 55 and 70, public class PracticeYourJava {
write a program to determine and public static void main(String[] args) {
99. print out which is the larger of the int bigger = Math.max(55, 70);
two. System.out.printf("The bigger number is %f\n", bigger);
}
Hint: Math.max }
public class PracticeYourJava {
Given two numbers, 320 public static void main(String[] args) {
and -2.95 of type double, write a double smaller = Math.min(320, -2.95);
program to determine and print System.out.printf("The smaller number is %f\n", smaller);
100. out which is the smaller of the two }
numbers. }
Hint: Math.min Note: to do comparisons using Math.min or Math.max the numbers being
compared must be of the same type.
public class PracticeYourJava {
Round the value 12777.899 to the public static void main(String[] args) {
nearest whole number double and double x = 12777.899;
101. print the result out. double rounded = Math.rint(x);
System.out.printf("The rounded value is %f\n", rounded);
Hint: Math.rint }
}
public class PracticeYourJava {
Round the value 12777.899 to the public static void main(String[] args) {
nearest long and print the result double x = 12777.899;
102. out. long rounded = Math.round(x);
System.out.printf("The rounded value is %d\n", rounded);
Hint: Math.round }
}
public class PracticeYourJava {
public static void main(String[] args) {
double d01 = 5.799;
Write a program to print out the double d02 = 583.6;
ceiling of 5.799 and 583.6 double ceil01 = Math.ceil(d01);
103. respectively.
double ceil02 = Math.ceil(d02);
Hint: Math.ceil System.out.printf("The ceiling of %f is %f\n",d01,ceil01);
System.out.printf("The ceiling of %f is %f\n",d02,ceil02);
}
}
public class PracticeYourJava {
public static void main(String[] args) {
double d01 = 5.799;
double d02 = 583.6;
Write a program to print out the
double ceil01 = Math.floor(d01);
104. floor of 5.799 and 583.6 double ceil02 = Math.floor(d02);
respectively.
System.out.printf("The floor of %f is %f\n",d01,ceil01);
System.out.printf("The floor of %f is %f\n",d02,ceil02);
}
}
105. Give the signum of each of the public class PracticeYourJava {
following double values: public static void main(String[] args) {
double num01=-55.6, num02=0.0004, num03=0.0;
1. -55.6 int num04=79;
2. 0.0004
3. 0 double signum01 = Math.signum(num01);
double signum02 = Math.signum(num02);
4. 79 double signum03 = Math.signum(num03);
double signum04 = Math.signum(num04);
26
System.out.printf("signum of %f is %f\n", num01, signum01);
System.out.printf("signum of %f is %f\n", num02, signum02);
System.out.printf("signum of %f is %f\n", num03, signum03);
System.out.printf("signum of %d is %f\n", num04, signum04);
}
}
106. I have two double variables x and public class PracticeYourJava {
y. Write a program that returns a public static void main(String[] args) {
number with the magnitude of x double set1_num1=-89.5, set1_num2=200;
but the sign of y. double set2_num1=400, set2_num2=-300;
Test the program with the double result1 = Math.copySign(set1_num1, set1_num2);
following pairs (x, y) of values: double result2 = Math.copySign(set2_num1, set2_num2);
-89.5, 200 System.out.printf("First pair result = %f \n", result1);
400, -300 System.out.printf("First pair result = %f \n", result2);
}
Hint: Math.copySign }
107. IMPORTANT: Print out the result of the division of the following calculation: a/b, where a and b are both
integers of value 1 and 4 respectively. Put the result into a float.
Explain the result.
An initial attempt at writing the code might yield the following:
public class PracticeYourJava {
public static void main(String[] args) {
int a=1, b=4;
float result = a/b; // WRONG !!!
System.out.println(result);
}
}
Explanation: The result of this code is 0! The issue here is that on seeing integer values (1 and 4 in this case),
Java automatically performs an integer calculation (irrespective of the type of the target output variable). If you
want the correct results, then ensure that you cast the input variables appropriately. In this case we would write
the following calculation for result:
float result = (float)a/(float)b;
What is the expected output of this code fragment?
public class PracticeYourJava {
public static void main(String[] args) { The program will stop running and it will throw the
108. int a = 5; exception 'java.lang.ArithmeticException' for this
int b = 0; integer divide by zero situation.
System.out.printf("%d/%d=%f",a,b,(a/b));
}
}
Infinity/-Infinity/NaN
109. Write a program which determines public class PracticeYourJava {
and prints out the result of the public static void main(String[] args) {
following computations given the float a = 0, b=0, c=-1, d=1;
noted variable values: System.out.printf("%f/%f = %f\n", a, b, a / b);
System.out.printf("%f/%f = %f\n", c, a, c / a);
float a=0, b=0, c=-1, d=1;
System.out.printf("%f/%f = %f\n", d, a, d / a);
1. a/b }
2. c/a }
3. d/a
Results
1. 0/0 = NaN (which means Not a Number)
2. -1/0 = -Infinity
3. 1/0 = Infinity
27
110. Write a program which determines public class PracticeYourJava {
and prints out the result of each of public static void main(String[] args) {
the following calculations: float a = Float.POSITIVE_INFINITY;
1. -∞ + ∞ float b = Float.NEGATIVE_INFINITY;
2. ∞ / ∞ System.out.printf("%f+%f = %f\n", b, a, b + a);
3. -∞ / ∞ System.out.printf("%f/%f = %f\n", b, a, b / a);
4. ∞ / 0 System.out.printf("%f/%f = %f\n", b, b, b / b);
5. -∞ / 0 System.out.println(a+ "/0 = " + (a/0));
System.out.println(b+ "/0 = " + (b/0));
Hint: The constants //System.out.printf("%f/%f=%f\n", a, 0, a / 0);
Float.POSITIVE_INFINITY, //System.out.printf("%f/%f=%f\n", b, 0, b / 0);
Float.NEGATIVE_INFINITY }
}
Results
1. –Infinity + Infinity = NaN
2. –Infinity / Infinity = NaN
3. –Infinity / -Infinity = NaN
4. Infinity / 0 = Infinity
5. –Infinity / 0 = -Infinity
Complex Numbers
111. We have the complex number 10 + 5i, public class PracticeYourJava {
with each of its numerical values public static void main(String[] args) {
expressed in a double variable. double x_var1 = 5;
Express it in polar form, i.e. (r, θ). double y_var1 = 10;
double r = Math.hypot(x_var1, y_var1);
Hint: Math.hypot, Math.atan2 double theta = Math.atan2(x_var1, y_var1);
System.out.printf("The complex number in polar form is
(%f, %f)\n", r, theta);
}
}
Increment, decrement and shorthand operators
112. Given the following initialized variable: 3
int i=2;
The increment operator(++) simply means that the value of the
State what its value is after the statement: variable in question should be incremented by 1.
i++;
113. Given the following variable: 9.46
double i=8.46;
The increment operator also works on floating point numbers,
State what its value is after the statement: incrementing the value of the variable in question by 1.
i++;
114. Given the following initialized variable: 3
int i=2; It does not matter for a variable in a standalone statement like this
State what its value is after the statement: whether the increment operator appears before or after the variable.
++i; The same logic applies to the decrement operator.
115. Given the following variable: int i=26; 25
State what its value is after the statement: The decrement operator(--) simply means that the value of the
i--; variable in question should be decremented by 1.
Given the following variable: int i=23; This statement is saying j = incremented value of i
State what the values of j and i are after Thus i is incremented first before assigning the incremented value of i
116. the following statement: to j. Thus the result is:
j=24
int j=++i; i=24
Given the following variable: j=23
int i=23; i=24
117. State what the values of j and i are after The statement j=i++; means the following:
the following statement: assign i to j and then afterwards increment i
int j=i++; Thus j is assigned the current value of i, that is 23 and then i is
28
incremented to 24.
118. Given the following code snippet: 1. i = 6
int i=5; j=27; 2. j = 26
int result = i++ + --j; 3. result = 5+26 = 31
1. What is the expected value of i? In words we can say that the line of code means the following:
2. What is the expected value of j? result=
3. What is the expected value of (i, (then increment i), PLUS (decremented value of j))
result?
119. Given the following code snippet:
int i=5; j=27; 1. i=4
result = --i - --j; 2. j=26
3. result= 4-26 = -22
1. What is the expected value of i?
2. What is the expected value of j? In words we can say:
result = (decrement i MINUS decrement j)
3. What is the expected value of
result?
Shorthand operators
Given two numerical variables g and y,
120. what does the following statement mean? This means increment g by y, in short, g = g+y;
g+=y;
Given two numerical variables g and y,
121. what does the following statement mean? This means multiply g by y, in short it means exactly the same thing as:
g = g*y;
g*=y;
Given two numerical variables g and y,
122. what does the following statement mean? This means divide g by y, in short, g = g/y;
g/=y;
Given two numerical variables g and y,
123. what does the following statement mean? This means decrement g by y, in short, g = g-y;
g-=y;
Given the following variable: int i=12, i=41
124. state the value of i after the statement The given statement is a shorthand way of saying: i = i+29; (i.e. add
i+=29; 29 to i)
Given the following variable: int i=39, i=13
125. state the value of i after the statement The given statement is a shorthand way of saying: i = i/3; (i.e. divide
i/=3; i by 3)
Given the following variable: int j=9, j=54
126. state the value of j after the statement The given statement is a shorthand way of saying: j = j*6; (i.e.
j*=6; multiply j by 6)
Given the following variable: float 3.2
127. x=5.2f, state the value of x after the The given statement is a shorthand way of saying: x = x-2; (i.e.
following statement: x-=2; decrement x by 2)
What is the difference between the
128. following two statements? There is no difference; both mean the same thing, which is increment i
i+=1;
i++; by 1.
29
If I added 2 to the value of x, then x would be moved to the position Integer.MIN_VALUE - 1.
This is how integer overflow occurs in Java.
Integer overflow should be assumed to be a risk for any integer computation.
Note: Even though we used the int type as an example, this concept applies to any integer type.
130. Describe the concept of integer underflow.
Integer underflow happens when the result of an integer computation results in a value that is less than (i.e.
closer to -∞) the minimum value that the integer type in question can contain. Continuing with the previous
analogy of int values on a wheel, imagine we have x= Integer.MIN_VALUE. If we subtract the value of 1 from x,
i.e. x=x-1, we are moving backwards on the wheel and the result is x= Integer.MAX_VALUE, which is clearly
incorrect!
131. How do I guard against the integer overflow/underflow issue?
Use the “Exact” set of methods (introduced in Java 8) of the class Math instead of the regular integer operators.
132. What is the result if a computation overflows or underflows when we use an “Exact” method?
An exception will be generated by the program. If the exception is not explicitly caught by the program, the
program will stop running. We will look at exceptions in a later chapter.
133. I have two int variables a and b, the addition of which has a risk of overflowing and I want to catch this
overflow. Write a sample program to show how this would be done.
State what the output of this program is. Use a value of Integer.MAX_VALUE for both variables a and b.
Hint: Math.addExact
public class PracticeYourJava {
public static void main(String[] args) {
int a = Integer.MAX_VALUE; //just a value for the purposes of this program
int b = Integer.MAX_VALUE; //as above
int total;
total = Math.addExact(a, b);
System.out.println(total);
}
}
Note(s):
1. Running this code for the choice of numbers herein will result in an overflow, which causes the throwing of
the exception java.lang.ArithmeticException. Exceptions are discussed in a later chapter.
2. Note that if you did not use the Math.addExact method keyword, the result would overflow anyway, but not
inform you (see the next exercise).
3. The same exception occurs for integer underflow conditions.
134. I have two int variables a and b each with the value Integer.MAX_VALUE. Add these using the addition operator
and print out the result. Contrast the results of this computation with the result of the preceding exercise.
public class PracticeYourJava {
public static void main(String[] args) {
int a = Integer.MAX_VALUE; //just a value for the purposes of this program
int b = Integer.MAX_VALUE; //as above
int total;
total = a + b;
System.out.println(total);
}
}
Output: -2
Notes: The result of the computation is clearly wrong due to the fact that it has overflowed! Also, note that there
was no exception generated!
Conclusion: If we want to detect under/overflow conditions, then the “Exact” methods should be used.
However, their exceptions should be caught in order to avoid program stoppage due the exception being thrown.
We look at how to handle exceptions in a later chapter.
30
135. We have the int variable, a = Integer.MAX_VALUE.
Write two programs to show the result of incrementing the value a by 1. The first program should use the
standard increment operator, the second should use the Math.incrementExact method.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args){ public static void main(String[] args){
int a = Integer.MAX_VALUE; int a = Integer.MAX_VALUE;
int total = ++a; int total = Math.incrementExact(a);
System.out.println(total); System.out.println(total);
} }
} }
Result: The computation results in an overflow. However, in the first case, the overflow is silent, thus putting an
erroneous result Integer.MIN_VALUE into the variable total. In the second case using Math.incrementExact the
following exception is generated: java.lang.ArithmeticException.
136. We have two int values, a = Integer.MAX_VALUE and b = 2.
Write two programs to show the result of multiplying a by b. The first program should use the standard
multiplication operator, the second should use the Math.multiplyExact method.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args) { public static void main(String[] args) {
int a = Integer.MAX_VALUE; int a = Integer.MAX_VALUE;
int b = 2; int b = 2;
int total = a * b; int total = Math.multiplyExact(a, b);
System.out.println(total); System.out.println(total);
} }
} }
Result: As expected, the computation results in an overflow. However, in the first case, the overflow is silent,
thus putting an erroneous result into the variable total: -2. In the second case using Math.multiplyExact the
following exception is generated: java.lang.ArithmeticException.
137. We have two int values, a = Integer.MIN_VALUE and b = 1.
Write two programs to show the result of subtracting b from a. The first program should use the standard
subtraction operator, the second should use the Math.subtractExact method.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args) { public static void main(String[] args) {
int a = Integer.MIN_VALUE; int a = Integer.MIN_VALUE;
int b = 2; int b = 2;
int total = a - b; int total = Math.subtractExact(a, b);
System.out.println(total); System.out.println(total);
} }
} }
Result: As expected, the computation results in an underflow. However, in the first case, the underflow is silent,
thus putting a clearly erroneous result into the variable total: 2147483646. In the second case using
Math.subtractExact the following exception is generated: java.lang.ArithmeticException.
138. We have the following int variable, a = Integer.MIN_VALUE.
Write two programs to show the result of decrementing the value a by 1. The first program should use the
standard decrement operator, the second should use the Math.decrementExact method.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args) { public static void main(String[] args) {
int a = Integer.MIN_VALUE; int a = Integer.MIN_VALUE;
int total = --a; int total = Math.decrementExact(a);
System.out.println(total); System.out.println(total);
} }
} }
Result: As expected, the computation results in an underflow. However, in the first case, the underflow is silent,
thus putting a clearly erroneous result into the variable total: 2147483647. In the second case using
31
Math.decrementExact the following exception is generated: java.lang.ArithmeticException.
139. We have the following int variable, a = Integer.MIN_VALUE. Write two programs to show the result of
attempting to negate this value. The first program should use the negation operator (-) and the second should use
the method Math.negateExact. State the result of the program and explain why it is so.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args) { public static void main(String[] args) {
int a = Integer.MIN_VALUE; int a = Integer.MIN_VALUE;
int total = -a; int total = Math.negateExact(a);
System.out.println(total); System.out.println(total);
} }
} }
Result: An exception, java.lang.ArithmeticException is generated.
Reason: When worked out manually, the result of this negation = Integer.MAX_VALUE + 1. This clearly is a
number that an int cannot contain (this is an overflow scenario) and therefore the method negateExact throws
an exception.
140. We have the following long variable, a = 3047483688. Write two separate programs to cast it to an int, the first
program using a cast and the second using the method Math.toIntExact. Observe and comment on the output
of each program.
public class PracticeYourJava { public class PracticeYourJava {
public static void main(String[] args) { public static void main(String[] args) {
long a = 3047483688L; long a = 3047483688L;
int result = (int)a; int total = Math.toIntExact(a);
System.out.println(result); System.out.println(total);
} }
} }
Result: The first solution gives the clearly erroneous result of this cast: -1247483608. The second solution
rightfully throws the exception java.lang.ArithmeticException.
141. If we have integer computations whose input values or results we expect to exceed the value Long.MAX_VALUE,
what means can we use to safely handle such numbers in Java?
Use the class BigInteger. This class represents arbitrarily long integers. Exercises on the class BigInteger are
presented in Chapter 12, entitled Number Handling III.
Hexadecimal numbers
public class PracticeYourJava {
144. Write a program which assigns the public static void main(String[] args) {
32
hexadecimal value FFF0 to an int int var01 = 0xFFF0;
variable named var01. System.out.println(var01);
Print out the equivalent base 10 }
number. }
145. Write a program which adds the public class PracticeYourJava {
hexadecimal values 1EC05 and F238C. public static void main(String[] args) {
Print out the resulting base 10 number. int var01 = 0x1EC05;
int var02 = 0xF238C;
int var03 = var01 + var02;
System.out.println(var03);
}
}
Note: later we’ll see how to print out the result in hexadecimal.
Formatting
In this section we move on to exercises with which to hone our skills on formatting mathematical output.
In particular we look at the formatting options available for the method printf. Unless otherwise specified in this
section, every output directive implies the usage of printf.
It should be noted that the method println does have formatting specifiers but we do not address those here.
public class PracticeYourJava {
Given the int variable m=304638, public static void main(String[] args) {
print the value of this variable int m = 304638;
150. out on separate lines in decimal, System.out.printf("In decimal :%d\n", m);
hexadecimal and octal format. System.out.printf("In hexadecimal :%x\n", m);
System.out.printf("In octal :%o\n", m);
Hint: %d, %x, %o }
}
33
Discovering Diverse Content Through
Random Scribd Documents
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.