Java Tutorial/Data Type/Data Type Introduction

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

Default values for primitives and references

TypeDefault Valuebooleanfalsebyte0short0int0long0Lchar\u0000float0.0fdouble0.0dobject referencenull



   <source lang="java">

public class ClassInitializer1 {

 static boolean bool;
 static byte by;
 static char ch;
 static double d;
 static float f;
 static int i;
 static long l;
 static short sh;
 static String str;
 public static void main(String[] args) {
   System.out.println("bool = " + bool);
   System.out.println("by = " + by);
   System.out.println("ch = " + ch);
   System.out.println("d = " + d);
   System.out.println("f = " + f);
   System.out.println("i = " + i);
   System.out.println("l = " + l);
   System.out.println("sh = " + sh);
   System.out.println("str = " + str);
 }

}</source>





Get the minimum and maximum value of a primitive data types

   <source lang="java">

public class Main {

 public static void main(String[] args) {
   System.out.println("Byte.MIN = " + Byte.MIN_VALUE);
   System.out.println("Byte.MAX = " + Byte.MAX_VALUE);
   System.out.println("Short.MIN = " + Short.MIN_VALUE);
   System.out.println("Short.MAX = " + Short.MAX_VALUE);
   System.out.println("Integer.MIN = " + Integer.MIN_VALUE);
   System.out.println("Integer.MAX = " + Integer.MAX_VALUE);
   System.out.println("Long.MIN = " + Long.MIN_VALUE);
   System.out.println("Long.MAX = " + Long.MAX_VALUE);
   System.out.println("Float.MIN = " + Float.MIN_VALUE);
   System.out.println("Float.MAX = " + Float.MAX_VALUE);
   System.out.println("Double.MIN = " + Double.MIN_VALUE);
   System.out.println("Double.MAX = " + Double.MAX_VALUE);
 }

}</source>





Literals

   <source lang="java">

public class MainClass {

 char c = 0xffff; // max char hex value
 byte b = 0x7f; // max byte hex value
 short s = 0x7fff; // max short hex value
 int i1 = 0x2f; // Hexadecimal (lowercase)
 int i2 = 0X2F; // Hexadecimal (uppercase)
 int i3 = 0177; // Octal (leading zero)
 // Hex and Oct also work with long.
 long n1 = 200L; // long suffix
 long n2 = 200l; // long suffix (but can be confusing)
 long n3 = 200;
 // ! long l6(200); // not allowed
 float f1 = 1;
 float f2 = 1F; // float suffix
 float f3 = 1f; // float suffix
 float f4 = 1e-45f; // 10 to the power
 float f5 = 1e+9f; // float suffix
 double d1 = 1d; // double suffix
 double d2 = 1D; // double suffix
 double d3 = 47e47d; // 10 to the power

}</source>





Primitive utilities

   <source lang="java">

/*

* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

/**

* Primitive utilities.
* 
* @version $Revision: 1958 $
* @author 
*/

public final class Primitives {

 /**
  * Get a Boolean from a boolean, equivalent to the java 1.4 method
  * Boolean.valueOf(boolean)
  * 
  * @param value
  *          the boolean
  * @return the Boolean equivalent
  */
 public static Boolean valueOf(boolean value) {
   if (value)
     return Boolean.TRUE;
   else
     return Boolean.FALSE;
 }
 /**
  * Test the equality of two doubles by converting their values into IEEE 754
  * floating-point "double format" long values.
  * 
  * @param a
  *          Double to check equality with.
  * @param b
  *          Double to check equality with.
  * @return True if a equals b.
  */
 public static boolean equals(final double a, final double b) {
   return Double.doubleToLongBits(a) == Double.doubleToLongBits(b);
 }
 /**
  * Test the equality of two doubles by converting their values into IEEE 754
  * floating-point "single precision" bit layouts.
  * 
  * @param a
  *          Float to check equality with.
  * @param b
  *          Float to check equality with.
  * @return True if a equals b.
  */
 public static boolean equals(final float a, final float b) {
   return Float.floatToIntBits(a) == Float.floatToIntBits(b);
 }
 /**
  * Test the equality of a given sub-section of two byte arrays.
  * 
  * @param a
  *          The first byte array.
  * @param abegin
  *          The begining index of the first byte array.
  * @param b
  *          The second byte array.
  * @param bbegin
  *          The begining index of the second byte array.
  * @param length
  *          The length of the sub-section.
  * @return True if sub-sections are equal.
  */
 public static boolean equals(final byte a[], final int abegin, final byte b[], final int bbegin,
     final int length) {
   try {
     int i = length;
     while (--i >= 0) {
       if (a[abegin + i] != b[bbegin + i]) {
         return false;
       }
     }
   } catch (ArrayIndexOutOfBoundsException e) {
     return false;
   }
   return true;
 }
 /**
  * Test the equality of two byte arrays.
  * 
  * @param a
  *          The first byte array.
  * @param b
  *          The second byte array.
  * @return True if the byte arrays are equal.
  */
 public static boolean equals(final byte a[], final byte b[]) {
   if (a == b)
     return true;
   if (a == null || b == null)
     return false;
   if (a.length != b.length)
     return false;
   try {
     for (int i = 0; i < a.length; i++) {
       if (a[i] != b[i]) {
         return false;
       }
     }
   } catch (ArrayIndexOutOfBoundsException e) {
     return false;
   }
   return true;
 }

}</source>





