0% found this document useful (0 votes)
85 views32 pages

Chap05 Numbers

Here are the steps to solve this problem: 1. Split the given string into whole number and fractional parts using split(".") 2. Parse the whole number part to int using Integer.parseInt() 3. Parse the fractional part to double using Double.parseDouble() 4. Add the whole number and fractional parts 5. Print the sum So the code would be: ```java public static void main(String[] args) { String number = "12.45"; String[] parts = number.split("\\."); int whole = Integer.parseInt(parts[0]); double fractional = Double.parseDouble("0." + parts[1]); double

Uploaded by

Gajhodhar Paresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views32 pages

Chap05 Numbers

Here are the steps to solve this problem: 1. Split the given string into whole number and fractional parts using split(".") 2. Parse the whole number part to int using Integer.parseInt() 3. Parse the fractional part to double using Double.parseDouble() 4. Add the whole number and fractional parts 5. Print the sum So the code would be: ```java public static void main(String[] args) { String number = "12.45"; String[] parts = number.split("\\."); int whole = Integer.parseInt(parts[0]); double fractional = Double.parseDouble("0." + parts[1]); double

Uploaded by

Gajhodhar Paresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Contents

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.

Figure 5.1: Numeric Types

5.2 Checking Whether a String Is a Valid Number


Problem
You need to check whether a given string contains a valid number, and, if so, convert it
to binary (internal) form.
Solution
To accomplish this, use the appropriate wrapper class’s conversion routine and catch
the NumberFormatException.

2
Soultion:

public static void main ( String [] args ) {


String s = args [0];
try {
Double d= Double . parseDouble ( s ) ;
System . out . println ( d ) ;
}
catch ( NumberFormatException e )
{
System . out . println ( " Invalid num : " + s ) ;
return ;
}
}

Assignment

1. Write a program which read a sting and convert it to integer number.

2. Write a program which read a string and convert it to double number.

5.3 Storing a Larger Number in a Smaller Number


Problem
You have a number of a larger type and you want to store it in a variable of a smaller
type.
Discussion
Example:

Default type for a number with a decimal point is double , not


float . So code like :
float f = 3.0;
won ’t even compile ! It ’s as if you had written :
double tmp = 3.0;
float f = tmp ;
You can fix it in one of several ways :
\ begin { itemize }
\ item By making the 3.0 a float ( probably the best solution )
\ item By making f a double
\ item By putting in a cast
\ item By assigning an integer value of 3 , which will get
" promoted " (e .g ., float f = 3 )
\ end { itemize }
float f = 3.0 f; // or just 3 f
double f = 3.0;
float f = ( float ) 3.0;
float f = 3;

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 ) ;

5.4 Wrapper Class and its method


Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different
scenarios, where we need to use the wrapper classes.

• 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.

• Synchronization: Java synchronization works with objects in Multithreading.

• 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 parseInt(s) returns a signed decimal integer value equivalent to


string’s

Static Integer valueOf() returns a Integer object equivalent to string’s

String toString(i) returns a new String object representing the integer i

byte byteValue() returns the value of this Integer as a byte

double doubleValue() returns the value of this Integer as a double

float floatValue() returns the value of this Integer as a float

int intValue() returns the value of this Integer as an int

short shortValue() returns the value of this Integer as a short

long longValue() returns the value of this Integer as a long

int compareTo(int i) Compares the numerical value of the invoking object


with that of i. Returns 0 if the values are equal. Re-
turns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.

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

Double d = new Double (" 6.9685 " ) ;


// Converting this Double ( Number ) object to
// different primitive data types
byte b = d . byteValue () ;
short s = d. shortValue () ;
int i = d. intValue () ;
long l = d. longValue () ;
float f = d . floatValue () ;
double d1 = d . doubleValue () ;
System . out . println (" byte : " + b ) ;
System . out . println (" short : " + s ) ;
System . out . println (" int : " + i ) ;
System . out . println (" long : " + l ) ;
System . out . println (" float : " + f ) ;
System . out . println (" double : " + d1 ) ;

