Why to use wrapper class?

hello,
can anybody please tell me why wrapper class are used in JAVA and what are exactly wrapper class?
reply me soon....

I want to give an example and then explain why it is for. Primitives will be good example for this situation.
Example:
Below are the primitive types and their wrapper classes...
Primitive to Wrapper Class
byte - Byte
short - Short
int - Integer
long - Long
char - Character
float - Float
double - Double
boolean - Boolean
USING OBJECT CREATION
Think a situation when you create an integer object using this code:
---> Integer intVar = new Integer();
you have the methods and constants:
1 MAX_VALUE ,
2 MIN_VALUE ,
3 byteValue() ,
4 compareTo(Integer anotherInteger) ,
5 compareTo(Object o) ,
6 decode(String nm) ,
7 doubleValue() ,
8 equals(Object obj) ,
9 floatValue() ,
10 getInteger(String nm) ,
11 getInteger(String nm, int val) ,
12 getInteger(String nm, Integer val) ,
13 hashCode() ,
14 intValue() ,
15 longValue() ,
16 parseInt(String s) ,
17 parseInt(String s, int radix) ,
18 shortValue() ,
19 toBinaryString(int i) ,
20 toHexString(int i) ,
21 toOctalString(int i) ,
22 toString(),
23 toString(int i) ,
24 toString(int i, int radix) ,
25 valueOf(String s) ,
26 valueOf(String s, int radix)
now you have an object with 2 constants and 24 methods.
USING WRAPPER CLASS
and think using wrapper class of Integer..
CODE ---> int intVar = Integer.parseInt((String)someStringData);
In this case your Integer object have the methods and constants
1 MAX_VALUE ,
2 MIN_VALUE ,
3 parseInt(String s) ,
4 parseInt(String s, int radix) ,
5 toBinaryString(int i) ,
6 toHexString(int i) ,
7 toOctalString(int i) ,
8 toString(int i) ,
9 toString(int i, int radix) ,
10 valueOf(String s) ,
11 valueOf(String s, int radix)
as you in this situation you have 2 constants and 9 methods.
AS YOU SEE THERE ARE 15 METHODS DIFFERENCE FROM THE OBJECT AND THE WRAPPER CLASS OF INTEGER OBJECT.
NOW TALKING ABOUT PRIMITIVE TYPES ALL PROGRAMMERS USED THIS TYPES FOR THEIR CODES AND THEY ALWAYS NEED SOME THIS KIND OF CASTING. IN MY EXAMPLE I TAKE THE VALUE OF AN STRING VARIABLE. AND THERE ARE LOTS OF THINGS SIMILIAR TO THIS EXAMPLE.
IDEA OF THIS WRAPPER CLASSES IS THAT USE AS YOU NEED NOTHING MORE. IN THE WRAPPER CLASS YOU DONT HAVE INTEGER OBJECT. YOU ONLY NEED THE PARSEINT METHOD OF INTEGER OBJECT INSTEAD OF CREATING THE INTEGER OBJECT YOU USE THE WRAPPER CLASS OF THIS TYPE...
OBJECTS ARE STORED IN A MEMORY PLACE CALLED HEAP WHICH IS PLACED ON RAM AND GARBAGING OF THIS OBJECTS TAKES MORE TIME TO ALLOCATE FROM HEAP STORAGE.
AND ANOTHER NOTE FOR THIS WRAPPER CLASSES if you want to store an int inside a container such as an ArrayList (which takes only Object references), you can wrap your int inside the standard library Integer class
EX:
import java.util.*;
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?
} ///:~
GOOD LUCK...
REALKINGTA....