Print the limits of primitive types (e.g. byte, short, int ...) in Java

   <source lang="java">

public class Main {

 public static void main(String args[]) {
   System.out.println("Min byte value   = " + Byte.MIN_VALUE);
   System.out.println("Max byte value   = " + Byte.MAX_VALUE);
   System.out.println("Min short value  = " + Short.MIN_VALUE);
   System.out.println("Max short value  = " + Short.MAX_VALUE);
   System.out.println("Min int value    = " + Integer.MIN_VALUE);
   System.out.println("Max int value    = " + Integer.MAX_VALUE);
   System.out.println("Min float value  = " + Float.MIN_VALUE);
   System.out.println("Max float value  = " + Float.MAX_VALUE);
   System.out.println("Min double value = " + Double.MIN_VALUE);
   System.out.println("Max double value = " + Double.MAX_VALUE);
 }

}</source>





Return primitive type the passed in wrapper type corresponds to

   <source lang="java">

import java.util.HashSet; import java.util.List; import java.util.Set; /*

* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

public class Main {

 /**
  * @param wrapper
  *          a primitive wrapper type
  * @return primitive type the passed in wrapper type corresponds to
  */
 public static Class getPrimitive(Class wrapper) {
   Class primitive;
   if (Integer.class == wrapper) {
     primitive = int.class;
   } else if (Long.class == wrapper) {
     primitive = long.class;
   } else if (Double.class == wrapper) {
     primitive = double.class;
   } else if (Boolean.class == wrapper) {
     primitive = boolean.class;
   } else if (Short.class == wrapper) {
     primitive = short.class;
   } else if (Float.class == wrapper) {
     primitive = float.class;
   } else if (Byte.class == wrapper) {
     primitive = byte.class;
   } else if (Character.class == wrapper) {
     primitive = char.class;
   } else {
     throw new IllegalArgumentException("The class is not a primitive wrapper type: " + wrapper);
   }
   return primitive;
 }

}</source>





Shows default initial values

   <source lang="java">

public class MainClass {

 boolean t;
 char c;
 byte b;
 short s;
 int i;
 long l;
 float f;
 double d;
 void print(String s) {
   System.out.println(s);
 }
 void printInitialValues() {
   print("Data type      Initial value");
   print("boolean        " + t);
   print("char           [" + c + "]");
   print("byte           " + b);
   print("short          " + s);
   print("int            " + i);
   print("long           " + l);
   print("float          " + f);
   print("double         " + d);
 }
 public static void main(String[] args) {
   MainClass iv = new MainClass();
   iv.printInitialValues();
 }

}</source>



Data type      Initial value
boolean        false
char           []
byte           0
short          0
int            0
long           0
float          0.0
double         0.0


Size for Java"s Primitive Types

   <source lang="java">

Type Explanation int A 32-bit (4-byte) integer value short A 16-bit (2-byte) integer value long A 64-bit (8-byte) integer value byte An 8-bit (1-byte) integer value float A 32-bit (4-byte) floating-point value double A 64-bit (8-byte) floating-point value char A 16-bit character using the Unicode encoding scheme boolean A true or false value</source>





Surprise! Java lets you overflow

   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
   int big = 0x7fffffff; // max int value
   System.out.println("big = " + big);
   int bigger = big * 4;
   System.out.println("bigger = " + bigger);
 }

}</source>



big = 2147483647
bigger = -4


The Primitive Types

Java has eight primitive types of data: byte, short, int, long, char, float, double, and boolean.

These can be put in four groups:

  1. Integers includes byte, short, int, and long
  2. Floating-point numbers includes float and double
  3. Characters includes char, like letters and numbers.
  4. Boolean includes boolean representing true/false values.



   <source lang="java">

byte

    The smallest integer type
    a range from -128 to 127. 
    useful when working with a stream of data from a network or file. 
    Byte variables are declared by use of the byte keyword. 
    byte b, c;

int

   The most commonly used integer type
   a signed 32-bit type 
   Ranging from -2,147,483,648 to 2,147,483,647
   used to control loops and to index arrays. 
   the most efficient type

long

  a signed 64-bit type</source>
   
  
 
  



Wrapping a Primitive Type in a Wrapper Object: boolean, byte, char, short, int, long, float, double

   <source lang="java">

public class Main {

 public static void main(String[] argv) throws Exception {
   Boolean refBoolean = new Boolean(true);
   boolean bool = refBoolean.booleanValue();
   
   
   Byte refByte = new Byte((byte) 123);
   byte b = refByte.byteValue();
   
   
   Character refChar = new Character("x");
   char c = refChar.charValue();
   
   
   Short refShort = new Short((short) 123);
   short s = refShort.shortValue();
   
   
   Integer refInt = new Integer(123);
   int i = refInt.intValue();
   
   
   Long refLong = new Long(123L);
   long l = refLong.longValue();
   
   
   Float refFloat = new Float(12.3F);
   float f = refFloat.floatValue();
   
   
   Double refDouble = new Double(12.3D);
   double d = refDouble.doubleValue();
 }

}</source>