Constructor of wrapper class


Every wrapper class in java has two constructors,

• First constructor takes corresponding primitive data as an argument

• Second constructor takes string as an argument.

Note:

• The string passed to second constructor should be parseable to number, otherwise


you will get run time NumberFormatException.

• 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.

Example: Wrapper Class Constructor Demo

Integer iObj = new Integer (10) ;


Integer iObj1 = new Integer ( " 10 " ) ;
Integer iObj2 = new Integer ( " 10.2 " ) ; // throws
NumberFormatException

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:

String s =" 12.45 " ;


String words []= s . split ( " \\. " ) ;
for ( String s1 : words )
{
int sum =0;
for ( Character ch : s1 . toCharArray () )
{
int x = Character . getNumericValue ( ch ) ;
sum = sum + x;
}
System . out . println ( sum ) ;
}
Output :
3
9

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:

String line = " 12.45 ";


String [] words = line . split ( " \\. " ) ;
// It will print the whole part and decimal part
System . out . println ( words [0] + " . " + words [1]) ;
int sum = Integer . parseInt ( words [0]) +
Integer . parseInt ( words [1]) ;
System . out . println ( sum ) ;
Output :
12.45
57

3. WAP which read dob in dd/ mm/ yy format and the current date. Find out the
age of the student.

7
Solution:

public class FindAge {


static void findAge ( int current_date , int
current_month , int current_year , int birth_date ,
int birth_month , int birth_year )
{
int month [] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 ,
31 , 30 , 31 , 30 , 31 };
if ( birth_date > current_date ) {
current_date = current_date +
month [ current_month ];
current_month = current_month - 1;
}

if ( birth_month > current_month ) {


current_year = current_year - 1;
current_month = current_month + 12;
}
// calculate date , month , year
int calculated_date = current_date - birth_date ;
int calculated_month = current_month - birth_month ;
int calculated_year = current_year - birth_year ;
// print the present age
System . out . println ( " Present Age " ) ;
System . out . println ( calculated_year + " Years " +
calculated_month +
" Months " + calculated_date + " Days " ) ;
}
public static void main ( String [] args )
{
// present date dd / mm / yyyy
String cdate = " 22/02/2020 " ; // 22/02/2020 07/12/2018
String words []= cdate . split ( " / " ) ;
int current_date = Integer . parseInt ( words [0]) ;
int current_month = Integer . parseInt ( words [1]) ;
int current_year = Integer . parseInt ( words [2]) ;
// birth dd / mm / yyyy
String bdate = " 26/08/1990 " ; // 26/08/1990 16/12/2009
words = bdate . split ( " / " ) ;
int birth_date = Integer . parseInt ( words [0]) ;
int birth_month = Integer . parseInt ( words [1]) ;
int birth_year = Integer . parseInt ( words [2]) ;
System . out . println ( birth_date + " " + birth_month + "
"+ birth_year ) ;
// function call to print age
findAge ( current_date , current_month , current_year ,
birth_date , birth_month , birth_year ) ;
}
}
Output :
26 8 1990
Present Age
29 Years 5 Months 27 Days

4. WAP to read a file having information about inventory for a company for a year.

8
Find the total price of the stock.

Product Price. Quantity


ID.
1264 2000 4
1267 400 5

Solution:

Pattern patt = Pattern . compile ( " (\\ d +) " ) ;


FileReader fr = new FileReader ( " input . txt " ) ;
BufferedReader r = new BufferedReader ( fr ) ;
// For each line of input , try matching in it .
String line ;
Double sum =0.0;
while (( line = r . readLine () ) != null ) {
Matcher m = patt . matcher ( line ) ;
int count =0;
double prod =1.0;
while ( m. find () ) {
if (++ count >=2)
prod = prod * Double . parseDouble ( m . group (0) ) ;
}
if ( count >1)
sum = sum + prod ;
}
System . out . println (" TotalPrice : " + sum ) ;
Output :
TotalPrice :10000.0

