Byte, Short, Integer, and Long
- The Byte,Short,Integer, and Long classes are wrappers for byte, short, int, and long integer types, respectively.
- Their constructors are as follows:
Byte(byte num)
Byte(String str) throws NumberFormatException
Short(short num)
Short(String str) throws NumberFormatException
Integer(int num)
Integer(String str) throws NumberFormatException
Long(long num)
Long(String str) throws NumberFormatException
- All these objects are constructed from either number or String which contains a valid whole number
The constants defined by these objects are as follows:
The methods defined by Byte are as follows:
Methods defined by Short are as follows
Methods defined by Integer are as follows
Methods defined by Iong are as follows:
Converting Numbers to and from Strings
- One of the significant feature of java is to converting the string representation of a number in to its corresponding type format by using the following methods
parseByte( ) //converts in to Byte type
parseShort( ) //converts in to Short type
parseInt( )//converts in to int type
parseLong( )//coverts in to long type
/* This program sums a list of numbers entered
by the user. It converts the string representation
of each number into an int using parseInt().
*/
import java.io.*;
public class ParseDemo
{
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
int i;
int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do
{
str = br.readLine();
try
{
i = Integer.parseInt(str);
}
catch(NumberFormatException e)
{
System.out.println("Invalid format");
i = 0;
}
sum += i;
System.out.println("Current sum is: " + sum);
} while(i != 0);
}
}
Input: Input:
131hk23412345
0 0
Output: Output:
Enter numbers, 0 to quit. Enter numbers, 0 to quit.
Invalid format Invalid format
Current sum is: 0 Current sum is: 0
- The Integer and Long classes also provide the methods toBinaryString( ), toHexString( ), and toOctalString( ), which convert a value into a binary, hexadecimal , or octal string, respectively.
/* Convert an integer into binary, hexadecimal,
and octal.
*/
public class StringConversions
{
public static void main(String args[])
{
int num = 19648;
System.out.println(num + " in binary: " + Integer.toBinaryString(num));
System.out.println(num + " in octal: " + Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " + Integer.toHexString(num));
}
}
Output:
19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0