Wrapper classes/ instance variables&methods

can anyone provide me additional information on the wrapper classes.
In addition, could someone please provide an explination of the- instance and class (variables+methods)

Every primitive class has a wrapper class e.g.
int - Integer
float - Float
long - Long
char - Character
etc. When a primitive is wrapped it becomes an object and immutable. Primitives are generally wrapped (either to make them immutable) or to be able to add them to the collections framework(sets, maps, lists which can only take objects, not primitives).
An instance variable is a variable that each copy of the object you create contains, as is an instance method. Each instance you create (each copy of the object) contains its own copy of the variable and method.
A class variable and method means that no matter how many objects you create, there will be one and only one copy of the variable and method.
Hope this helps. Also see the java tutorial.

Similar Messages

  • Binding a JavaFX variable to a Java class instance variable

    Hi,
    I am pretty new to JavaFX but have been developing in Java for many years. I am trying to develop a JavaFX webservice client. What I am doing is creating a basic scene that displays the data values that I am polling with a Java class that extends Thread. The Java class is reading temperature and voltage from a remote server and storing the response in an instance variable. I would like to bind a JavaFx variable to the Java class instance variable so that I can display the values whenever they change.
    var conn: WebserviceConnection; // Java class that extends Thread
    var response: WebserviceResponse;
    try {
    conn = new WebserviceConnection("some_url");
    conn.start();
    Thread.sleep(10000);
    } catch (e:Exception) {
    e.printStackTrace();
    def bindTemp = bind conn.getResponse().getTemperature();
    def bindVolt = bind conn.getResponse().getVoltage();
    The WebserviceConnection class is opening a socket connection and reading some data in a separate thread. A regular socket connection is used because the server is not using HTTP.
    When I run the application, the bindTemp and bindVolt are not updated whenever new data values are received.
    Am I missing something with how bind works? Can I do what I want to do with 'bind'. I basically want to run a separate thread to retrieve data and want my UI to be updated when the data changes.
    Is there a better way to do this than the way I am trying to do it?
    Thanks for any help in advance.
    -Richard

    Hi,
    If you don't want to constantly poll for value change, you can use the observer design pattern, but you need to modify the classes that serve the values to javafx.
    Heres a simple example:
    The Thread which updates a value in every second:
    // TimeServer.java
    public class TimeServer extends Thread {
        private boolean interrupted = false;
        public ValueObject valueObject = new ValueObject();
        @Override
        public void run() {
            while (!interrupted) {
                try {
                    valueObject.setValue(Long.toString(System.currentTimeMillis()));
                    sleep(1000);
                } catch (InterruptedException ex) {
                    interrupted = true;
    }The ValueObject class which contains the values we want to bind in javafx:
    // ValueObject.java
    import java.util.Observable;
    public class ValueObject extends Observable {
        private String value;
        public String getValue() {
            return this.value;
        public void setValue(String value) {
            this.value = value;
            fireNotify();
        private void fireNotify() {
            setChanged();
            notifyObservers();
    }We also need an adapter class in JFX so we can use bind:
    // ValueObjectAdapter.fx
    import java.util.Observer;
    import java.util.Observable;
    public class ValueObjectAdapter extends Observer {
        public-read var value : String;
        public var valueObject : ValueObject
            on replace { valueObject.addObserver(this)}
        override function update(observable: Observable, arg: Object) {
             // We need to run every code in the JFX EDT
             // do not change if the update method can be called outside the Event Dispatch Thread!
             FX.deferAction(
                 function(): Void {
                    value = valueObject.getValue();
    }And finally the main JFX code which displays the canging value:
    // Main.fx
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.text.Text;
    import javafx.scene.text.Font;
    import threadbindfx.TimeServer;
    var timeServer : TimeServer;
    var valueObjectAdapter : ValueObjectAdapter = new ValueObjectAdapter();
    timeServer = new TimeServer();
    valueObjectAdapter.valueObject = timeServer.valueObject;
    timeServer.start();
    Stage {
        title: "Time Application"
        width: 250
        height: 80
        scene: Scene {
            content: Text {
                font : Font {
                    size : 24
                x : 10, y : 30
                content: bind valueObjectAdapter.value;
    }This approach uses less cpu time than constant polling, and changes aren't dependent on the polling interval.
    However this cannot be applied to code which you cannot change obviously.
    I hope this helps.

  • Sub class will allocate seperate memory for super class  instance variable?

    class A
    int i, j;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    class B extends A
    int k;
    void showij()
    System.out.println("i and j: " + i + " " + j);
    what is size of class B will it be just 4 byte for k or 12 bytes for i, j and k ?
    will be a seperate copy of i and j in B or address is same ?
    thank u

    amit.khosla wrote:
    just to add on...if you create seprate objects of A and B, so the addresses will be different. We cant inherit objects, we inherit classes. It means if you have an object of A and another object of B, they are totally different objects in terms of state they are into. They can share same value, but its not compulsary that they will share same values of i &j.
    Extending A means to making a new class which already have properties & behaviour of A.
    Hope this help.That is very unclear.
    If you create two objects, there will be two "addresses", and two sets of member variables.
    If you create one object, there will be one "address", and one complete set of non-static member variables that is the union of all non-static member variables declared in the class and all its ancestor classes.

  • Not able to access parent instance variable in outside of methods in child

    Hi,
    I am not getting why i am not able to access parent class instance variable outside the child class intance methods.
    class Parent
         int a;
    class Child extends Parent
         a = 1; // Here i am getting a compilation error that Syntax error on token "a", VariableDeclaratorId expected after this token
         void someMethod()
              a = 1;  // Here i am not getting any compilation error while accessing parent class variable
    }Can any one please let me know exact reason for this and what is the error talks about?
    Thanks,
    Uday
    Edited by: Udaya Shankara Gandhi on Jun 13, 2012 3:30 AM

    You can only put assignments or expressions inside methods, constructors or class initializors, or when declaring a variable.
    It has nothing to the with Child extending Parent.
    class Parent {
        int a = 1;
        { a = 1; }
        public Parent() {
            a = 1;
       public void method() {
           a = 1;
    }

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Binding: Instance variable loses value.

    Hi all,
    Just making my first steps into Objective-C, I've done a lot of C, C++ and C# on win & linux. Anyhow, I've been hacking away happily and discovered a peculiar behaviour, and I'm not sure if it's my code or some obscure bug in Xcode.
    1. I have a Check Box(NSButton) directly bound to a BOOL instance variable called "checkValue" using KVC. The containing class is a custom NSView subclass.
    2. I manually implemented the setter according to KVC naming rules "setCheckValue".
    3. When debugging the UI (check box) calls the setter perfectly with the correct value, which shows up in the NSLog output.
    4. I hooked up the action for the check box as well, and inside the action handler the instance variable reports the value correctly. Everything looks fine.
    5. Now here's the rub. I put a mousedown event handler into the class as well, and it is called flawlessly when I click on the custom view. However, "checkValue" does not report the correctly set value.
    So, how can a class instance variable, which is set and reports correctly elsewhere in the same scope, all of the sudden take on a nonsense value in a event handler? If a variable has a value set, it should be the same everywhere within the same scope!
    Below is simplified code extracted from the original project for clarity. It produces exactly the same behaviour as the more complex project without the distracting code.
    #import "CheckBoxHandler.h"
    @implementation CheckBoxHandler
    @synthesize checkValue;
    //Apparently this is required for binding in NSView based classes
    //The same behaviour occurs even if you remove this.
    +(void)initialize
    [self exposeBinding:@"checkValue"];
    -(id)initWithFrame:(NSRect)frameRect
    self = [super initWithFrame:frameRect];
    if(!self)
    return nil;
    [self setCheckValue:YES];
    return self;
    //manual impelementation of KVC setter
    -(void)setCheckValue:(BOOL)v
    checkValue = v;
    NSLog(@"Setter Called: checkValue is %d", checkValue);
    //The action works fine as evidenced by Log output
    //Check and uncheck the box a few times.
    -(IBAction)checkBoxAction:(id)sender
    NSLog(@"UI State:%d Ivar State: %d", [checkBox state], checkValue);
    //Mouse clicking on the view calls into this event.
    //The problem is the value reported by [self checkValue] OR checkValue directly
    //do not match the UI state. In fact it always reports some nonsense value.
    -(void)mouseDown:(NSEvent *)event
    NSLog(@"Inside Mousedown: checkValue is: %d", [self checkValue]);
    @end
    I have a workaround, but it really bends my head when something doesn't behave as expected!

    I have synthesized against "checkValue", although I manually implemented the setter so I could set a breakpoint and observe the value. I thought [self checkValue] and self.checkValue both simply call the same getter, just different syntax.
    The setting of the value using the UI checkbox happens outside of the event call chain. I can check and uncheck the checkbox and the value changes correctly. The checkbox is in a separate space on the window, so clicking it does not activate mousedown on the view, this is correct behaviour. Clicking on the view does activate the mousedown event, this is done after I've set the checkbox so the value has been set well before the mousedown event. Thus it should already have the correct value in the event.
    For completeness this is the interface file:
    #import <Cocoa/Cocoa.h>
    @interface CheckBoxHandler : NSView {
    IBOutlet NSButton *checkBox;
    BOOL checkValue;
    -(IBAction)checkBoxAction:(id)sender;
    @property (assign, readwrite) BOOL checkValue;
    @end
    I'll change everything to self.checkValue just for the excercise. Ok, done. checkValue still reports a value of 1 in the mousedown event regardless of the value set elsewhere.

  • Inheritance - instance variable initialization

    Hi all.
    I have a question regarding inherited instance variables.
    class Animal {
       int weight;
       int age = 10;
    class Dog extends Animal {
       String name;
    class Test {
       public static void main(String[] args) {
          new Dog();
    }This is just an arbitrary code example.
    When new Dog() is invoked, I understand that it's instance variable "name" is give the default
    type value of null before Dog's default constructor's call to super() is invoked.But Im a little perplexed about
    Animals instance variables. I assume that like Dog, Animals instance variables are given their default type values
    of 0 & 0 respectively, before Animals invocation of super(); What im unclear about is that at the point that weight and age are given their default type values, are Dog's inherited weight and age variables set to 0 aswell at that exact moment? Or are Dog's inherited weight and age variables only assigned their values after Animals constructor fully completes because initialization values are only assigned to a classes instance variables after it's call to super().
    Many thanks & best regards.

    Boeing-737 wrote:
    calvino_ind wrote:
    Boeing-737 wrote:
    newark wrote:
    why not throw in some print statements and find out?Super() or this() have to be the very first statement in a constructor..
    Also you cannot access any instance variables until after super or this.
    :-S
    Kind regardsbut if you add the "print" statement in animal constructor, you can easily see what happened to the attributes of Dog ; that s the trick to print "before" super()You can never add a print before super(). It's a rule of thumb, super() and this() must always be the first statements
    in a constructor, whether added implicitly by the compiler or not. In this case there are 2 default constructors (inserted by the compiler), each with a super() invocation. Even if i added them myself and tried to print before super(), the compiler would complain.
    Thanks for the help & regards.you didn't understand what i meant ; take a look at that:
    class Animal {
       int weight;
       int age = 10;
       public Animal() {
           Dog thisAsADog = (Dog) this;
          System.out.println(thisAsADog.name);
          System.out.println(thisAsADog.x);
    class Dog extends Animal {
       String name;
       int x = 10;
    public class Test {
       public static void main(String[] args) {
          new Dog();
    }this way you will know what really does happen

  • Instance/Class Variables/Methods

    Can someone please give a CLEAR explanation on what is a Instance Variable, Instance Method, Class Variable, and Class Method? Thanks a lot!

    instance method and variable is one that requires an instance to be created before they can be used.
    Class method and variables don't need an instance. They have the static qualifier.
    For example
    public class Test {
        public String instanceVar;
        static public String classVar;
    }Now to use instanceVar you have to do this
    Test test = new Test();
    test.instanceVar = "";To use classVar
    Test.classVar = "";Another way of looking at it is that each instance of a class (created using new) has its own copy of instance variables.
    Multiple instances of a class however share the same copy of class variables.
    The same pretty much goes for methods.

  • Public instance variable vs. accessor method

    I know some OOP purists believe all instance variables should be private, and if there's a need to view or set the value of these instance variable, public accessor methods need to be created. Data encapsulation is the driving force behind this belief.
    But in Java, it's easy enough to declare an instance variable public thus eliminating the need to write accessor method. What's the rational behind this feature? Is it merely to save developer some time from typing in the accessor methods? Does this reason justify the use of public members?

    I know some OOP purists believe all instance variables
    should be private, ALL? No way!
    and if there's a need to view or
    set the value of these instance variable, public
    accessor methods need to be created. There has to be a reason for any :- public int getMyInt(){ ...
    and in many cases protected or default package is more appropriate
    Data
    encapsulation is the driving force behind this belief.
    Correct , also avoiding multiple instances of member states - very often its a control issue too
    But in Java, it's easy enough to declare an instance
    variable public Yes and its also easy enough to write shittie code too ...
    if an instance variable is public there should be a clear comment explaining why the field has to be public
    thus eliminating the need to write
    accessor method. There's nothing wrong with accessors and mutators - the java language is full if them
    What's the rational behind this
    feature? As you stated encapsulation
    Is it merely to save developer some time
    from typing in the accessor methods? This is a lame reason
    Does this reason
    justify the use of public members?and attract unwanted side effects?
    I also don't like to see (or to write) a huge long list of getters and setters at the bottom of any class file and find it quite ugly - You should use them when you need to, not as a matter of routine.
    Accessor - mutator is a design issue for private instance variables that you wish to keep hidden. Your suggestion to make them all public is also a design issue and if I was to see a long list of public variables at the beginning of a class (unexplained with javadoc comments) I would be very puzzled indeed.
    Eclipse will automate the generation of accessors and mutators for you and also has a refactoring tool too - both are extremely useful

  • Wrapper Class methods

    Hello.
    I'm testing wrapper class methods. I'm working right now with valueOf(). I'm trying to do a resume about the min and max values of all radix for wrapper class, something like this:
              p(" - Integer Table - ");
              p("Min: "+Integer.MIN_VALUE);
              p("Max: "+Integer.MAX_VALUE);
              p("Max Bin value: 1111111111111111111111111111111");
              p("->" + Integer.valueOf("1111111111111111111111111111111", 2));
              p("Max Oct value: 7777777777");
              p("->" + Integer.valueOf("777777777", 8));
              p("Max Hex value: 7777777777");
              p("->" + Integer.valueOf("FFFFFF", 16));Don't worry about p(). So .. when I'm using the method for octal and hexadecimal base they don't reach the max value of the integer. So I think that this is a mathematical issue that I don't know (I don't have math instruction =( so be nice with me) or probably something else. Let me know if my question is now well asked.
    Regards.
    vanhalt

    Two's complement isn't all that straightforward, but it's not too hard once you really look at it. (Catch-22, I know.)
    The basics (I assume you know the first part, but I just want to make sure it's clear):
    A computer stores numbers in binary. So, for instance, an 8-bit number has spots for 8 binary digits, making the largest possible number 11111111 (255). So that gives us 0-255 (256 possible values), but no negatives.
    To store negatives, you could take a bit away from your possible values, making it 1 bit for sign (say, 0 for positive and 1 for negative) and 7 bits for the number. In this scheme, you could get 127 positive values (00000001 to 01111111 [1 to 127]), 127 negative values (10000001 to 11111111 [-1 to -127]) and 2 ways to express zero (00000000 and 10000000, since 0 and -0 are the same number).
    Well, for a number of reasons, this isn't practical. Most importantly, it makes doing binary math very difficult. For example
    (5 - 2) --> (5 + -2) --> (00000101 + 10000010) = 10000111 --> -7. This is clearly the wrong answer.
    So some smart computer scientists realized that by taking an inverse of the binary value and then adding 1, they could do math with negative numbers without much difficulty. So instead of -2 being 10000010, they'd take the positive value (00000010) and get the inverse (11111101), then add 1 (11111110). Now you can add them: (00000101 + 11111110) = 100000011 (which has a 9th bit because of carry-over in the addition). And hey, it's not going to fit anyway so let's drop the 9th bit. And now we have 00000011. Which, lo and behold, is 3.
    And if your result comes back with a negative in the 8th bit, reverse the two's complement -- subtract 1, then inverse, and you have the absolute value.
    It's a nice trick that takes advantage of some arithmetic and the fact that we know we'd have to drop digits at the end. [Here's a more thorough explanation of why it works.|http://www.cs.duke.edu/courses/cps104/spring07/twoscomp.html]

  • About "method", "instance variable" and "constructor"

    Does a method need to be initialise?? if yes, how to write the code?
    for example,is it:
    public String mymethod( String args[]); ?
    public double mymethod2 (); ?
    what is the meaning of "instance variable" and "constructor"?
    Please help.....THANKS!

    Previously posted to this OP:
    Read the Java Tutorial: Learning the Java Language.
    http://java.sun.com/docs/books/tutorial/java/index.html
    � {�                                                                                                                                                                                                                                                                                                   

  • I want to access that BEA instance variable inside of a external java class

    Hi,
    This is N.pradeep. I am a java programmer, and I am new to BEA AquaLogic BPM studio5.7. I have a question regarding how to retrieve an instance variable of BEA Aqua Logic to an external Java Program. i.e. I want to access that BEA instance variable inside of a external java class, and vice versa.

    You can use PAPI or PAPI-WS for accessing BPM instance variable from a Java code, thougt I am not sure how the reverse will be done. Assuming that you are aware aof PAPI-WS and have created the necessary stubs out of the PAPI-WS WSDL using Axis, you can access instance variables using the API's or operations defined therein.
    Thanks and Regards
    Vivek Nandey
    BEA Certified Developer for Integration Solutions
    [email protected]

  • Convertion of class variable (static) into instance variable(non-static)!

    Dear all,
    got a slight different question.
    Is that possible to convert class variable (static) into instance variable(non-static)?
    If so, how to make the conversion?
    Appreciating your replies :)
    Take care all,
    Leslie V
    http://www.googlestepper.blogspot.com
    http://www.scrollnroll.blogspot.com

    JavaDriver wrote:
    Anything TBD w.r.to pass by value/reference (without removing 'static' keyword)?Besides the use of acronyms in ways that don't make much sense there are two other large problems with this "sentence".
    1) Java NEVER passes by reference. ALWAYS pass by value.
    2) How parameters are passed has exactly zero to do with static.
    Which all means you have a fundamentally broken understanding of how Java works at all.
    Am I asking something apart from this?
    Thanks for your reply!
    Leslie VWhat you're asking is where to find the tutorials because you're lost. Okay. Here you go [http://java.sun.com/docs/books/tutorial/java/index.html]
    And also for the love of god read this [http://www.javaranch.com/campfire/StoryPassBy.jsp] There is NO excuse for not knowing pass-by in Java in this day and age other than sheer laziness.

  • Problem in recognising instance variables declared in the class

    Hi all,
    I am trying to deploy an Servlet desiged in WebObjects5.1 application server on application on Iplanet Application server 6.5
    Back ground: All of you might be aware that WebObjects5.1 is an J2ee compliant application server. When an application is designed in WebObjects, it creates a WAR file which can be deployed on any J2ee complaint application server.
    I tried to create such application in WebObjects and tried to deploy on IplanetApplication server6.5(running on Windows using IIS web server).
    I am able to successfully deploy the application. But inorder to do this i had to manually add ias-Web.xml file to the war file generated( gave some arbitrary global id). The aplication just consists some string displaying hello world.
    Now when i try to deploy an application which has some instance variables, the instance variables are not getting recognised. This application works fine on WebObjects5.1. But variables are not getting recognised when deployed iplanet application server
    Has any one faced such kind of problem earlier? If yes please help me out
    Thanks
    Venkatesh

    Hi,
    Please send me your servlet code and war file.
    Thanks

  • Passing Wrapper Classes as arguments

    I have a main class with an Integer object within it as an instance variable. I create a new task that has the Integer object reference passed to it as an argument, the task then increases this objects value by 1. However the objects value never increases apart from within the constructor for the task class, it's as if it's treating the object as a local variable. Why?
    mport java.util.concurrent.*;
    public class Thousand {
         Integer sum = 0;
         public Thousand() {
              ExecutorService executor = Executors.newCachedThreadPool();
              for(int i = 0; i < 1; i++) {
                   executor.execute(new ThousandThread(sum));
              executor.shutdown();
              while(!executor.isTerminated()) {
              System.out.println(sum);
         public static void main(String[] args) {
              new Thousand();
         class ThousandThread implements Runnable {
              public  ThousandThread(Integer sum) {
                        sum = 5;
                        System.out.println(sum);
              public void run() {
                   System.out.println("in Thread : ");
    }

    AlyoshaKaz wrote:
    here's the exact queston
    (Synchronizing threads) Write a program that launches one thousand threads. Each thread adds 1 to a variable sum that initially is zero. You need to pass sum by reference to each thread.There is no pass by reference in Java
    In order to pass it by reference, define an Integer wrapper object to hold sum. This is not passing by reference. It is passing a reference by value.
    If the instructor means that you are to define a variable of type java.lang.Integer, this will not help, as Integer is immutable.
    If, on the other hand, you are meant to define your own Integer class (and it's not a good thing to use a class name that already exists in the core API), then you can do so, and make it mutable. In this case, passing a reference to this Integer class will allow your method to change the contents of an object and have the caller see that change. This ability to change an object's state and have it seen by the caller is why people mistakenly think that Java passes objects by reference. It absolutely does not.
    Bottom line: Your instructor is sloppy with terminology at best, and has serious misunderstanding about Java and about CS at worst. At the very least, I'd suggest getting clarification on whether he means for you to use java.lang.Integer, which might make the assignment impossible as worded, or if you are supposed to create your own Integer wrapper class.
    Edited by: jverd on Oct 27, 2009 3:38 PM

Maybe you are looking for

  • First bug in Imovie Mavericks Vluggie on October 23, 2013

    First bug in Imovie Mavericks Vluggie on October 23, 2013 # Today the new Imovie updated. Looks better and anything after searching and trying, it all seems to work well. What strikes me is that there are no moving globes are available on "Maps and S

  • ThinkVantage Registry Monitor Service consuming too much CPU!

    My X200 Tablet is often in an unusable stable for 10~20 minutes after a reboot or a wakeup from a sleep/hibernation state. I noticed it's mainly because CPU is busy with the ThinkVantage Registry Monitor Service. I noticed that although the CPU usage

  • Write array to spreadsheet string

    Hi, I have 3 numeric arrays and 1 string array.  I am try to use the function write array to spreadsheet string.  What is the easy way to do this, since I have both numeric and string, I can't create a 2d array directly? Yik Kudos and Accepted as Sol

  • Title 3D manual roll

    I'm trying to apply customized Motion to the Title 3D, in place of the standard "roll". But probably I'm missing something, since I'm not able to build a title higher than the standard 720x576 (PAL) to be rolled across the screen. In the Title 3D pan

  • Bad link for reset password

    hi all.. I'm trying to reset my Apple ID password for the mac app store. It consistently sends me an email with a link, but when i follow the link i get: Invalid Link We apologize, but we are unable to verify the link you used to access this page. Pl