5. Extract numeric part of a string and find the sum.


Example:
Input: “abc 123 xxxx 1 pqr 23”
Output: 147
Solution:

import java . util . regex .*;


public class FindSum {
public static void main ( String [] args ) {
String s= " abc 123 xxxx 1 pqr 23 " ;
String patt =" \\ d + " ;
Matcher m= Pattern . compile ( patt ) . matcher ( s ) ;
int sum =0;
while ( m. find () )
sum = sum + Integer . parseInt ( m . group (0) ) ;
System . out . println ( " Sum : " + sum ) ;
}
}

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:

Integer iObj =10; // Auto - boxing


System . out . println ( iObj );
Float fObj =10.6 f; // Auto - boxing
System . out . println ( fObj );
Double dObj =12.5; // Auto - boxing
System . out . println ( dObj );

Auto-unboxing:
Auto-unboxing means converting a object type to base type automatically by compiler.
Example:

Integer iObj = new Integer (10) ;


int i = iObj ; // Auto - unboxing
System . out . println (i );
Float fObj = new Float (12.2) ;
float f = fObj ; // Auto - unboxing
System . out . println (f );
Byte bObj = new Byte ( " 20 " ) ;
byte b = bObj ; // Auto - unboxing
System . out . println (b );

Q1. Mark where auto unboxing happen in the below program:


Auto-unboxing Example:

public static void foo ( int x )


{
System . out . println (" x= " + x ) ;
}
public static void main ( String args [])
{
Integer iObj = new Integer (10) ;
foo ( iObj );
}

Q2. Mark where auto boxing happen in the below program:

10
Auto-boxing Example:

public static void foo ( Integer x )


{
System . out . println (" x= " + x ) ;
}
public static void main ( String args [])
{
foo (10) ;
}

Q3. Mark where auto boxing and auto unboxing happen in the below program:
Example:

public static void main ( String [] args ) {


int i = 42;
int result = foo (i );
System . out . println ( result ) ;
}
public static Integer foo ( Integer i ) {
System . out . println (" Object = " + i ) ;
return Integer . valueOf (123) ;
}

5.6 Taking a Fraction of an Integer Without Using


Floating Point
Problem
You want to multiply an integer by a fraction without converting the fraction to a
floating-point number. Solution:
Multiply the integer by the numerator and divide by the denominator.

11
Example:

double d1 = 0.666 * 5; // fast but obscure and inaccurate :


convert
System . out . println ( d1 ) ; // 2/3 to 0.666 in programmer ’s head
double d2 = 2/3 * 5; // wrong answer - 2/3 == 0 , 0*5 = 0
System . out . println ( d2 ) ;
double d3 = 2d /3 d * 5; // " normal "
System . out . println ( d3 ) ;
double d4 = (2*5) /3 d ; // one step done as integers , almost same
answer
System . out . println ( d4 ) ;
int i5 = 2*5/3; // fast , approximate integer answer
System . out . println ( i5 ) ;
Output :
3.33
0.0
3.333333333333333
3.3333333333333335
3

5.7 Ensuring the Accuracy of Floating-Point Num-


bers
Problem
You want to know if a floating-point computation generated a sensible result.
Solution
Compare with the INFINITY constants, and use isNaN() to check for “not a num-
ber”.

• In java integer division by 0 consider as logical error so it throws an ArithmeticEx-


ception.

• Floating-point operations, however, do not throw an exception because they are


defined over an (almost) infinite range of values.

• Java signal errors by producing the constant POSITIVE_INFINITY if you divide


a positive floating-point number by zero.

• Signal constant NEGATIVE_INFINITY if you divide a negative floating-point


value by zero.

• NaN (Not a Number) if you otherwise generate an invalid result.

• 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 ).

• x==NaN never be true, instead, the methods Float.isNaN(float) and


Double.isNaN(double) must be used.

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

5.8 Comparing Floating-Point Numbers


