Вы находитесь на странице: 1из 11

Autoboxing and Unboxing in Java 5

Java 5 (and hence AspectJ 1.5) supports automatic conversion of primitive types (int,
float, double etc.) to their object equivalents (Integer, Float, Double,...) in
assignments and method and constructor invocations. This conversion is know as
autoboxing.
Java 5 also supports automatic unboxing, where wrapper types are automatically
converted into their primitive equivalents if needed for assignments or method or
constructor invocations.
For example:

int i = 0;
i = new Integer(5); // auto-unboxing

Integer i2 = 5; // autoboxing

Autoboxing And Unboxing in Java 5


23 April 2007

Java 5 supports automatic conversion of primitive types (int, float, double etc.) to their object
equivalents (Integer, Float, Double,…) in assignments, method and constructor invocations. This
conversion is know as autoboxing.
Java 5 also supports automatic unboxing, where wrapper types are automatically converted into
their primitive equivalents if needed for assignments or method or constructor invocations.For
example:
int inative = 0;

inative = new Integer(5); // auto-unboxing

Integer intObject = 5; // autoboxing


Before J2SE 5.0, we could not put primitive values like int, long, float, double, char etc. into
collections as they are not objects. Collections can hold object references, So we were required
to use wrapper classes.
Consider the following example: if we want to store an int “a” into vector “vt”, we have to use
wrapper class. And if we want to get element stored at position “0” of vector “vt”, we again have
to do casting.
int a = 10;

Vector vt = new Vector();

vt.add(new Integer(a));
int n = ((Integer)vt.elementAt(0)).intValue();
J2SE 5.0 has made this easy. If we want to do the same in Java 5, the code will be like:
int a = 10;

Vector <integer> vt = new Vector <integer> ();

vt.add(a);

int n = vt.elementAt(0); </integer></integer>


Before J2SE 5.0, Java had primtive data types with wrappers around them, So we had to convert
from one type to another manually
int a = 12;

Integer b = Integer.valueOf(a);

int c = b.intValue();
But now the life is easy. J2SE 1.5’s autoboxing/unboxing removes the pain of manual conversion
between primitives and wrappers. Ofcourse, the compiler creates code to implicitly create objects
for us.
int a = 12;

Integer b = a;

int c = b;
Auto-Boxing works also in comparisons (==, <, >, etc.). For instance you can compare int with
Integer.
int a = 10;

Integer b = 10;

System.out.println(a==b);

Output:

true
Few things to remember when using autoboxing/unboxing is that java compiler actually manages
type conversions for us. So boxing and unboxing too many values can make garbage collector go
wild. Hence it is not a advisable to use autoboxing and unboxing for scientific computing, or
other performance-sensitive numerical code as it will affect the performance to a good
extent.Using primitive types will better serve the purpose there.
Related Posts:
• No related posts

Top Of Page | Trackback


If you found this page useful, consider linking to it. Simply copy and paste the code below into
your web site.
It will look like this: Autoboxing And Unboxing in Java 5
<a href="http://w w w .java-tips.org/blog/java-se/autoboxing-and-unboxing-in-java-5.html">Autoboxing A nd Unboxing in Java 5</a>

2 Responses to “Autoboxing And Unboxing in Java 5”

1. On April 23rd, 2007 at 11:44 pm, Anjan Bacchu Says:

hi there,
nice post.
“remember when using autoboxing/unboxing is that java compiler actually manages type
conversions for us. So boxing and unboxing too many values can make garbage collector
go wild”
If the compiler were doing the task for us, why would the GC get involved ?
Thank you,
BR,
~A
2. On April 27th, 2007 at 6:09 am, editor Says:

Thanks for the comment. You might note that autoboxing will create objects ,other than
the natives in the earlier case. Whenever there are objects we cannot ignore Garbage
Collector. Look at an example given below. It reveals what I tried to say.
public class TestAutobox {
public int test;
//fields are public to skip compiler optimizations

public void autoboxmethod(Integer i) {


test = i;
}

public void nativemethod(int i) {


test = i;
}

public static void main(String[] args) {


TestAutobox autobox = new TestAutobox();

long startTime = System.currentTimeMillis();

for (int i = 0; i < Integer.MAX_VALUE; i++)


autobox.nativemethod(i);

long endTime = System.currentTimeMillis();


long result = endTime - startTime;
System.out.println("native ++++++++++++++++");
System.out.println("startTime : " + startTime);
System.out.println("endTime : " + endTime);
System.out.println("result : " + result);

startTime = System.currentTimeMillis();

for (int i = 0; i < Integer.MAX_VALUE; i++)


autobox.autoboxmethod(i);

endTime = System.currentTimeMillis();
result = endTime - startTime;

System.out.println("autobox ++++++++++++++++");
System.out.println("startTime : " + startTime);
System.out.println("endTime : " + endTime);
System.out.println("result : " + result);

}
OutPut is

native ++++++++++++++++
startTime : 1177645700505
endTime : 1177645715512
result : 15007
autobox ++++++++++++++++
startTime : 1177645715512
endTime : 1177645830339
result : 114827
The performance of Autoboxing depeds on the old trade-off between memory and speed.
Autoboxed values are frequently cached and reused. This appeals logical as the wrapper
objects are immutable. Look how the above programm outpur changes when I pass a
constant.
native ++++++++++++++++
startTime : 1177646390041
endTime : 1177646409836
result : 19795
autobox ++++++++++++++++
startTime : 1177646409836
endTime : 1177646483650
result : 73814

What is AutoBoxing and UnBoxing in java 5?


Conversion of primitive data types automatically to their corresponding wrapper classes is called
AutoBoxing and the reverse of this operation is called UnBoxing.

Ex:
Long L = new Long(100);
long x = L;

Now x will have a value 100.

What is enumeration?
Enumeration types are an essential ingredient in writing human readable source code. Due to
their special nature, special care must be taken when deciding how to use them and - even more
importantly - assessing implications of their use.
ex:- c++
enum myenum {white, black, red, green, blue, magenta, yellow, cyan };
the default value attached is {0,1,2,3,4,5,6,7}
niv

Java native method


The Java native method is a great way to gain and merge the power of C or C++ programming
into Java. To use Java as a scientific and high performance language, when efficient native Java
compilers are not fully implemented, use native method can boost the performance to at least the
speed of C compiled code.
Example 2. Example showing how Java native method works.
JMPI.java :
public class JMPI {
public native int Init(String[] args);
public native int Finalize();
static {
System.loadLibrary("JMPI");
}
}

JMPI.h : (created by javah and JMPI.class)


/* DO NOT EDIT THIS FILE - it is machine generated */
#include <native.h>
/* Header for class JMPI */

#ifndef _Included_JMPI
#define _Included_JMPI

typedef struct ClassJMPI {


char PAD; /* ANSI C requires structures to have a least one member
*/
} ClassJMPI;
HandleTo(JMPI);

#ifdef __cplusplus
extern "C" {
#endif
struct Hjava_lang_String;
extern long JMPI_Init(struct HJMPI *,HArrayOfString *);
extern long JMPI_Finalize(struct HJMPI *);
#ifdef __cplusplus
}
#endif
#endif

JMPI.c : (created by javah -stub and JMPI.class)


/* DO NOT EDIT THIS FILE - it is machine generated */
#include <StubPreamble.h>

/* Stubs for class JMPI */


/* SYMBOL: "JMPI/Init([Ljava/lang/String;)I", Java_JMPI_Init_stub */
stack_item *Java_JMPI_Init_stub(stack_item *_P_,struct execenv *_EE_) {
extern long JMPI_Init(void *,void *);
_P_[0].i = JMPI_Init(_P_[0].p,((_P_[1].p)));
return _P_ + 1;
}
/* SYMBOL: "JMPI/Finalize()I", Java_JMPI_Finalize_stub */
stack_item *Java_JMPI_Finalize_stub(stack_item *_P_,struct execenv
*_EE_) {
extern long JMPI_Finalize(void *);
_P_[0].i = JMPI_Finalize(_P_[0].p);
return _P_ + 1;
}

JMPINative.c :
#include "mpi.h"
#include "JMPI.h"
#include "stdlib.h"

long JMPI_Init(struct HJMPI *this, HArrayOfString *args) {


int i, result, len;
char** sargs;
HString **data = unhand(args)->body;
len = obj_length(args);
sargs = (char**)calloc(len, sizeof(char*));
for (i=0; i<len; i++) {
sargs[i] = allocCString(data[i]);
}
result = MPI_Init(&len, &sargs);
for (i=0; i<len; i++) free(sargs[i]);
free(sargs);
return result;
}

long JMPI_Finalize(struct HJMPI *this) {


return MPI_Finalize();
}
The only programs user created are JMPI.java and JMPINative.c. The JMPI.h and
JMPI.c are generated by javah and compiled JMPI.class files. Compile the JMPI.c
and JMPINative.c into libJMPI.so (in UNIX) or JMPI.dll (in Microsoft Windows) and
you are done.

Declaring Native Methods


This page shows you how to declare a native method in Java and how to generate
the C/C++ function prototype.

The Java Side

Our first example, Prompt.java, contains a native method that takes and prints a Java string,
waits for user input, and then returns the line that the user typed in.
The Java class Prompt contains a main method which is used to invoke the program. In addition,
there is a getLine native method:
private native String getLine(String prompt);
Notice that the declarations for native methods are almost identical to the declarations for
regular, non-native Java methods. There are two differences. Native methods must have the
native keyword. The native keyword informs the Java compiler that the implementation for
this method is provided in another language. Also, the native method declaration is terminated
with a semicolon, the statement terminator symbol, because there are no implementations for
native methods in the Java class file.
The Native Language Side
You must declare and implement native methods in a native language, such as C or
C++. Before you do this, it is helpful to generate the header file that contains the
function prototype for the native method implementation.

First, compile the Prompt.java file and then generate the .h file. Compile the Prompt.java file
as follows:
javac Prompt.java
Once you have successfully compiled Prompt.java and have created the Prompt.class file,
you can generate a JNI-style header file by specifying a -jni option to javah:
javah -jni Prompt
Examine the Prompt.h file. Note the function prototype for the native method getLine that you
declared in Prompt.java.
JNIEXPORT jstring JNICALL
Java_Prompt_getLine(JNIEnv *, jobject, jstring);
The native method function definition in the implementation code must match the generated
function prototype in the header file. Always include JNIEXPORT and JNICALL in your native
method function prototypes. JNIEXPORT and JNICALL ensure that the source code compiles on
platforms such as Win32 that require special keywords for functions exported from dynamic link
libraries.
Native method names are concatenated from the following components:
• the prefix Java_
• the fully qualified class name
• an underscore "_" separator
• the method name
(Note that overloaded native method names, in addition to the above components, have extra two
underscores "__" appended to the method name followed by the argument signature.)
As a result, the Prompt.getLine method is implemented by Java_Prompt_getLine in native
code. (There is no package name component because the Prompt class is in the default package.)
Each native method has two additional parameters, in addition to any parameters that you declare
on the Java side. The first parameter, JNIEnv *, is the JNI interface pointer. This interface
pointer is organized as a function table, with every JNI function at a known table entry. Your
native method invokes specific JNI functions to access Java objects through the JNIEnv *
pointer. The jobject parameter is a reference to the object itself (it is like the this pointer in
C++).
What is the difference between Abstract class and Interface

Answered by Scott on 2005-05-12 10:03:06: An abstract class can contain non-abstract


methods which do not have to be overridden in the subclass.

There is no difference between a fully abstract class (all methods declared as abstract and
all fields are public static final) and an interface.

A class implementing an interface must implement all of the methods defined


in the interface while a class extending an abstract class need not implement
any of the methods defined in the abstract class. Additionally a class extending
an abstract class can implement an infinite number of it's own methods.
another key difference between abstract class and interface is that in abstract class we can
put sharable code but that is not possible in case of interface.
Another key difference between abstract class and interface is that
We can use interface as marker ( we can use abstract class also as abstract but then we
can't extends any oter class so it is better always use interface as marker)
Abstract class does not support Multiple Inheritance . Interface supports
Multiple Inheriatnce..
The differnce is that in interface all are public but in abstract class u can have
private and protected members

What is the difference between static and non-static


variables
A static variable is associated with the class as a whole rather than with specific instancesof
a class. Non-static variables take on unique values with each object instance.

Instance variables can be accessed only by the Instance methods only.

Static variables can be accessed by any method(static or Instance methods)

Static variables belongs to class only they have no relation to object. They
allocate memory when class is loaded at run time. That's why we can call them
by the name of class variables.
Non-static variables belongs to object. They allocate memory at compile time.

Static variables:
There is only one copy of static variable and even
when the class is instatiated, the value remains the same.

Non-static variables:
Every time the class is instatiated, the objest has
their own copy of these variables.

static variables are class variables and the values remains


same fr the whole class
nonstatic variables are of two kinds
global variables:are the variables which defines variables
which can be accesible over the whole class
local variables:the scope of local variables is with tin
the method only

Refer to the Current Instance of an Object


(Visual Basic)
The current instance of an object is the instance in which the code is currently executing.
You use the Me keyword to refer to the current instance.
To refer to the current instance

• Use the Me keyword where you would normally use the name of an object variable.
Copy

Me.ForeColor = System.Drawing.Color.Crimson

Me.Close()

Although Me behaves like an object variable, you cannot declare it or assign anything to
it. Me always refers to the current instance.

Inner classes

Believe it or not, there are advantages to Java's inner classes. But before we go into that, I'll
provide a short background on inner classes.

Inner classes nest within other classes. A normal class is a direct member of a package, a
top-level class. Inner classes, which became available with Java 1.1, come in four flavors:
• Static member classes
• Member classes
• Local classes
• Anonymous classes

Let's take a quick look at each in turn.

Briefly, a static member class is a static member of a class. Like any other static method, a
static member class has access to all static methods of the parent, or top-level, class.

Like a static member class, a member class is also defined as a member of a class. Unlike
the static variety, the member class is instance specific and has access to any and all
methods and members, even the parent's this reference.

Local classes are declared within a block of code and are visible only within that block, just
as any other method variable.

Finally, an anonymous class is a local class that has no name.

To answer your specific question, I'll focus on the member and anonymous inner classes
since those are the ones you'll likely encounter and use. To me, the advantages of inner
classes can be divided into three categories: an object-oriented advantage, an
organizational advantage, and a call-back advantage.
JIT
Short for just-in-time compiler, a code generator that converts Java bytecode into
machine language instructions. Some Java Virtual Machines (VMs), including the VM
in the Netscape Navigator browser, include a JIT in addition to a Java interpreter.

Java programs compiled by a JIT generally run much faster than when the
bytecode is executed by an interpreter.

In computing, just-in-time compilation (JIT), also known as dynamic translation, is a method


to improve the runtime performance of computer programs. Traditionally, computer programs
had two modes of runtime operation, either interpreted or static (ahead-of-time) compilation.
[citation needed]
Interpreted code is translated from a high-level language to a machine code
continuously during every execution, whereas statically compiled code is translated into machine
code before execution, and only requires this translation once.
JIT compilers represent a hybrid approach, with translation occurring continuously, as with
interpreters, but with caching of translated code to minimize performance degradation. It also
offers other advantages over statically compiled code at development time, such as handling of
late-bound data types and the ability to enforce security guarantees.
JIT builds upon two earlier ideas in run-time environments: bytecode compilation and dynamic
compilation. It converts code at runtime prior to executing it natively, for example bytecode into
native machine code.
Several modern runtime environments, such as Microsoft's .NET Framework and most
implementations of Java, rely on JIT compilation for high-speed code execution.

Вам также может понравиться