Java/Data Type/Autobox Unbox

Материал из Java эксперт
Версия от 09:18, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

An error produced by manual unboxing.

   <source lang="java">

public class UnboxingError {

 public static void main(String args[]) {  
     
   Integer iOb = 1000; // autobox the value 1000 
 
   int i = iOb.byteValue(); // manually unbox as byte !!! 
 
   System.out.println(i);  // does not display 1000 ! 
 }  

}


 </source>
   
  
 
  



Autobox Demo

   <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.
*/

public class AutoboxDemo {

 public static void main(String[] args) {
   int i = 42;
   foo(i);
 }
 public static void foo(Integer i) {
   System.out.println("Object = " + i);
 }

}


 </source>
   
  
 
  



Autoboxing/unboxing occurs inside expressions.

   <source lang="java">
 
  

class AutoBox3 {

 public static void main(String args[]) {
   Integer iOb, iOb2;
   int i;
   iOb = 100;
   System.out.println("Original value of iOb: " + iOb);
   ++iOb;
   System.out.println("After ++iOb: " + iOb);
   iOb2 = iOb + (iOb / 3);
   System.out.println("iOb2 after expression: " + iOb2);
   i = iOb + (iOb / 3);
   System.out.println("i after expression: " + i);
 }

}

 </source>
   
  
 
  



Autoboxing/unboxing takes place with method parameters and return values.

   <source lang="java">
 
  

class AutoBox2 {

 static int m(Integer v) {
   return v; // auto-unbox to int
 }
 public static void main(String args[]) {
   Integer iOb = m(100);
   System.out.println(iOb);
 }

}

 </source>
   
  
 
  



Autobox unbox a Boolean and Character.

   <source lang="java">

public class AutoBox5 {

 public static void main(String args[]) { 
   
   Boolean b = true; 

   // Below, b is auto-unboxed when used in  a conditional expression, such as an if. 
   if(b) 
       System.out.println("b is true"); 

   // Autobox/unbox a char. 
   Character ch = "x"; // box a char 
   char ch2 = ch; // unbox a char 

   System.out.println("ch2 is " + ch2); 
 } 

}


 </source>
   
  
 
  



Autobox unbox: convert

   <source lang="java">

public class AutoBox4 {

 public static void main(String args[]) { 
    
   Integer iOb = 100;; 
   Double dOb = 98.6; 


   dOb = dOb + iOb; 
   System.out.println("dOb after expression: " + dOb); 
 } 

}


 </source>
   
  
 
  



Autobox unbox occurs inside expressions.

   <source lang="java">

public class AutoBox3 {

 public static void main(String args[]) { 
    
   Integer iOb, iOb2; 
   int i; 

   iOb = 100; 
   System.out.println("Original value of iOb: " + iOb); 

   // The following automatically unboxes iOb, performs the increment, and then reboxes 
   // the result back into iOb. 
   ++iOb; 
   System.out.println("After ++iOb: " + iOb); 

   // Here, iOb is unboxed, the expression is evaluated, and the result is reboxed and 
   // assigned to iOb2. 
   iOb2 = iOb + (iOb / 3); 
   System.out.println("iOb2 after expression: " + iOb2); 

   // The same expression is evaluated, but the result is not reboxed. 
   i = iOb + (iOb / 3); 
   System.out.println("i after expression: " + i); 

 } 

}


 </source>
   
  
 
  



Autobox unbox takes place with method parameters and return values.

   <source lang="java">


public class AutoBox2 {

 // Take an Integer parameter and return an int value; 
 static int m(Integer v) { 
   return v ; // auto-unbox to int 
 }  

 public static void main(String args[]) {     
   // Pass an int to m() and assign the return value 
   // to an Integer.  Here, the argument 100 is autoboxed 
   // into an Integer.  The return value is also autoboxed into an Integer. 
   Integer iOb = m(100);  

   System.out.println(iOb); 
 } 

}


 </source>
   
  
 
  



Auto-unboxing allows you to mix different types of numeric objects in an expression.

   <source lang="java">
 

class AutoBox4 {

 public static void main(String args[]) {
   Integer iOb = 100;
   Double dOb = 98.6;
   dOb = dOb + iOb;
   System.out.println("dOb after expression: " + dOb);
 }

}

 </source>
   
  
 
  



Demonstrate autobox and unbox.

   <source lang="java">

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



Java Autobox and Unbox

   <source lang="java">

/* License for Java 1.5 "Tiger": A Developer"s Notebook

    (O"Reilly) example package

Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) by Brett McLaughlin and David Flanagan. ISBN: 0-596-00738-8 You can use the examples and the source code any way you want, but please include a reference to where it comes from if you use it in your own products or services. Also note that this software is provided by the author "as is", with no expressed or implied warranties. In no event shall the author be liable for any direct or indirect damages arising in any way out of the use of this software.

  • /

public class ConversionTester {

 public static void main(String[] args) {
   Integer i = 0;
   // Boxing
   int foo = 0;
   Integer integer = foo;
   // Simple Unboxing
   int bar = integer;
   Integer counter = 1;        // boxing
   int counter2 = counter;     // unboxing
   while (true) {
     System.out.printf("Iteration %d%n", counter++);
     if (counter > 1000) break;
   }
   Boolean case1 = true;
   Boolean case2 = true;
   boolean case3 = false;
   Boolean result = (case1 || case2) && case3;
   Integer i1 = 256;
   Integer i2 = 256;
   if (i1 == i2) System.out.println("Equal!");
   else System.out.println("Not equal!");
   Boolean arriving = false;
   Boolean late = true;
   System.out.println(arriving ? (late ? "It"s about time!" : "Hello!") : 
                                 (late ? "Better hurry!" : "Goodbye"));
   Integer peopleInRoom = 0;
   int maxCapacity = 100;
   boolean timeToLeave = false;
   while (peopleInRoom < maxCapacity) {
     if (arriving) {
       System.out.println("It"s good to see you.");
       peopleInRoom++;
     } else {
       peopleInRoom--;
     }
     if (timeToLeave) {
       do {
         System.out.printf("Hey, person %d, get out!%n", peopleInRoom);
         peopleInRoom--;
       } while (peopleInRoom > 0);
     }
   }
 }

}


 </source>
   
  
 
  



Type conversion (JDK1.5 Autoboxing/Unboxing)

   <source lang="java">

public class Main {

 public static void main(String... args) {
   Integer integer = 1; // int into Integer
   System.out.println(integer);
   int i = integer + 3; // mix Integer and ints
   System.out.println(i);
 }

}

 </source>
   
  
 
  



What is Autoboxing?

   <source lang="java">


import java.util.HashMap; import java.util.Map; public class Main {

 public static void main(String[] args) {
   Map<String, Integer> map = new HashMap<String, Integer>();
   map.put("Age", 25);
   int age = map.get("Age");
   Integer newAge = age + 10;
 }

}

 </source>