Problem
You want to compare two floating-point numbers for equality.
Discussion

• 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).

• To actually compare floating-point numbers for equality, it is generally desirable


to compare them within some tiny range of allowable differences; this range is
often regarded as a tolerance or as epsilon.

13
Example:

static double EPSILON =0.0000001;


public static void main ( String [] args ) {
double da = 3 * .3333333333;
double db = 0.99999992857;
System . out . println (" da = " + da + " \ n db = " + db ) ;
if ( da == db )
System . out . println ( " Equal " ) ;
else if ( equals ( da , db ) )
System . out . println ( " Equal within EPSILON " ) ;
else
System . out . println ( " Not Equal " ) ;
}
static boolean equals ( double da , double db )
{
if ( Math . abs (da - db ) < EPSILON )
return true ;
else
return false ;
}

Output:
da=0.9999999999
db=0.99999992857
Equal within EPSILON

5.9 Rounding Floating-Point Numbers


Problem
You need to round floating-point numbers to integers or to a particular precision.
Solution

• 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:

/* Round numbers greater than 0.54 instead of the normal 0.5 */


public class RoundFloatNo {
static double THRESHOLD =0.54;
public static void main ( String [] args ) {
double d =1.54;
System . out . println ( Math . round ( d ) ) ; // 2
System . out . println ( round ( d ) ) ; // 2
}
static int round ( double d )
{
return ( int ) Math . floor ( d + 1 - THRESHOLD ) ;
}
}

1. Find the output of the following code.


Example:

for ( float x = 0.1 f; x <= 1.0 f ; x += 0.1 f )


System . out . println ( x ) ;
Output :
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001

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.

2. Find the out put of the following program:


Example:

for ( double d =0.0 ; d !=1.0 ; d = d +0.1)


{
System . out . println ( d ) ;
}
Output : infinite loop

3. Modify the above program to print 0.0 to 0.9

15
Solution:

for ( double d =0.0 ; d <=1.0 ; d = d +0.1)


System . out . println ( d ) ;

4. Modify the above program to print 0.0 to 1 with epsilon .001


Solution:

for ( double d =0.0 ; d <=1.0 ; d = d +0.001)


System . out . println ( d ) ;

Note: Floating-point variables must not be used as loop counters.

5.10 Formatting Numbers


Problem
You need to format numbers.
Solution:

• Use a NumberFormat subclass.

• A DecimalFormat object appropriate to the user’s locale can be obtained from


the factory method NumberFormat.getInstance() and manipulated using set meth-
ods.

• Package to import java.text.NumberFormat;


Example:

Creating a NumberFormat object


NumberFormat nf = NumberFormat . getInstance ()

Some important Methods of NumberFormat class:

i. void setMaximumFractionDigits(int newValue)


Sets the maximum number of digits allowed in the fraction portion of a number.

ii. void setMaximumIntegerDigits(int newValue)


Sets the maximum number of digits allowed in the integer portion of a number.

iii. void setMinimumFractionDigits(int newValue)


Sets the minimum number of digits allowed in the fraction portion of a number.

iv. void setMinimumIntegerDigits(int newValue)


Sets the minimum number of digits allowed in the integer portion of a number.

16
Example:

import java . text . NumberFormat ;


public class test {
public static final double data [] = {0 , 1 , 22 d /7 , 100.2345678};
public static void main ( String [] argv ) {
// Get a format instance
NumberFormat form = NumberFormat . getInstance () ;
// Set it to look like 999.99[99]
form . setMinimumIntegerDigits (3) ;
form . setMinimumFractionDigits (2) ;
form . setMaximumFractionDigits (4) ;
// Now print using it .
for ( int i =0; i < data . length ; i ++)
System . out . println ( data [ i ] + " \ t formats as " +
form . format ( data [ i ]) ) ; }
}
Output :
0.0 formats as 000.00
1.0 formats as 001.00
3.142857142857143 formats as 003.1429
100.2345678 formats as 100.2346

