Passing primitive Wrapper class by reference
Hello,
Can we pass int value by reference?
At least by passing it's wrapper class.
class Test
public static void main(String args[])
Integer myInt = 0;
Test.testInteger(myInt, 5);
System.out.println("MyInt: " + myInt);
static void testInteger(Integer val, int value)
Integer newVal = value;
val = newVal;
}The code above surprisingly instead of outputting '5', it outputs '0'.
Isn't it passing object is always by reference?
Why it's not the case for primitive Wrapper class?
Is there any way to do this (pass by reference)?
Regards,
Heru
No! References to objects are passed by copy soif
you chage the copy you do not change theoriginal.
All values in Java are passed by copy. But when it's an object of a class, it works "by
reference".Java references are like pointer in C++ and not
references in C++. They are just called references
even though they are pointers.Yeah, but Integer is "just the same" with other class created by me (subclass of Object), why is the behavior different?
Similar Messages
-
Passing complex java class by reference to JNI
Hello all ,
I need to pass a java class (with primitive class members) to JNI and let the C++ update class member values so java would automatically get the new values.
I also would like to return such a class from JNI to java..
Is it possible ?
I would be happy to get some examples ...
thanks1. Passing an object is trivial. Define the java class, instantiate an object, and pass it as a parameter of your native method.
2. Calling methods of that object is standard JNI. You must
o Look up the class.
o Look up the method.
o Call the method.
3. Returning a java object from C is trivial. Just make it a parameter of your return statement. However you might want to think about whether you really need to do that; if it was an object passed with the native method call, then the object already exists within java. Otherwise, you will have to consider using JNI to instantiate java objects.
Start with the tutorials. If this project gets extensive, then I recommend buying a book on JNI. -
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 -
Class for primitive to class for corresponding wrapper?
Is there any way to programmatically get hold of the class object for a primitive wrapper (eg Double.class) from the class object for the primitive type (eg double.class)? What about the reverse mapping?
I can easily initilialize a Map of my own or write a method with if statements, but I'm curious if there is a library method somewhere. Or a simple coding trick. You know, just in case a new primitive type is added at some point ;-)Works with autoboxing.Object o = (byte) 3;
System.out.println(o.getClass().getName());
o = 3;
System.out.println(o.getClass().getName());
o = 3L;
System.out.println(o.getClass().getName());
o = 3.5F;
System.out.println(o.getClass().getName());
o = 3.5;
System.out.println(o.getClass().getName());
o = true;
System.out.println(o.getClass().getName());db
edit Sorry, I see that you want to get the wrapper class
from the class object for the primitive typeNo, I don't know a way to do that.
Edited by: Darryl.Burke -
What exactly is a wrapper class?
In so far as Integer, Byte, Double et al. are concerned I understand that those wrapper classes are a way to handle primitive types as objects. But I've come across references to wrapper classes in documentation and other technical articles and I don't think I really understand what they are really used for. Why do you need a wrapper class for an object?
Could someone shed me some light on this issue?
Thanks,
JohnAn instance of a wrapper class holds a pointer to and instance of some other class or interface and provides access to it, typically supplying methods equivalent to all the methods of the underlying type.
The basic wrapper class a functional replacement for the underlying object.
When you're passed an object from some code outside your control you often don't know what exact class it is, or have access to it's class definition.
A wrapper object allows you to modify the functionality of such an object. You can extend the wrapper class, for example, adding extra methods. Or you can modify the methods, for example to provide logging of calls made.
As a concrete example, I have a wrapper class LoggedConnection which wraps a java.sql.Connection object. It also implements java.sql.Connection. If you ask a LoggedConnection for a Statement or PreparedStatement it fetches the appropriate object and returns a wrapped version which logs the SQL and the execution times etc..
My "get me a connection" routine can return either a raw Connection or a LoggedConnection according to whether a SQL log file is provided.
The main program doesn't need to know if it's using a genuine Connection object or the wrapped version.
Part of the definition would look like:
public class LoggedConnection implements Connection {
private Connection wrappee;
public LoggedConnection(Connection con) {
wrapee = con;
public createStatement() throws SQLExeception {
return new LoggedStatement(wrappee.createStatement())
}(Of course this was tedious to write by hand because Connection has so many methods, all of which the wrapper must implement. Later I wrote a java program to generate Wrapper classes). -
What is meant by a wrapper class ?
What is meant by a wrapper class ?
java uses simple types such as int and char. these data type r not part of object hierarchy. they r passed by value to methods and cannot b directly passed by reference. there is no way for 2 methods to refer to the same instance of an int. at times u will need an object representation for one of these simple types.wrapper classes encapsulate or wrap the simple types within a class. thus, they r commonly referred to as type wrapper.
java provides classes that correspond to each of the simple types -
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.... -
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] -
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. -
I am new to the concept of wrapper classes. I have a small spell checker program that I need to access via a servlet by passing a string in and getting a string out with spelling suggestions. I could really use some advice on how to write a servlet that would do such a thing. TIA
grin1dan wrote:
I am new to the concept of wrapper classes. I have a small spell checker program that I need to access via a servlet by passing a string in and getting a string out with spelling suggestions. I could really use some advice on how to write a servlet that would do such a thing. TIABasically, a wrapper class is a class that "wraps" another - otherwise referred to as a "HAS-A" relationship (as opposed to a sub-class, which involves an "IS-A" relationship). It does this by including an instance of the wrapped class as one of its fields.
In many cases, wrapping is actually superior to inheritance.
I don't know how this fits with your servlet, but - assuming that your SpellChecker is implemented as a class - all you need to do is have your servlet define a "spellchecker" field; perhaps something like:
private final SpellChecker spellCheck = new SpellChecker();Probably worth reading up on though. Google "wrapper classes" and "forwarders".
Winston -
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. -
Could not load mediaLib accelerator wrapper classes. Continuing in pure Jav
Can anyone provide an explanation/solution to the following error message:
"Could not load mediaLib accelerator wrapper classes. Continuing in pure Java mode."This problem seems to occur if only the JAI JAR files are installed without the native DLL's. Is there some property that can be passed in to JAI so that it doesn't look for the DLL's? The lookup is causing quite a delay in initial server response time. We don't want to include the DLL's since they are a big pain for our customers to install and the performance issue is not a concern.
Thanks for any help!
-Matt -
Advantages and disadvantages of wrapper classes
Hi ,
will you please let me know what are the advantages and disadvantages of wrapper classes.
please do needful ASAP.
thanks in advanceHi Anil,
Wrapper classes are classes that allow primitive types to be accessed as objects.
Refer the foll Link:
http://www.cs.wustl.edu/~schmidt/PDF/Reactor1-93.pdf
http://whitepapers.silicon.com/0,39024759,60104914p,00.htm
Regards,
Sunil -
Advantages and disadvantages of wrapper class
Hi ,
will you please let me know what are the advantages and disadvantages of wrapper classes.
please do needful ASAP.
thanks in advanceHi Anil,
Wrapper classes are classes that allow primitive types to be accessed as objects.
Refer the foll Link:
http://www.cs.wustl.edu/~schmidt/PDF/Reactor1-93.pdf
http://whitepapers.silicon.com/0,39024759,60104914p,00.htm
Regards,
Sunil -
Hi,
I'm creating a class to my SCJD cert impl that has a protected RandomAccessFile reference member. I've designed this member as protected since subclasses really need to access it.
My dilema is that I thought of this class as a wrapper to that member, but, the way it is, classes from the same package can access it too, and I didn't really need/want that. I think of a wrapper as something that really encapsulates something, so...
Am I breaking any rules with the definition of wrapper classes? Does anyone know if any Java class has the same dilema?
thanks in advance,
Talessubclasses
really need to access it.Unlikely. I don't think I've ever created a protected member variable in 8 or 9 years of writing Java code.
My dilema is that I thought of this class as a
wrapper to that member,I would think the thing being wrapped would be private.
but, the way it is, classes
from the same package can access it too,Yes. Protected access allows classes in the same package to access it.
and I didn't
really need/want that.Then I think you're misunderstanding packages and/o subclassing. A package is a "closer" relationship than a parent/child relationship. It's perfectly natural for classes in the same package to be able to access a protected member. If it's a problem that they're able to access that member, then they probably shouldn't be in that package.
Am I breaking any rules with the definition of
wrapper classes? I'm not sure what the formal definition is--or if there is one--but I think making the wrapped thing non-private does violate the spirit of wrapper classes.
Also, I don't know if it's a good idea for a wrapper class not to be final.
Maybe you are looking for
-
After reading and resetting everything with Keyboard I still get blank white screen on 2nd? page of boot. The only way I can boot to Mavericks is unplug power cord, push and hold power button while plugging power cord in. Fans run at full speed, mach
-
I am unable to switch on the wifi on my iPhone 4s. I have tried restart, restore, update etc. But its still not working. Please help
-
How do I get my Ipod to sync if it says that the sync session failed to start?
How do I get my Ipod to sync if it says that the sync session failed to start?
-
How to unblock youtube website? in page info states "connection not encrypted"
a few months ago i blocked youtube then i want to unblock it but i don't know how. i see in the page info that states (website identity) website: www.youtube.com owner: this website does not supply ownership information. verified by: not specified (t
-
Hi Techis, I need to create user response function in webi report in a variable.The variable i use for furtur calculation. Gentis is a prompt name and user selects any one of the 2 values in a prompt. suppose user select "A" in the prompt it will ret