Java Tutorial/Data Type/Integer Data Type

Материал из Java эксперт
Перейти к: навигация, поиск

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>





Binary and Decimal value table

BinaryDecimal0000 000001000 00001280000 000111000 00011290000 001021000 00101300001 0000161001 00001440001 0001171001 00011450111 11001241111 11002520111 11011251111 11012530111 11101261111 11102540111 11111271111 1111255


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>





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>





Hexadecimal Numbers and its corresponding Decimal and binary value

   <source lang="java">

Hexadecimal Decimal Binary

  0               0           0000
  1               1           0001
  2               2           0010
  3               4           0011
  4               4           0100
  5               5           0101
  6               6           0110
  7               7           0111
  8               8           1000
  9               9           1001
  A               10          1010
  B               11          1011
  C               12          1100
  D               13          1101
  E               14          1110
  F               15          1111</source>
   
  
 
  



int array to byte array

   <source lang="java">

/*

* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in 
* the Software without restriction, including without limitation the rights to 
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
* SOFTWARE.
*/

public class ArrayCopy {

 public static byte[] int2byte(int[]src) {
   int srcLength = src.length;
   byte[]dst = new byte[srcLength << 2];
   
   for (int i=0; i<srcLength; i++) {
       int x = src[i];
       int j = i << 2;
       dst[j++] = (byte) ((x >>> 0) & 0xff);           
       dst[j++] = (byte) ((x >>> 8) & 0xff);
       dst[j++] = (byte) ((x >>> 16) & 0xff);
       dst[j++] = (byte) ((x >>> 24) & 0xff);
   }
   return dst;

} }</source>





Integer Calculations

  1. The basic operators in calculations are +, -, *, and /. They have the usual meanings: add, subtract, multiply, and divide, respectively.
  2. Using parentheses in arithmetic calculations to change the sequence of operations.



   <source lang="java">

public class MainClass{

 public static void main(String[] argv){
   int a = (20 - 3) * (3 - 9) / 3;
   int b = 20 - 3 * 3 - 9 / 3;    
   
   System.out.println(a);
   System.out.println(b);
 }

}</source>



-34
8


Integer Data Types in Java: memory and length

  1. There are four types of integer data variables.
  2. They can store both negative and positive values.

Data TypeValueMemorybyte-128 -- +127occupy 1 byte (8 bits) in memoryshort-32768 -- 32767occupy 2 bytes (16 bits) in memoryint-2147483648 -- 2147483647occupy 4 bytes (32 bits) in memorylong-9223372036854775808 -- 9223372036854775807occupy 8 bytes (64 bits) in memory


Min and Max values of datatype int

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   System.out.println(Integer.MIN_VALUE);
   System.out.println(Integer.MAX_VALUE);
 }

} /* -2147483648 2147483647

  • /</source>





Multiply 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 {

 /**
  * Multiply two integers, checking for overflow.
  * 
  * @param x a factor
  * @param y a factor
  * @return the product x*y
  * @throws ArithmeticException if the result can not be represented as an
  *         int
  * @since 1.1
  */
 public static int mulAndCheck(int x, int y) {
     long m = ((long)x) * ((long)y);
     if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
         throw new ArithmeticException("overflow: mul");
     }
     return (int)m;
 }

}</source>





Subtract two integers, checking for overflow.

   <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 {

 /**
  * Subtract two integers, checking for overflow.
  * 
  * @param x the minuend
  * @param y the subtrahend
  * @return the difference x-y
  * @throws ArithmeticException if the result can not be represented as an
  *         int
  * @since 1.1
  */
 public static int subAndCheck(int x, int y) {
     long s = (long)x - (long)y;
     if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
         throw new ArithmeticException("overflow: subtract");
     }
     return (int)s;
 }

}</source>