Q1. Write a program to print a double number having maximum fraction digit 2.
Solution:

import java . text . NumberFormat ;


public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat nf = NumberFormat . getInstance () ;
nf . setMaximumFractionDigits (2) ;
double d =123.456;
System . out . println ( nf . format ( d ) ) ;
}
}
Output : 123.46

Q2. Write a program to print a double number having maximum fraction digit 4 and
minimum fraction digit 2.
Solution:

public class NumberFormatTest {


public static void main ( String args [])
{
NumberFormat nf = NumberFormat . getInstance () ;
nf . setMaximumFractionDigits (4) ;
nf . setMinimumFractionDigits (2) ;
double d =123.4;
System . out . println ( nf . format ( d ) ) ;
}
}
Input : 123.4
Output : 123.40
Input : 12.14567
Output : 12.1457

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:

import java . text . NumberFormat ;


public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat nf = NumberFormat . getInstance () ;
nf . setMinimumIntegerDigits (3) ;
nf . setMaximumFractionDigits (4) ;
nf . setMinimumFractionDigits (2) ;
double d =12.4;
System . out . println ( nf . format ( d ) ) ;
}
}
Input : 12.4
Output : 012.40

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().

• Some of the more common pattern characters are shown in Table.

Figure 5.2: DecimalFormat pattern characters

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

• The NumFormatDemo program uses one DecimalFormat to print a number with


only two decimal places and a second to format the number according to the de-
fault locale:

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:

import java . text . NumberFormat ;


import java . text . DecimalFormat ;
public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat ourForm = new DecimalFormat ( " ###.## " ) ;
double d =123.345;
System . out . println ( ourForm . format ( d ) ) ;
}
}
Input : 123.345
Output : 123.34
Input : 12.456
Output : 12.46
Input : 12345.47789
Output : 12345.48
Input : .345
Output : 0.34

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:

import java . text . NumberFormat ;


import java . text . DecimalFormat ;
public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat ourForm = new DecimalFormat ( " 0000.## " ) ;
double d =1234.5678;
System . out . println ( ourForm . format ( d ) ) ;
}
}
Input : 1234.5678
Output : 1234.57
Input : 12.5678
Output : 0012.57
if format is NumberFormat ourForm = new
DecimalFormat (" 0000.000 " ) ;
Input : 12.5
Output : 0012.500

Q3. Write a program to print a decimal number grouping it to 2 digit at a time.

20
Solution:

import java . text . NumberFormat ;


import java . text . DecimalFormat ;
public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat ourForm = new DecimalFormat ( " ## ,##.## " ) ;
double d =1245677.5566;
System . out . println ( ourForm . format ( d ) ) ;
}
}
Input : 1245677.5566
Output : 1 ,24 ,56 ,77.56

Q4. Write a program to print a double number -ve sign assigned to it.
Solution:

import java . text . NumberFormat ;


import java . text . DecimalFormat ;
public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat ourForm = new DecimalFormat ( " -##.## " ) ;
double d =57.5678;
System . out . println ( ourForm . format ( d ) ) ;
}
}
Input : 57.5678
Output : -57.57

Q5. Write a program to print percentage of a double number.


Solution:

import java . text . NumberFormat ;


import java . text . DecimalFormat ;
public class NumberFormatTest {
public static void main ( String args [])
{
NumberFormat ourForm = new DecimalFormat ( " %##.## " ) ;
double d =657.5566;
System . out . println ( ourForm . format ( d ) ) ;
}
}
Input : 657.5566
Output : %65755.66

Q6. Write a program to print a double number starting with Rs.

5.11 Converting Between Binary, Octal, Decimal,


and Hexadecimal
Problem
You want to display an integer as a series of bits—for example, when interacting with

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:

