Java Tutorial/Data Type/Integer
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
- 1 Bit manipulation methods in Integer: bitCount
- 2 Compare integers using if statements, relational operators and equality operators
- 3 Compare Two Java int Arrays
- 4 Convert a byte array to a Hex string
- 5 Convert an int value to String: concatenate string to an int value
- 6 Convert an int value to String: Integer.toString(i)
- 7 Convert an int value to String: new Integer(i).toString()
- 8 Convert a String to int
- 9 Convert binary number to decimal number
- 10 Convert decimal integer to hexadecimal number
- 11 Convert decimal integer to octal number
- 12 Convert Decimal to Binary
- 13 Convert Decimal to Hexadecimal
- 14 Convert Decimal to Octal
- 15 Convert from Byte array to hexadecimal string
- 16 Convert from decimal to binary
- 17 Convert from decimal to hexadecimal
- 18 Convert from decimal to hexadecimal with leading zeroes and uppercase
- 19 Convert from integer to String
- 20 Convert from String to integer
- 21 Convert hexadecimal number to decimal number
- 22 Convert octal number to decimal number
- 23 Convert string to an integer or number
- 24 Create an Integer object
- 25 Equals Method
- 26 Equivalence
- 27 Highest one bit: 128
- 28 Integer.lowestOneBit(n), Integer.numberOfLeadingZeros(n), Integer.numberOfTrailingZeros(n)
- 29 Integer: MAX, MIN VALUE
- 30 Integer.reverseBytes( ) reverses the order of the bytes in num and returns the result
- 31 Integer: rotate Left
- 32 Integer signum() returns
- 33 Java int:int is 32 bit signed type ranges from � to .
- 34 Parse and format a number to decimal
- 35 Parse and format a number to octal
- 36 Pass an integer by reference
- 37 Read Integers from console and calculate
- 38 Reverse an Integer
- 39 Shifted and scaled random integers
- 40 The number of bits used to represent an int value in two"s complement binary form.
- 41 To catch illegal number conversion, try using the try/catch mechanism.
Bit manipulation methods in Integer: bitCount
public class MainClass {
public static void main(String args[]) {
int n = 170; // 10101010
System.out.println("Value in binary: 10101010");
System.out.println("Number of one bits: " + Integer.bitCount(n));
}
}
Value in binary: 10101010 Number of one bits: 4
Compare integers using if statements, relational operators and equality operators
import java.util.Scanner;
public class MainClass
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
int number2;
System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
if ( number1 < number2 )
System.out.printf( "%d < %d\n", number1, number2 );
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );
if ( number1 <= number2 )
System.out.printf( "%d <= %d\n", number1, number2 );
if ( number1 >= number2 )
System.out.printf( "%d >= %d\n", number1, number2 );
}
}
Enter first integer: 2 Enter second integer: 3 2 != 3 2 < 3 2 <= 3
Compare Two Java int Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a1 = new int[] { 2, 7, 1 };
int[] a2 = new int[] { 2, 7, 1 };
System.out.println(Arrays.equals(a1, a2));
}
}
Convert a byte array to a Hex string
public class Main {
public static void main(String[] argv) {
byte[] b = "ada".getBytes();
for (int i = 0; i < b.length; i++) {
System.out.println(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
}
}
}
/*
61
64
61
*/
Convert an int value to String: concatenate string to an int value
public class Main {
public static void main(String[] args) {
int i = 50;
String str = "" + i;
System.out.println(str + " : " + ("" + i).getClass());
}
}
// 50 : class java.lang.String
Convert an int value to String: Integer.toString(i)
public class Main {
public static void main(String[] args) {
int i = 50;
String str = Integer.toString(i);
System.out.println(str + " : " + Integer.toString(i).getClass());
}
}
//50 : class java.lang.String
Convert an int value to String: new Integer(i).toString()
public class Main {
public static void main(String[] args) {
int i = 50;
String str = new Integer(i).toString();
System.out.println(str + " : " + new Integer(i).toString().getClass());
}
}
//50 : class java.lang.String
Convert a String to int
public class Main {
public static void main(String[] argv) {
String sValue = "5";
try {
int iValue = Integer.parseInt(sValue);
System.out.println(iValue);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
}
Convert binary number to decimal number
public class Main {
public static void main(String[] args) {
System.out.println(Integer.parseInt("111000", 2));
}
}
Convert decimal integer to hexadecimal number
public class Main {
public static void main(String[] args) {
System.out.println(Integer.toHexString(32));
}
}
Convert decimal integer to octal number
public class Main {
public static void main(String[] args) {
System.out.println(Integer.toOctalString(27));
}
}
Convert Decimal to Binary
public class Main {
public static void main(String[] args) {
int integer = 127;
String binary = Integer.toBinaryString(integer);
System.out.println("Binary value of " + integer + " is " + binary + ".");
int original = Integer.parseInt(binary, 2);
System.out.println("Integer value of binary "" + binary + "" is " + original + ".");
}
}
Convert Decimal to Hexadecimal
public class Main {
public static void main(String[] args) {
System.out.println(Integer.toHexString(1976));
System.out.println(Integer.parseInt("7b8", 16));
}
}
Convert Decimal to Octal
public class Main {
public static void main(String[] args) {
int integer = 1024;
String octal = Integer.toOctalString(integer);
System.out.printf("Octal value of %d is "%s".\n", integer, octal);
System.out.printf("Octal value of %1$d is "%1$o".\n", integer);
int original = Integer.parseInt(octal, 8);
System.out.printf("Integer value of octal "%s" is %d.", octal, original);
}
}
Convert from Byte array to hexadecimal string
public class Main {
public static void main(String[] args) throws Exception {
int i = Integer.valueOf("1234A", 16).intValue();
// or
i = Integer.parseInt("BBA", 16);
}
}
Convert from decimal to binary
public class Main {
public static void main(String[] args) throws Exception {
int i = 42;
String bin = Integer.toBinaryString(i);
System.out.println(bin);
}
}
//101010
Convert from decimal to hexadecimal
public class Main {
public static void main(String[] args) throws Exception {
int i = 42;
String hexstr = Integer.toString(i, 16);
System.out.println(hexstr);
hexstr = Integer.toHexString(i);
System.out.println(hexstr);
}
}
/*
2a
2a
*/
Convert from decimal to hexadecimal with leading zeroes and uppercase
public class Main {
public static void main(String[] args) throws Exception {
System.out.print(Integer.toHexString(0x10000 | i).substring(1).toUpperCase());
}
}
Convert from integer to String
public class Main {
public static void main(String[] args) throws Exception {
int i = 2;
String str = Integer.toString(i);
System.out.println(str);
// or
str = "" + i;
System.out.println(str);
}
}
Convert from String to integer
public class Main {
public static void main(String[] args) throws Exception {
String str = "25";
int i = Integer.valueOf(str).intValue();
// or
i = Integer.parseInt(str);
}
}
Convert hexadecimal number to decimal number
public class Main {
public static void main(String[] args) {
System.out.println(Integer.parseInt("20", 16));
}
}
Convert octal number to decimal number
public class Main {
public static void main(String[] args) {
System.out.println(Integer.parseInt("33", 8));
}
}
Convert string to an integer or number
public class Main {
public static void main(String[] args) {
String myNumber = "13";
Integer number = Integer.parseInt(myNumber);
System.out.println("My lucky number is: " + number);
number = Integer.parseInt(myNumber, 16);
System.out.println("My lucky number is: " + number);
number = Integer.parseInt(myNumber, 8);
System.out.println("My lucky number is: " + number);
}
}
Create an Integer object
public class Main {
public static void main(String[] args) {
Integer intObj1 = new Integer(10);
Integer intObj2 = new Integer("10");
System.out.println(intObj1);
System.out.println(intObj2);
}
}
Equals Method
public class MainClass {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1.equals(n2));
}
}
true
Equivalence
public class MainClass {
public static void main(String[] args) {
Integer n1 = new Integer(47);
Integer n2 = new Integer(47);
System.out.println(n1 == n2);
System.out.println(n1 != n2);
}
}
false true
Highest one bit: 128
public class MainClass {
public static void main(String args[]) {
int n = 170;
System.out.println("Highest one bit: " + Integer.highestOneBit(n));
}
}
Integer.lowestOneBit(n), Integer.numberOfLeadingZeros(n), Integer.numberOfTrailingZeros(n)
public class MainClass {
public static void main(String args[]) {
int n = 170;
System.out.println("Lowest one bit: " + Integer.lowestOneBit(n));
System.out.println("Number of leading zeros : " + Integer.numberOfLeadingZeros(n));
System.out.println("Number of trailing zeros : " + Integer.numberOfTrailingZeros(n));
System.out.println("\nBeginning with the value 1, " + "rotate left 16 times.");
}
}
Lowest one bit: 2 Number of leading zeros : 24 Number of trailing zeros : 1 Beginning with the value 1, rotate left 16 times.
Integer: MAX, MIN VALUE
A constant holding the maximum value an int can have, 2^31-1.
A constant holding the minimum value an int can have, -2^31.
public class MainClass {
public static void main(String[] arg) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
2147483647 -2147483648
Integer.reverseBytes( ) reverses the order of the bytes in num and returns the result
public class MainClass {
public static void main(String args[]) {
System.out.println(Integer.reverseBytes(10));
System.out.println(Integer.reverseBytes(-10));
System.out.println(Integer.reverseBytes(0));
}
}
167772160 -150994945 0
Integer: rotate Left
public class MainClass {
public static void main(String args[]) {
int n = 1;
for (int i = 0; i < 16; i++) {
n = Integer.rotateLeft(n, 1);
System.out.println(n);
}
}
}
2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
Integer signum() returns
- -1 if num is negative
- 0 if it is zero, and
- 1 if it is positive
public class MainClass {
public static void main(String args[]) {
System.out.println(Integer.signum(10));
System.out.println(Integer.signum(-10));
System.out.println(Integer.signum(0));
}
}
1 -1 0
Java int:int is 32 bit signed type ranges from � to .
public class Main {
public static void main(String[] args) {
int i = 0;
int j = 100;
System.out.println("Value of int variable i is :" + i);
System.out.println("Value of int variable j is :" + j);
}
}
Parse and format a number to decimal
public class Main {
public static void main(String[] argv) throws Exception {
int i = Integer.parseInt("1023");
String s = Integer.toString(i);
System.out.println(s);
}
}
Parse and format a number to octal
public class Main {
public static void main(String[] argv) throws Exception {
int i = Integer.parseInt("1000", 8);
String s = Integer.toString(i, 8);
System.out.println(s);
}
}
Pass an integer by reference
public class Main {
public static void main(String[] argv) {
int[] a = new int[1];
a[0] = 1;
add(a);
System.out.println(a[0]);
}
static void add(int[] a) {
a[0] = a[0] + 2;
}
}
// 3
Read Integers from console and calculate
import java.util.Scanner;
public class MainClass
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int x;
int y;
int z;
int result;
System.out.print( "Enter first integer: " );
x = input.nextInt();
System.out.print( "Enter second integer: " );
y = input.nextInt();
System.out.print( "Enter third integer: " );
z = input.nextInt();
result = x * y * z;
System.out.printf( "Product is %d\n", result );
}
}
Enter first integer: 1 Enter second integer: 2 Enter third integer: 3 Product is 6
Reverse an Integer
class ReverseInt {
public static void main(String[] args) {
int num = 1234567890;
int[] digits = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 0;
while (num != 0) {
digits[i++] = num % 10;
num /= 10;
}
for (i = 0; i < digits.length; i++)
System.out.print(digits[i]);
}
}
Shifted and scaled random integers
import java.util.Random;
public class MainClass
{
public static void main( String args[] )
{
Random randomNumbers = new Random(); // random number generator
int face; // stores each random integer generated
for ( int i = 1; i <= 20; i++ )
{
// pick random integer from 1 to 6
face = 1 + randomNumbers.nextInt( 6 );
System.out.printf( "%d ", face );
// if i is divisible by 5, start a new line of output
if ( i % 5 == 0 )
System.out.println();
}
}
}
3 6 4 1 1 2 5 6 5 1 2 6 2 3 2 1 5 1 2 4
The number of bits used to represent an int value in two"s complement binary form.
public class MainClass {
public static void main(String[] arg) {
System.out.println(Integer.SIZE);
}
}
32
To catch illegal number conversion, try using the try/catch mechanism.
public class Main {
public static void main(String[] args) throws Exception {
try {
int i = Integer.parseInt("asdf");
} catch (NumberFormatException e) {
;
}
}
}