Java/Data Type/int
Содержание
- 1 Add two integers, checking for overflow.
- 2 Are all hex integers negative
- 3 Autoboxing/unboxing int
- 4 Compare Two Java int Arrays
- 5 Convert binary number to decimal number
- 6 Convert decimal integer to hexadecimal number
- 7 Convert decimal integer to octal number
- 8 Convert hexadecimal number to decimal number
- 9 Convert octal number to decimal number
- 10 Convert string to integer
- 11 Demonstrate a type wrapper.
- 12 Gets the maximum of three int values.
- 13 Gets the minimum of three int values.
- 14 Getting a Valid Integer
- 15 Given an integer, return a string that is in an approximate, but human readable format
- 16 Integer class creates primitives that wrap themselves around data items of the int data type
- 17 Integer.MIN_VALUE
- 18 Integer.toBinaryString
- 19 Integer.toHexString
- 20 Int Overflow
- 21 Java int:int is 32 bit signed type ranges from �2,147,483,648 to 2,147,483,647.
- 22 Java Sort int Array
- 23 Modifiable Integer
- 24 Multiply a decimal fraction, not using floating point
- 25 Pass an integer by reference
- 26 Returns the sign for int value x
- 27 Rolling the Dice
- 28 The Integer class cannot be changed
Add two integers, checking for overflow.
<source lang="java">
import java.io.File; /*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */
public class Main {
/**
* Add two integers, checking for overflow.
*
* @param x an addend
* @param y an addend
* @return the sum x+y
* @throws ArithmeticException if the result can not be represented as an
* int
* @since 1.1
*/
public static int addAndCheck(int x, int y) {
long s = (long)x + (long)y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int)s;
}
}
</source>
Are all hex integers negative
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
/**
* Are all hex integers negative? * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: HexNeg.java,v 1.4 2004/02/09 03:33:53 ian Exp $ */
public class HexNeg {
public static void main(String[] argv) { //+ long data[] = { 0, 0x01, 0xff, 0x100, 0xffff, 0xffffff, 0x7fffffff, 0xffffffff }; for (int i=0; i<data.length; i++) System.out.println("data["+i+"] = " + data[i]); //- }
}
</source>
Autoboxing/unboxing int
<source lang="java">
class AutoBox {
public static void main(String args[]) { Integer iOb = 100; // autobox an int int i = iOb; // auto-unbox System.out.println(i + " " + iOb); // displays 100 100 }
}
</source>
Compare Two Java int Arrays
<source lang="java">
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)); }
}
</source>
Convert binary number to decimal number
<source lang="java">
public class Main {
public static void main(String[] args) { String strBinaryNumber = "111000"; int decimalNumber = Integer.parseInt(strBinaryNumber, 2); System.out.println(decimalNumber); }
}
</source>
Convert decimal integer to hexadecimal number
<source lang="java">
public class Main {
public static void main(String[] args) { int i = 32; String strHexNumber = Integer.toHexString(i); System.out.println(strHexNumber); }
} //20
</source>
Convert decimal integer to octal number
<source lang="java">
public class Main {
public static void main(String[] args) { int i = 27; String strOctalNumber = Integer.toOctalString(i); System.out.println(strOctalNumber); }
} //33
</source>
Convert hexadecimal number to decimal number
<source lang="java">
public class Main {
public static void main(String[] args) { System.out.println(Integer.parseInt("20", 16)); }
}
</source>
Convert octal number to decimal number
<source lang="java">
public class Main {
public static void main(String[] args) { String strOctalNumber = "33"; int decimalNumber = Integer.parseInt(strOctalNumber, 8); System.out.println(decimalNumber); }
} //27
</source>
Convert string to integer
<source lang="java">
class Main {
public static void main(String[] args) { int x, y; x = Integer.parseInt("1"); y = Integer.parseInt("2"); if (x > y) { System.out.println(x + ">" + y); } else if (x < y) { System.out.println(x + "<" + y); } else { System.out.println(x + "=" + y); } }
}
</source>
Demonstrate a type wrapper.
<source lang="java">
class Wrap {
public static void main(String args[]) { Integer iOb = new Integer(100); int i = iOb.intValue(); System.out.println(i + " " + iOb); // displays 100 100 }
}
</source>
Gets the maximum of three int values.
<source lang="java">
import java.math.BigDecimal; import java.math.BigInteger; /**
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
*Provides extra functionality for Java Number classes.
* * @author * @author Eric Pugh * @author Phil Steitz * @since 1.0 * @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z bayard $ * */
public class Main {
/***
Gets the maximum of three int
values.
* * @param a value 1 * @param b value 2 * @param c value 3 * @return the largest of the values */ public static int maximum(int a, int b, int c) { if (b > a) { a = b; } if (c > a) { a = c; } return a; }
}
</source>
Gets the minimum of three int values.
<source lang="java">
import java.math.BigDecimal; import java.math.BigInteger; /**
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
*Provides extra functionality for Java Number classes.
* * @author * @author Eric Pugh * @author Phil Steitz * @since 1.0 * @version $Id: NumberUtils.java 488819 2006-12-19 21:50:04Z bayard $ * */
public class Main {
/***
Gets the minimum of three int
values.
* * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ public static int minimum(int a, int b, int c) { if (b < a) { a = b; } if (c < a) { a = c; } return a; }
}
</source>
Getting a Valid Integer
<source lang="java">
import java.util.InputMismatchException; import java.util.Scanner; public class MainClass {
static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.print("Enter an integer: "); int i = GetInteger(); System.out.println("You entered " + i); } public static int GetInteger() { while (true) { try { return sc.nextInt(); } catch (InputMismatchException e) { sc.next(); System.out.print("That"s not " + "an integer. Try again: "); } } }
}
</source>
Given an integer, return a string that is in an approximate, but human readable format
<source lang="java">
/**
* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.StringTokenizer; import java.util.Collection;
/**
* General string utils */
public class StringUtils {
final public static char COMMA = ","; final public static String COMMA_STR = ","; final public static char ESCAPE_CHAR = "\\"; private static DecimalFormat oneDecimal = new DecimalFormat("0.0"); /** * Given an integer, return a string that is in an approximate, but human * readable format. * It uses the bases "k", "m", and "g" for 1024, 1024**2, and 1024**3. * @param number the number to format * @return a human readable form of the integer */ public static String humanReadableInt(long number) { long absNumber = Math.abs(number); double result = number; String suffix = ""; if (absNumber < 1024) { // nothing } else if (absNumber < 1024 * 1024) { result = number / 1024.0; suffix = "k"; } else if (absNumber < 1024 * 1024 * 1024) { result = number / (1024.0 * 1024); suffix = "m"; } else { result = number / (1024.0 * 1024 * 1024); suffix = "g"; } return oneDecimal.format(result) + suffix; }
}
</source>
Integer class creates primitives that wrap themselves around data items of the int data type
<source lang="java">
public class MainClass {
public static void main(String[] args) { int i = 17; Integer i2 = new Integer(i); System.out.println(i2.intValue()); }
}
</source>
Integer.MIN_VALUE
<source lang="java">
public class Main {
public static void main(String args[]) { int mininteger = Integer.MIN_VALUE; System.out.println(mininteger); }
} //-2147483648
</source>
Integer.toBinaryString
<source lang="java">
import java.util.Enumeration; import java.util.Vector; class WrapperDemo {
public static void main(String[] args) { System.out.println("16055 in binary: " + Integer.toBinaryString(16055));
}
}
</source>
Integer.toHexString
<source lang="java">
import java.util.Enumeration; import java.util.Vector; class WrapperDemo {
public static void main(String[] args) { System.out.println("16055 in hexadecimal: " + Integer.toHexString(16055));
}
}
</source>
Int Overflow
<source lang="java">
public class IntOverflow {
public static void main(String[] unused) { do_shorts(); do_ints(); } protected static void do_shorts() { short i = Short.MAX_VALUE; System.out.println("i=" + i++); System.out.println("i=" + i++); System.out.println("i=" + i++); } protected static void do_ints() { int i = Integer.MAX_VALUE; System.out.println("i=" + i++); System.out.println("i=" + i++); System.out.println("i=" + i++); }
}
</source>
Java int:int is 32 bit signed type ranges from �2,147,483,648 to 2,147,483,647.
<source lang="java">
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); }
}
</source>
Java Sort int Array
<source lang="java">
import java.util.Arrays; public class Main {
public static void main(String[] args) { int[] i1 = new int[] { 2, 2, 5, 4, 1 }; for (int i:i1){ System.out.print(" " + i); } Arrays.sort(i1); for (int i:i1){ System.out.print(" " + i); } int[] i2 = new int[] { 51, 21, 31, 11, 41 }; Arrays.sort(i2, 1, 4); for (int i:i2){ System.out.print(" " + i); } }
}
</source>
Modifiable Integer
<source lang="java">
/*
* JGraphT : a free Java graph-theory library * * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2007, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */
/* ----------------------
* ModifiableInteger.java * ---------------------- * * (C) Copyright 2002-2004, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id: ModifiableInteger.java 588 2008-01-28 01:38:08Z perfecthash $ * * Changes * ------- * 2004-05-27 : Initial version (BN); * */
/**
* The*ModifiableInteger
class wraps a value of the primitive type *int
in an object, similarly to {@link java.lang.Integer}. An * object of typeModifiableInteger
contains a single field whose * type isint
. *
Unlike java.lang.Integer
, the int value which the
* ModifiableInteger represents can be modified. It becomes useful when used
* together with the collection framework. For example, if you want to have a
* {@link java.util.List} of counters. You could use Integer
but
* that would have became wasteful and inefficient if you frequently had to
* update the counters.
**
WARNING: Because instances of this class are mutable, great care must be
* exercised if used as keys of a {@link java.util.Map} or as values in a {@link
* java.util.Set} in a manner that affects equals comparisons while the
* instances are keys in the map (or values in the set). For more see
* documentation of Map
and Set
.
* * @author Barak Naveh * @since May 27, 2004 */
public class ModifiableInteger
extends Number implements Comparable
{
//~ Static fields/initializers ---------------------------------------------
private static final long serialVersionUID = 3618698612851422261L;
//~ Instance fields --------------------------------------------------------
/**
* The int value represented by this ModifiableInteger
.
*/
public int value;
//~ Constructors -----------------------------------------------------------
/**
* !!! DON"T USE - Use the {@link #ModifiableInteger(int)} constructor
* instead !!!
*
* This constructor is for the use of java.beans.XMLDecoder * deserialization. The constructor is marked as "deprecated" to indicate to * the programmer against using it by mistake.
* * @deprecated not really deprecated, just marked so to avoid mistaken use. */ @Deprecated public ModifiableInteger() { } /** * Constructs a newly allocatedModifiableInteger
object that * represents the specifiedint
value. * * @param value the value to be represented by the* ModifiableInteger
object. */ public ModifiableInteger(int value) { this.value = value; } //~ Methods ---------------------------------------------------------------- /** * Sets a new value for this modifiable integer. * * @param value the new value to set. */ public void setValue(int value) { this.value = value; } /** * Returns the value of this object, similarly to {@link #intValue()}. This * getter is NOT redundant. It is used for serialization by * java.beans.XMLEncoder. * * @return the value. */ public int getValue() { return this.value; } /** * Adds one to the value of this modifiable integer. */ public void increment() { this.value++; } /** * Subtracts one from the value of this modifiable integer. */ public void decrement() { this.value--; } /** * Compares twoModifiableInteger
objects numerically. * * @param anotherInteger theModifiableInteger
to be compared. * * @return the value0
if thisModifiableInteger
* is equal to the argumentModifiableInteger
; a value less * than0
if thisModifiableInteger
is numerically * less than the argumentModifiableInteger
; and a value * greater than0
if thisModifiableInteger
is * numerically greater than the argumentModifiableInteger
* (signed comparison). */ public int compareTo(ModifiableInteger anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal < anotherVal) ? -1 : ((thisVal == anotherVal) ? 0 : 1); } /** * Compares thisModifiableInteger
object to another object. If * the object is anModifiableInteger
, this function behaves * likecompareTo(Integer)
. Otherwise, it throws a* ClassCastException
(asModifiableInteger
objects are * only comparable to otherModifiableInteger
objects). * * @param o theObject
to be compared. * * @return the value0
if the argument is a* ModifiableInteger
numerically equal to this* ModifiableInteger
; a value less than0
if the * argument is aModifiableInteger
numerically greater than * thisModifiableInteger
; and a value greater than* 0
if the argument is aModifiableInteger
numerically * less than thisModifiableInteger
. * * @see java.lang.ruparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { return compareTo((ModifiableInteger) o); } /** * @see Number#doubleValue() */ public double doubleValue() { return this.value; } /** * Compares this object to the specified object. The result is* true
if and only if the argument is notnull
and is * anModifiableInteger
object that contains the same* int
value as this object. * * @param o the object to compare with. * * @returntrue
if the objects are the same;false
* otherwise. */ public boolean equals(Object o) { if (o instanceof ModifiableInteger) { return this.value == ((ModifiableInteger) o).value; } return false; } /** * @see Number#floatValue() */ public float floatValue() { return this.value; } /** * Returns a hash code for thisModifiableInteger
. * * @return a hash code value for this object, equal to the primitive* int
value represented by thisModifiableInteger
* object. */ public int hashCode() { return this.value; } /** * @see Number#intValue() */ public int intValue() { return this.value; } /** * @see Number#longValue() */ public long longValue() { return this.value; } /** * Returns anInteger
object representing this* ModifiableInteger
"s value. * * @return anInteger
representation of the value of this * object. */ public Integer toInteger() { return Integer.valueOf(this.value); } /** * Returns aString
object representing this* ModifiableInteger
"s value. The value is converted to signed * decimal representation and returned as a string, exactly as if the * integer value were given as an argument to the {@link * java.lang.Integer#toString(int)} method. * * @return a string representation of the value of this object in * base 10. */ public String toString() { return String.valueOf(this.value); }
} // End ModifiableInteger.java
</source>
Multiply a decimal fraction, not using floating point
<source lang="java">
/**
* Multiply a decimal fraction, not using floating point * @author Ian F. Darwin, http://www.darwinsys.ru/ * @version $Id: IntFract.java,v 1.5 2004/02/09 03:33:57 ian Exp $ */
public class IntFract {
public static void main(String[] argv) { //+ int a = 100; int b = a*5/7; System.out.println("5/7 of " + a + " is " + b); // Just for fun, do it again in floating point. final double FRACT = 0.7142857132857; int c = (int)(a*FRACT); System.out.println(FRACT + " of " + a + " is " + c); //- }
}
</source>
Pass an integer by reference
<source lang="java">
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
</source>
Returns the sign for int value x
<source lang="java">
import java.math.BigDecimal; /*
* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */
public class Main {
/**
* Returns the
* for int value x
.
* * For an int value x, this method returns +1 if x > 0, 0 if x = 0, and -1 * if x < 0.
* * @param x the value, an int * @return +1, 0, or -1, depending on the sign of x */ public static int sign(final int x) { return (x == 0) ? 0 : (x > 0) ? 1 : -1; }
}
</source>
Rolling the Dice
<source lang="java">
public class MainClass {
public static void main(String[] args) { int roll; String msg = "Here are 100 random rolls of the dice:"; System.out.println(msg); for (int i = 0; i < 100; i++) { roll = randomInt(1, 6); System.out.print(roll + " "); } } public static int randomInt(int low, int high) { int result = (int) (Math.random() * (high - low + 1)) + low; return result; }
}
</source>
The Integer class cannot be changed
<source lang="java">
// : appendixa:ImmutableInteger.java // The Integer class cannot be changed. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.util.ArrayList; import java.util.List; public class ImmutableInteger {
public static void main(String[] args) { List v = new ArrayList(); for (int i = 0; i < 10; i++) v.add(new Integer(i)); // But how do you change the int inside the Integer? }
} ///:~
</source>