public class ConversionTest {


public static void main ( String args [])
{
int i =42;
String res1 = Integer . toString (i ,2) ;
String res2 = Integer . toString (i ,8) ;
String res3 = Integer . toString (i ,16) ;
String res4 = Integer . toString (i ,10) ;
System . out . println ( " 42 in base 2 is " + res1 ) ;
System . out . println ( " 42 in base 8 is " + res2 ) ;
System . out . println ( " 42 in base 16 is " + res3 ) ;
System . out . println ( " 42 in base 10 is " + res4 ) ;
}
}
Input : 42
Output : 42 in base 2 is 101010
42 in base 8 is 52
42 in base 16 is 2 a
42 in base 10 is 42

Conversion from any type of number to an Integer:

public class ConversionTest {


public static void main ( String args [])
{
String str = " 1010 " ;
Integer iObj = Integer . parseInt ( str ,2) ;
System . out . println ( " 1010 in base 2 is " + iObj ) ;
Integer iObj1 = Integer . parseInt ( str ,8) ;
System . out . println ( " 1010 in base 8 is " + iObj1 ) ;
Integer iObj2 = Integer . parseInt ( str ,16) ;
System . out . println ( " 1010 in base 16 is " + iObj2 ) ;
}
}
Input : 1010
Output : 1010 in base 2 is 10
1010 in base 8 is 520
1010 in base 16 is 4112

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().

• The String class itself includes a series of static methods—valueOf(int), valueOf(double),


and so on—that also provide default formatting. That is, they return the given
numeric value formatted as a string.

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.

5.12 Operating on a Series of Integers


Problem
You need to work on a range of integers.
Solution:
For a contiguous set, use a for loop.
Discussion:

• 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.

• For discontinuous ranges of numbers, use a java.util.BitSet.

For a contiguous set, use a for loop:

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

// A discontiguous set of integers , using a BitSet


// Create a BitSet and turn on a couple of bits .
BitSet b = new BitSet () ;
b. set (0) ; // January
b. set (3) ; // April
b. set (8) ; // September
// Presumably this would be somewhere else in the code .
for ( int i =0; i < months . length ; i ++)
{
if ( b. get ( i) )
System . out . println ( " Month " + months [ i ]) ;
}

5.13 Formatting with Correct Plurals


