For example, considering the following code:
Integer x, y;In the above code, x and y are Integer objects assigned with primitive int values. When compiling this code, the compiler wraps them into Integer objects. Similarly, unwrapping is also done when vice versa happens.
x=12;
y=15;
A number object may be used instead of a primitive for the following reasons:
- As an argument of a method that expects an object.
- To use constants defined by a class.
- To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems.
The Number class is an abstract class. It has some abstract methods, which can be inherited by the derived class and modified according to the requirement.
Formatting Numeric Print Output
The java.io package, provides format() and printf() methods in the PrintStream class, to format numeric output. These methods can be used like the regular printf() function in C/C++. The Syntax for both printf and format() is same.
public PrintStream format(String format, Object... args)As in C, format specifiers are used, to enable formatting of the output. Format specifiers begin with a percent sign(%) and end with a converter. All converters, flags, and specifiers are documented in java.util.Formatter.
Example:
    int i = 38;
    System.out.format("The value of i is :%d%n", i);
%d denotes decimal integer
%n denotes newline character
The format() and printf() also have another argument called Locale. This is used to print the output in specific Locale. For example, Locale.FRANCE prints the output in French locale. In French locale, floating point numbers are printed with commas instead of decimals
Check out the sample TestFormat.java program in the tutorials page
DecimalFormat Class
The DecimalFormat is a subclass of NumberFormat Class, used to format decimal numbers. Using this, numbers can be parsed in different locales and patterns. The DecimalFormat class belongs to the java.text* package.
Check out the Demo program in the tutorials page.
MATH Class
The math class allows advanced arithmetic, beyond the operations performed by the arithmetic operators. The Math class includes more than 40 static methods. The key ingredients of this class:
- Constants and Basic Methods
- Exponential and Logarithmic Methods
- Trignometric Methods
- Random Numbers
tutorials
No comments:
Post a Comment