Chap05 Numbers
Chap05 Numbers
5 Numbers 2
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
5.2 Checking Whether a String Is a Valid Number . . . . . . . . . . . . . . . 2
5.3 Storing a Larger Number in a Smaller Number . . . . . . . . . . . . . . . 3
5.4 Wrapper Class and its method . . . . . . . . . . . . . . . . . . . . . . . . 4
5.5 Converting Numbers to Objects and Vice Versa . . . . . . . . . . . . . . 10
5.6 Taking a Fraction of an Integer Without Using Floating Point . . . . . . 11
5.7 Ensuring the Accuracy of Floating-Point Numbers . . . . . . . . . . . . . 12
5.8 Comparing Floating-Point Numbers . . . . . . . . . . . . . . . . . . . . . 13
5.9 Rounding Floating-Point Numbers . . . . . . . . . . . . . . . . . . . . . 14
5.10 Formatting Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.11 Converting Between Binary, Octal, Decimal, and Hexadecimal . . . . . . 21
5.12 Operating on a Series of Integers . . . . . . . . . . . . . . . . . . . . . . 23
5.13 Formatting with Correct Plurals . . . . . . . . . . . . . . . . . . . . . . . 24
5.14 Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . 25
5.15 Calculating Trigonometric Functions . . . . . . . . . . . . . . . . . . . . 26
5.16 Taking Logarithms: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.17 Multiplying Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.18 Handling Very Large Numbers . . . . . . . . . . . . . . . . . . . . . . . . 28
1
Chapter 5
Numbers
5.1 Introduction
Numbers are basic to just about any computation. They’re used for array indices, tem-
peratures, salaries, ratings, and an infinite variety of things.
Java has several built-in or “primitive” types that can be used to represent numbers,
summarized in Figure 5.1 with their “wrapper” (object) types.
2
Soultion:
Assignment
3
Example: Storing an int into a short, char, or byte
int i;
double j = 2.75;
i = j; // EXPECT COMPILE ERROR
i = ( int ) j; // with cast ; i gets 2
System . out . println (" i = " + i ) ;
byte b;
b = i; // EXPECT COMPILE ERROR
b = ( byte )i ; // with cast , i gets 2
System . out . println (" b = " + b ) ;
• Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primi-
tive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the seri-
alization. If we have a primitive value, we can convert it in objects through the
wrapper classes.
• java.util package: The java.util package provides the utility classes to deal with
objects.
• Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, Linked-
HashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
4
Table 5.1: Wrapper Class Methods
Method Purpose
static int compare (int Compares the values of num1 and num2. Returns 0 if
num1, int num2) the values are equal. Returns a negative value if num1
is less than num2. Returns a positive value if num1 is
greater than num2.
boolean equals(Object in- Returns true if the invoking Integer object is equiva-
tObj) lent to intObj. Otherwise, it returns false.
5
Example: Wrapper Class Methods Demo
Note:
• Wrapper Class Character has only one constructor which takes char type as an
argument. It doesn’t have a constructor which takes String as an argument. Be-
cause, String can not be converted into Character.
• Wrapper class Float has three constructors. The third constructor takes double
type as an argument.
Assignment
1. WAP which read a real number as a string and find out sum of the digits of the
whole part and sum of the digits of the fraction part of the real number.
6
Solution:
2. WAP which read a real number as a string and find out the summation of the
whole part and fraction part of the real number.
Solution:
3. WAP which read dob in dd/ mm/ yy format and the current date. Find out the
age of the student.
7
Solution:
4. WAP to read a file having information about inventory for a company for a year.
8
Find the total price of the stock.
Solution:
9
5.5 Converting Numbers to Objects and Vice Versa
Auto-boxing:
Auto boxing means converting a base type to object type automatically by compiler.
Example:
Auto-unboxing:
Auto-unboxing means converting a object type to base type automatically by compiler.
Example:
10
Auto-boxing Example:
Q3. Mark where auto boxing and auto unboxing happen in the below program:
Example:
11
Example:
• Values for these three public constants are defined in both the Float and the
Double wrapper classes.
12
• The value NaN has the unusual property that it is not equal to itself (i.e., NaN
!= NaN ).
Example:
double d = 123;
double e = 0;
if (d/e == Double . POSITIVE_INFINITY )
System . out . println (" Check for POSITIVE_INFINITY works " ) ;
double s = Math . sqrt ( -1) ;
if (s == Double . NaN )
System . out . println (" NaN incorrectly returns true " ) ;
if ( Double . isNaN (s ))
System . out . println (" Double . isNaN () correctly returns true " ) ;
Output:
Check for POSITIVE_INFINITY works
Double.isNaN() correctly returns true
• The equals() method returns true if the two values are the same bit for bit (i.e., if
and only if the numbers are the same or are both NaN).
13
Example:
Output:
da=0.9999999999
db=0.99999992857
Equal within EPSILON
• If you simply cast a floating value to an integer value, Java truncates the value.
A value like 3.999999 cast to an int or long becomes 3, not 4. To round floating-
point numbers properly, use Math.round().
• It has two overloads: if you give it a double , you get a long result; if you give it a
float, you get an int.
14
Example:
Note: Because 0.1f is rounded to the nearest value that can be represented in
the value set of the float type, the actual quantity added to x on each iteration is
somewhat larger than 0.1. Consequently, the loop executes only nine times and
typically fails to produce the expected output.
15
Solution:
16
Example:
Q1. Write a program to print a double number having maximum fraction digit 2.
Solution:
Q2. Write a program to print a double number having maximum fraction digit 4 and
minimum fraction digit 2.
Solution:
Q3. Write a program to set minimum integer digit to 3, maximum fraction digit to 4
17
and minimum fraction digit to 2 of a decimal number.
Solution:
Q4. Write a program to ask the user for maximum and minimum fraction and display
a real number according to it.
Changing the pattern dynamically:
• You can also construct a DecimalFormat with a particular pattern or change the
pattern dynamically using applyPattern().
18
Pattern Number Formatted String
###.### 123.456 123.456
###.# 123.456 123.5
###,###.## 123456.789 123,456.79
000.### 9.95 009.95
##0.### 0.95 0.95
$###,###.### 12345.67 $12,345.67
NumFormatDemo program:
/* * A number to format */
public static final double intlNumber = 1024.25;
/* * Another number to format */
public static final double ourNumber = 100.2345678;
NumberFormat defForm = NumberFormat . getInstance () ;
NumberFormat ourForm = new DecimalFormat ( " ##0.## " ) ;
// toPattern () will reveal the combination of #0. , etc
System . out . println (" defForm ’s pattern is " +
(( DecimalFormat ) defForm ) . toPattern () ) ;
System . out . println ( intlNumber + " formats as " +
defForm . format ( intlNumber ) ) ;
System . out . println ( ourNumber + " formats as " +
ourForm . format ( ourNumber ) ) ;
System . out . println ( ourNumber + " formats as " +
defForm . format ( ourNumber ) + " using the default format " ) ;
Output :
defForm ’s pattern is # ,##0.###
1024.25 formats as 1 ,024.25
100.2345678 formats as 100.23
100.2345678 formats as 100.235 using the default format
Q1. Write a program to print a double number in the format, 3 digits in hole part and
decimal number then two digits in fraction part.
19
Solution:
Q2. Write a program to print a double number in the format, 4 digits before decimal
(if number of digit is less print zero) and 3 digits after decimal.
Solution:
20
Solution:
Q4. Write a program to print a double number -ve sign assigned to it.
Solution:
21
certain hardware devices—or in some alternative number base (binary is base 2, octal
is base 8, decimal is 10, hexadecimal is 16). You want to convert a binary number or a
hexadecimal value into an integer.
Solution:
The class java.lang.Integer provides the solutions. Most of the time you can use Inte-
ger.parseInt(String input, int radix) to convert from any type of number to an
Integer, and Integer.toString(int input, int radix) to convert from integer to any
type.
Conversion from integer to any type:
Discussion:
• There are also specialized versions of toString(int) that don’t require you to spec-
ify the radix; for example, toBinaryString() to convert an integer to binary, to-
HexString() for hexadecimal, and so on.
22
• Going the other way, the Integer class includes toBinaryString(), toOctalString(),
and toHexString().
Assignment
1. WAP to prints the binary string "101010" as an integer in various bases such as 2,
8, 10, 16, & 36 respectively.
2. WAP to prints the integer 42 in various number bases such as 2, 8, 10, 16, & 36
respectively.
• To process a contiguous set of integers, Java provides a for loop. Loop control for
the for loop is in three parts: initialize, test, and change.
• If the test part is initially false, the loop will never be executed, not even once.
String months [] = {" January " ," February " ," March " ," April " ," May " ,
" June " ," July " ," August " ," September " ," October " ,
" November " ," December " };
for ( int i =0; i < months . length ; i ++)
{
System . out . println (" Month " + months [ i ]) ;
}
23
For discontinuous ranges of numbers, use a java.util.BitSet
24
Example: Quantized Format
Discussion:
• If you need integers, construct a java.util.Random object and call its nex-
tInt() method; if you pass it an integer value, this will become the upper bound.
Example:
You used the Unix tools sort and uniq, which together give a count of how many times
each value was chosen. For 1,000 integers, each of 10 values should be chosen about 100
times.
25
nextInt() Demo
8. The nextDouble() methods try to give a "flat" distribution between 0 and 1.0,
in which each value has an equal chance of being selected. A Gaussian or nor-
mal distribution is a bell-curve of values from negative infinity to positive infinity,
with the majority of the values around zero (0.0).
26
Figure 5.3: Flat (left) and Gaussian (right) distributions
Use the trig functions in java.lang.Math. Like java.lang.Math.random(), all the meth-
ods of the Math class are static, so no Math instance is necessary. Note that the argu-
ments for trigonometric functions are in radians, not in degrees.
Example:
// Logarithm . java
double someValue ;
// compute someValue ...
double log_e = Math . log ( someValue ) ;
Example:
27
Assignment:
1. Write a program to generate random numbers for a "flat" distribution and a nor-
mal distribution.
2. Write a program that computes trigonometric functions sine, cosine, & tangent
and displays the values of e and PI that are available in the math library.
28
You need to handle integer numbers larger than Long.MAX_VALUE or floating-point
values larger than Double.MAX_VALUE.
Solution:
In java two classes use for large number, that are present in java.math package:
Example:
System . out . println ( " Here ’s Long . MAX_VALUE : " + Long . MAX_VALUE ) ;
BigInteger bInt = new BigInteger ( " 3419229223372036854775807 " ) ;
System . out . println ( " Here ’s a bigger number : " + bInt ) ;
System . out . println ( " Here it is as a double : " +
bInt . doubleValue () ) ;
• Both BigInteger and BigDecimal objects are immutable; that is, once constructed,
they always represent a given number.
Constructor of BigInteger
Example:
1. BigInteger abs():
Returns a BigInteger whose value is the absolute value of this BigInteger.
29
Example:
Example:
7. float floatValue():
Converts this BigInteger to a float.
8. int intValue():
Converts this BigInteger to a int.
• BigDecimal(String val):
Translates the string representation of a BigDecimal into a BigDecimal.
30
• BigDecimal(BigInteger val):
Translates a BigInteger into a BigDecimal.
Methods of BigDecimal
1. BigDecimal abs():
Returns a BigDecimal whose value is the absolute value of this BigDecimal, and
whose scale is this.scale().
Real-world Applications
• Its method isProbablyPrime() can create prime pairs for public key cryptography.
BigNumCalc:
• Calculate a set of operands; the input is an Object array containing either BigDec-
imal objects (which may be pushed onto the Stack) and operators (which are op-
erated on immediately).
31
• + and * are commutative, order doesn’t matter
32