Similar Messages

  • What is the advantage of using Wrapper Classes ?

    Hi friends,
    I am happy to join Java/J2EE tech. My project is scaled over the network. MVC-II struts, EJB based architecture, we are using.
    We are asked to use Wrapper Classes in in Java programs and not the primitive data types. I could not understand the reason.
    Pls tell me what is the advantage of using Wrapper Classes over the primitive data types ?
    means Integer instead of int, etc....

    Hi friends,
    I am happy to join Java/J2EE tech. My project is
    scaled over the network. MVC-II struts, EJB based
    architecture, we are using.
    We are asked to use Wrapper Classes in in Java
    programs and not the primitive data types. I could
    not understand the reason.
    Pls tell me what is the advantage of using Wrapper
    Classes over the primitive data types ?
    means Integer instead of int, etc....I am not sure why use Integer over int; but Wrapper classes are used to remove coupling between classes and create one hand doesn't know what the other hand does effect.
    for example:
    when you have a SFTP java package but doesn't do everything that your application needs to do in one step and you need to do sftp stuff at many places in your application, it would be wise not to use SFTP java package directly from all the classes that need to do sftp stuff. Because if you were to change the SFTP package later due to say some bug fix or newer version or ... you would have to go and modify all the classes that had sftp stuff to update.
    Instead you could write a custom sftp wrapper that handles all the sftp stuff for your application needs and that wrapper deals with the SFTP java package. So all the classes don't need to know which SFTP java package is being used only the custom-wrapper needs to know.

  • Help,about why we use inner class?

    Hi,
    when i read "java Tutorial"
    i found there is one chapter about inner class .
    i copy it down as follow.
    the context is about there is a class Stack, and this class want to implement some function of interface Iterator,but as the book said
    we should not let class Stack implement the Iterator directly, we should add a inner class inside the Stack .
    i know it's very import ,but i still can not understand the reason why add a inner class here.
    hope somebody can explain it a little more for me or give an example.
    thank in advance!
    Iterator defines the interface for stepping once through the elements within an ordered set in order. You use it like this:
    while (hasNext()) {
    next();
    The Stack class itself should not implement the Iterator interface, because of certain limitations imposed by the API of the Iterator interface: two separate objects could not enumerate the items in the Stack concurrently, because there's no way of knowing who's calling the next method; the enumeration could not be restarted, because the Iterator interface doesn't have methods to support that; and the enumeration could be invoked only once, because the Iterator interface doesn't have methods for going back to the beginning. Instead, a helper class should do the work for Stack.
    The helper class must have access to the Stack's elements and also must be able to access them directly because the Stack's public interface supports only LIFO access. This is where inner classes come in.
    Here's a Stack implementation that defines a helper class, called StackIterator, for enumerating the stack's elements:
    public class Stack {
    private Object[] items;
    //code for Stack's methods and constructors
    not shown
    public Iterator iterator() {
    return new StackIterator();
    class StackIterator implements Iterator {
    int currentItem = items.size() - 1;
    public boolean hasNext() {
    public Object next() {
    public void remove() {
    or you can visit here
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

    the context is about there is a class Stack, and this
    class want to implement some function of interface
    Iterator,but as the book said
    we should not let class Stack implement the Iterator
    directly, we should add a inner class inside the
    Stack .Simply because the implementation of the Iterator is nobody's business. By declaring it to be a private inner clss, nobody will ever know about it and only see the Iterator interface.

  • How to keep track of status using wrapper class?

    Hi,
    I got the following code on the server side:
    ..........//this method invocation may take a long time to do
    Object methodResult = method.invoke(object, args);
    if (methodResult != null) //method invocation return results
          //convert the methodResult Object into JDOM Element   
         ObjectWriter writer = new SimpleWriter();  
         Element element = writer.write(methodResult); 
         //return result to client--------------------------------------------------------  
         //Results tag to notify incoming result from method invocation on next incoming byte  
         out.println("Results"); 
         //convert the element into String  
        String strXML = Util.convertXMLtoString(element);  
        //send the String xml out to the client. The client will receive the string representation of the xml  
        out.println("strXML):        
    else //there are no results return from method invocation
        //save the result into xml file  
        Util.createFile(element, new File(filename));
    .......................The problem is how to I keep track of the status of the method invocation.
    As can be seen from the above code, Object methodResult = method.invoke(object, args);
    the method invocation will take a long time!
    How do I write a wrapper class to keep track of the status of the method invocation that can be check by the client? I am thinking of using a url to keep track of method invocation so that the client can continously poll the wrapper object to check if the method invocation has finished.
    Can anyone change my code and give advice?
    Thanks a lot!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    No,
    I am not using Java threads at all.
    I just need to keep track of the status of the method invocation and report to the client.
    Sometimes, the method invocation can take ages so it is not acceptable for the client to invoke a method and wait a long time without any response: but in fact the server is still in the process of executing the method.
    Please advice.

  • Java Wrapper Classes are immutable?

    Hi guys,
    The one artichle i have read it says wrapper classes are immutable and once you assign a value to a variable(wrapper class type) you wont be able to change that value ,also ;
    Integer myInt=new Integer(5);
    myInt=10;//i change it no problem showed up.also why it says wrapper classes are immutable?
    //how the java works at the background and change it for us what methods does it use to change the value?
    //why java made wrapper classes as immutable?Thanks.

    Garibanus wrote:
    Hi guys,
    The one artichle i have read it says wrapper classes are immutableAnd it was correct in saying that.
    and once you assign a value to a variable(wrapper class type) you wont be able to change that valueThat has nothing to do with imutability. If the article said that, it's wrong. If it said that assigning a reference variable to point to an object has anything to do with that object's imutability, it was wrong.
    Immutability has to do with the state of an object, not with references that point to it.

  • Wrapper class for HashMap

    Why people write Wrapper class for HashMap? Why not directly use the HashMap?

    I thought that the term wrapper class is generally
    used to signify one class having an instance of
    another class inside it. And not one class
    deriving from another.
    But thats just me.I think that is just you. :)
    I consider "wrapping" as having a subset of the functionality of another class. This could be containing or extending, in my opinion.
    Consider:
    // only partially functional vector for JButtons...
    // class containing Vector
    public class JButtonVector
      Vector vec = new Vector();
      public void add(JButton button)
        vec.add(button);
      public JButton get(int index)
        if(index >= vec.size() || index < 0)
          throw new IllegalArgumentException(...);
        return (JButton)vec.get(index);
    // class extending Vector
    class JButtonVector2 extends Vector
      public void add(JButton but)
        super.add(but);
      public JButton get(int index)
        return (JButton)(super.get(index));
    }Problem with the second class is that it also allows adding of regular Objects. That might not be desirable (in this case, it is definitely not).

  • What are the uses of Void wrapper class?

    Hi,
    Similar to other Wrappers, Void is a wrapper class for the primitive ' void ' . We all know that Void is a final class , we can't instantiate it.
    My Question is what are the uses of Void?
    thanks,

    kajbj wrote:
    I have at times used it in reflection and jmx.I have used them with SwingWorker if I didn't have anything interesting to return. There is also an example in the tutorial: [http://java.sun.com/docs/books/tutorial/uiswing/concurrency/simple.html]

  • Why use abstract classes?

    Why should I use abstract classes instead of a regular class with empty method bodies? Just better design? Is there some logical or performance based reason?

    Why should I use abstract classes instead of aregular
    class with empty method bodies? Just better design?Is
    there some logical or performance based reason?Because it describes what you're doing.
    If you define a "regular" class with empty message
    bodies, everyone who looks at it will say "WTF is he
    trying to do" or, if they're charitable, "Look,
    Harvey, someone who's trying to make Java look just
    like C++!".
    sigh Maybe answers like THIS are why people keep asking the same question.
    Here's a couple things an abstract class does that a "regular" class with empty methods bodies doesn't:
    1) An abstract class cannot be instantiated.
    2) An abstract class forces it's abstract methods to be implemented.
    If you were to extend a non-abstract class with empty method bodies, you wouldn't have to override the methods... you could just leave them empty. An abstract class forces it.
    There's a lot more reasons... those are a couple obvious ones.

  • Why use Factory classes

    Why do we use Factory classes such BorderFactory, to get an instance of Border class, why cant we directly create an object of such classes like we do with regular concrete classes

    Why do we use Factory classes such BorderFactory, to
    get an instance of Border class, why cant we directly
    create an object of such classes like we do with
    regular concrete classesFactory methods (I mean static create methods here) have two advantages.
    First, the library designer doesn't have to expose concrete classes to the outside world, just interfaces. This adds flexibility.
    Second, the library designer is free to make object creations more flexible. The create method may take parameters that doesn't exactly correspond to a constructor of one specific class.

  • Why Use Nested Classes

    Hi All,
    Why do we use Nested Classes ? Explain it with example ....
    If we say - It is a way of logically grouping classes that are only used in one place. Then we can say we use it through "Package" so why inner class ??
    Thanks in advance ....

    A real life example to jschell's explaination may be this.
    The pistons in your automobile engine are encapsulated by the engine block -- or the engine block encapsulates the pistons inside. This is the desired effect because as soon as we take the pistons out of the engine block, and put them say, in the backseat of the car instead, they no longer perform the function they were intended. There is another side effect to this analogy. When the pistons are properly installed in the engine block, there is only one movement the pistons can move -- up and down movement, that's it... they cannot rotate, spin, twist around or anything inside the engin block. Furthermore, the up and down movement is the only useful thing a piston can do. As soon as we throw the pistons in the backseat of the car, they can roll around, spin, and generally rotate to any configuration or orientation -- which does not produce any useful power.
    Inner classes are generally the same way. So we can see this example with a little code -- which we like.
    public class Engine
      Piston[] pistons = new Piston[8];
      class Piston
        // the usual methods here..
    }Of course, if your program is extremely sohisticated, this may not be a good solution -- for example, if you are making a catalog of automotive parts, then you would probably want your <tt>Piston</tt> class to be stand-alone.
    Edited by: pierrot_2. Also notice that the class <tt>Piston</tt> is not an INNER class of Backseat!

  • What are Wrapper classes and what are they used for ?

    What are Wrappter classes and what are they used for ?..Also, any examples would be great to understand this concept

    Wrapper classes are used to enclose primitive data
    types so that they can be used in instances where an
    object is required. For example, if you want to add an
    integer to an ArrayList, you can't use this:java.util.List al = new ArrayList();
    int i=123;
    al.add(i);because the ArrayList expects data of type object. In
    order to all the integer to the ArrayList, you must wrap
    it in the Integer wrapper class. This works:java.util.List al = new ArrayList();
    int i=123;
    al.add(new Integer(i));Hope that helps.
    Mark

  • Why are we using Abstract class?

    Why are we using Abstract class? What is specify use of Abstract class?

    The way I understand it....and I may be wrong because
    I am very new....is that by making the class abstract
    you will add abstract methods to it. Those abstract
    methods MUST be defined in in any subclass that
    inherits from the abstract class thereby making the
    abstract a template for subclasses.
    If your animal class is abstract then you would need
    an abstract method (Which is just siganture, no body)
    of say "numberOfLegs". Then in your dog and cat
    classes which extend animal you must define a
    "numberOfLegs" method with appropriate code.it isn't mandatory for an abstract class to have abstract methods. if a class does have abstract methods, the class must be abstract. but the following is perfectly legal
    public abstract class NoAbstractMethods {
      public void doStuff() {
         // do stuff
    }a subclass of an abstract class can also be abstract, and as such need not implement any additional methods

  • Advantages,Dis-advantages,when and where -use java.lang.Void Wrapper  class

    Hi All,
    I like to know when and where to use the wrapper class java.lang.Void and when it is particulary needed.if anyone could give me some examples it will be better.
    Thanks in advance,
    Kathir

    I like to know when and where to use the wrapper class java.lang.VoidWhy? If you don't need it, you don't have to use it.
    and when it is particulary needed.It is needed when you want to represent the concept of a void return value.
    if anyone could give me some examples it will be better.
    Method wait = Object.class.getMethod("wait",null);
    if (wait.getReturnType() == Void.TYPE) {
      System.out.println("Object.wait() returns null");
    }

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Why JSP not use new class that I compile again?

    I use bean class with JSP. But When I add some code and compile new bean. JSP not use new been class it use old class.
    I try to set file server.xml and set <DefaultContext reloadable="true"/> and restart Tomcat. But it not work?
    any help please?

    I run JSP in http://localhost:8080/stringbean.jsp
    is context name mean localhost
    in c:\tomcat\work has following directory
    standalone (level1 dir)
    localhost (level2 dir)
    - (level3 dir)
    examples (level3 dir)
    manager (level3 dir)
    tomcat-doc (level3 dir)
    webdav (level3 dir)

Maybe you are looking for

  • How to control timeline sound of external SWF

    Hi All, Basic Intro: I am new in Action Script and trying to create a video tutorial framwork. In this I have lots of animated SWF files in all the files I have multiple scenes as those are 5min. to 10 min. each and all the files have the relevent ba

  • Print comments

    I just installed Reader 8.1.2. I have a document with comments (sticky notes and other) that I cannot print. Help says to go to Preferences and then to Commenting but I have no Commenting in my Preference. Can anyone help?

  • How to use the latest jdbc driver in weblogic61beta?

    weblogic61 comes with mssqlserver4v65.jar, currently the latest jdbc driver is mssqlserver4v70sp10 but seems the license and directory structure is only for weblogic51. I tried to use it for weblogic61beta, but it failed. please advice. thanks

  • Rotation doesn't preview in CC

    Hi All, I cant seem to get the rotate CSS transform to preview in DreamWeaver. It shows in IE11 but not many browsers seem to support rotate yet. cheers Roen

  • How do you open Jpeg 2000 files in CS4

    I am using PS CS4 on a virtual windows. I don't think that should matter. But I cannot open the jpeg 2000 or jpf 2000 files. Please advise. Do I have to buy software/plugin to do this? DVO