Problem
You’re printing something like "We used " + n + " items", but in English, "We used 1
items" is ungrammatical. You want "We used 1 item."
Solution:
Use a ChoiceFormat or a conditional statement.
Use Java’s ternary operator (cond ? trueval : falseval) in a string concatenation. Both
zero and plurals get an "s" appended to the noun in English ("no books, one book, two
books"), so we test for n==1;
Use a ChoiceFormat:
Example: Pluralized Format

import java . text . ChoiceFormat ;


public class ChoiceFormatTest {
// ChoiceFormat to just give pluralized word
static double [] limits = {0 ,1 ,2};
static String [] formats = { " reviews " ," review " ," reviews " };
static ChoiceFormat pluralizedFormat = new
ChoiceFormat ( limits , formats ) ;
static int [] data = { -1 ,0 ,1 ,2 ,3};
public static void main ( String [] argv ) {
System . out . println ( " Pluralized Format " ) ;
for ( int i : data )
System . out . println (" Found " + i + "
"+ pluralizedFormat . format ( i ) ) ;
}
}

24
Example: Quantized Format

import java . text . ChoiceFormat ;


public class ChoiceFormatTest {
// ChoiceFormat to give English text version , quantified
static ChoiceFormat quantizedFormat = new ChoiceFormat ( " 0# no
reviews |1# one review |1 < many reviews " ) ;
static int [] data ={ -1 ,0 ,1 ,2 ,3};
public static void main ( String [] argv ) {
System . out . println ( " Quantized Format " ) ;
for ( int i : data ) {
System . out . println (" Found " + quantizedFormat . format ( i ) ) ; }
}
}

5.14 Generating Random Numbers


Problem
You need to generate random numbers in a hurry.
Solution:
Use java.lang.Math.random() to generate random numbers. There is no claim that
the random values it returns are very good random numbers.
Example:

// java . lang . Math . random ( ) is static , don ’t need any


constructor calls
System . out . println ( "A random from java . lang . Math is " +
Math . random ( )) ;

Discussion:

• Note that Math.random() method only generates double values.

• 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:

Random r = new Random () ;


for ( int i =0; i <100; i ++)
{
// nextInt (10) goes from 0 -9; add 1 for 1 -10;
System . out . println (1+ r . nextInt (10) ) ;
}

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

import java . util . Random ;


class Main {
public static void main ( String [] args ) {
Random r= new Random () ;
for ( int i =0; i <1000; i ++)
System . out . println (1+ r . nextInt (10) ) ;
}
}
Output :
$ javac Main . java
$ java Main | sort | uniq -c | sort -k 2 -n
84 1
107 2
96 3
113 4
91 5
94 6
110 7
104 8
104 9
97 10

java.util.Random class has the following next*() methods:

1. boolean nextBoolean() to find a random boolean.

2. byte nextByte() to find a random byte.

3. int nextInt() to find a random int.

4. float nextFloat() to find a random float.

5. double nextDouble() to find next double.

6. long nextLong() to find next long.

7. You can also use the java.util.Random nextGaussian() method.

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).

5.15 Calculating Trigonometric Functions


Problem
You need to compute sine, cosine, and other trigonometric functions.
Solution:

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:

System . out . println ( " The cosine of 1.1418 is " +


Math . cos (1.1418) ) ;
System . out . println ( " Java ’s PI is " + Math . PI ) ;
System . out . println ( " Java ’s e is " + Math . E ) ;

5.16 Taking Logarithms:


Problem
You need to take the logarithm of a number.
Solution:
For logarithms to base e, use java.lang.Math’s log() function:
Example:

// Logarithm . java
double someValue ;
// compute someValue ...
double log_e = Math . log ( someValue ) ;

For logarithms to other bases, use the identity that:

Example:

public static double log_base ( double base , double value ) {


return Math . log ( value ) / Math . log ( base ) ;
}

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.

3. Write a program to calculate log 1000 of base 2 and 10.

4. Write a program to multiply two matrix.

5. Write a program to perform all the arithmetic operations (addition, subtraction,


multiplication, and division) on two complex numbers.

5.17 Multiplying Matrices


Problem
You need to multiply a pair of two-dimensional arrays, as is common in mathematical
and engineering applications.
Solution:
Use the following code as a model. It is straightforward to multiply an array of a nu-
meric type. The code in Example implements matrix multiplication.
Example:

public static int [][] multiply ( int [][] m1 , int [][] m2 ) {


int m1rows = m1 . length ;
int m1cols = m1 [0]. length ;
int m2rows = m2 . length ;
int m2cols = m2 [0]. length ;
if ( m1cols != m2rows )
throw new IllegalArgumentException ( " matrices don ’t
match : " + m1cols + " != " + m2rows ) ;
int [][] result = new int [ m1rows ][ m2cols ];
// multiply
for ( int i =0; i < m1rows ; i ++)
{
for ( int j =0; j < m2cols ; j ++)
{
for ( int k =0; k < m1cols ; k ++)
{
result [ i ][ j ] += m1 [ i ][ k ]* m2 [ k ][ j ];
}
}
}
return result ;

5.18 Handling Very Large Numbers


Problem

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:

1. BigInteger, to create a large integer number.

2. BigDecimal, to create a large decimal number (Real number).

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 () ) ;

• Note that the constructor takes the number as a string.

• Both BigInteger and BigDecimal objects are immutable; that is, once constructed,
they always represent a given number.

Constructor of BigInteger

• BigInteger(String val): Translates the decimal String representation of a Big-


Integer into a BigInteger.

• BigInteger(String val, int radix): Translates the String representation of a


BigInteger in the specified radix into a BigInteger.

Example:

import java . math . BigInteger ;


public class BigIntTest {
public static void main ( String args [])
{
BigInteger bi = new BigInteger ( " 1234455666666 " ) ;
System . out . println ( bi ) ;
}
}

Methods of BigInteger class

1. BigInteger abs():
Returns a BigInteger whose value is the absolute value of this BigInteger.

29
Example:

public class BigIntTest {


public static void main ( String args [])
{
BigInteger bi = new BigInteger ( " -1234455666456 " ) ;
System . out . println ( bi . abs () ) ;
}
}
Output : 1234455666456

2. BigInteger add(BigInteger val):


Returns a BigInteger whose value is (this + val).

Example:

public class BigIntTest {


public static void main ( String args [])
{
BigInteger bi1 = new BigInteger ( " 1234455666456 " ) ;
BigInteger bi2 = new BigInteger ( " 1234455666456 " ) ;
BigInteger bi3 = bi1 . add ( bi2 ) ;
System . out . println (" Sum of big integer = " + bi3 ) ;
}
}
Output : Sum of big integer = 2468911332912

3. BigInteger multiply(BigInteger val):


Returns a BigInteger whose value is (this * val).

4. BigInteger divide(BigInteger val):


Returns a BigInteger whose value is (this / val).

5. int compareTo(BigInteger val):


Compares this BigInteger with the specified BigInteger.

6. boolean equals(Object x):


Compares this BigInteger with the specified Object for equality.

7. float floatValue():
Converts this BigInteger to a float.

8. int intValue():
Converts this BigInteger to a int.

Constructor of BigDecimal class

• 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().

2. BigDecimal add(BigDecimal augend):


Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(),
augend.scale()).

3. BigDecimal divide(BigDecimal divisor):


Returns a BigDecimal whose value is (this / divisor), and whose preferred scale is
(this.scale() - divisor.scale()); if the exact quotient cannot be represented (be-
cause it has a non-terminating decimal expansion) an ArithmeticException is
thrown.

4. BigDecimal multiply(BigDecimal multiplicand):


Returns a BigDecimal whose value is (this * multiplicand), and whose scale is
(this.scale() + multiplicand.scale()).

5. int compareTo(BigDecimal val):


Compares this BigDecimal with the specified BigDecimal.

6. boolean equals(Object x):


Compares this BigDecimal with the specified Object for equality.

Real-world Applications

• BigInteger is mainly useful in cryptographic and security applications.

• Its method isProbablyPrime() can create prime pairs for public key cryptography.

• BigDecimal might also be useful in computing the size of the universe.

BigNumCalc:

1. WAP to implement a simple stack-based calculator using BigDecimal as its nu-


meric data type.
N.B.:

• An array of Objects, simulating user input

• Stack of numbers being used in the calculator.

• 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

• - and /, order *does* matter

A simple stack-based calculator using BigDecimal as its numeric data type.

import java . math .*;


import java . util .*;
public class Calculator {
static Stack < BigDecimal > stack = new Stack < >() ;
static Object obj []= { " / " ,
new BigDecimal (3419229223372036854775807.23343) ,
new BigDecimal (2.0) };
static void calc ()
{
String op =( String ) obj [0];
stack . push (( BigDecimal ) obj [1]) ;
stack . push (( BigDecimal ) obj [2]) ;
switch ( op . charAt (0) )
{
case ’+ ’:
stack . push (( stack . pop () ) . add ( stack . pop () ) ) ;
break ;
case ’ -’:
BigDecimal tmp = stack . pop () ;
stack . push (( stack . pop () ) . subtract ( tmp ) ) ;
break ;
case ’* ’:
stack . push (( stack . pop () ) . multiply ( stack . pop () ) ) ;
break ;
case ’/ ’:
BigDecimal tmp1 = stack . pop () ;
stack . push (( stack . pop () ) . divide ( tmp1 ) ) ;
break ;
default :
System . out . println ( " Invalid inputs " ) ;
break ;
}
}
public static void main ( String [] args ) {
calc () ;
System . out . println ( " Results : " + stack . pop () ) ;
}
}
Output :
Results :1709614611686018454126592

32

You might also like