Does Java pass objects by Reference
The following is my code:
public static boolean isValid(String tester, Integer intHours, Integer intMinutes)
int dotPosition = tester.indexOf('.');
String hours = tester.substring(0, dotPosition);
String minutes = tester.substring(dotPosition +1, tester.length());
try {
intHours = Integer.valueOf(hours);
intMinutes = Integer.valueOf(minutes);
} catch (NumberFormatException nfe) {
return false;
return true;
What Iam trying to do is pass the Integer Objects by reference so that they retain their values outside of the scope of the function. My teacher told me that objects are passed by reference in Java but (even though the values are being changed within the function they are not retaining their values outside the scope of the function. Was my teacher wrong?
aden_jones wrote:
So to get behaviour similar to passing by reference I would need to create my own object and give it a method e.g. MyObject.changeValue(new_value) but I can't do that with Integer objects because I can't change their actual value I can only change the Integer Object that is being pointed at??You cannot achieve behavior that duplicates PBR with Java.
However, if by "similar to passing by reference" you mean that the method makes a change that the caller can see, then, yes, you need to pass a reference to a mutable object, and change that object's state inside the method.
void foo(Bar bar) {
bar.setBaz(123);
Bar bar = new Bar();
bar.setBaz(999);
foo(bar);
// after foo() completes, the caller now sees that the Bar object's internal state has changed
// from 999 to 123Note the difference between changing the value of a caller's variable (which can be done with PBR, and cannot be done in Java) and changing the state of the single object pointed to by both the caller's variable and the method's copy of that variable (which can be accomplished in Java, as it does not rely on PBR).
Similar Messages
-
Passing objects by reference in PL/SQL
Hi,
I have come across an unexpected problem using object types in PL/SQL that is causing me some grief. I'm from a Java background and am relatively new to Oracle Objects but what I'm trying to do is fairly trivial, I think. The code below illustrates the problem.
--- cut here ---
CREATE OR REPLACE TYPE test_obj_t AS OBJECT
num INTEGER,
CONSTRUCTOR FUNCTION test_obj_t RETURN SELF AS RESULT
CREATE OR REPLACE TYPE BODY test_obj_t IS
CONSTRUCTOR FUNCTION test_obj_t RETURN SELF AS RESULT IS
BEGIN
num := 0;
RETURN;
END;
END;
CREATE OR REPLACE PACKAGE test_obj_ref AS
PROCEDURE init(o IN test_obj_t);
PROCEDURE inc;
FUNCTION get_num RETURN INTEGER;
END;
CREATE OR REPLACE PACKAGE BODY test_obj_ref IS
obj test_obj_t;
PROCEDURE init(o IN test_obj_t) IS
BEGIN
obj := o;
END;
PROCEDURE inc IS
BEGIN
obj.num := obj.num + 1;
END;
FUNCTION get_num RETURN INTEGER IS
BEGIN
RETURN obj.num;
END;
END;
--- cut here ---
The object type test_obj_t holds a integer and the test_obj_ref package holds a 'reference' to an instance of the object.
To test the above code I run this PL/SQL block:
declare
obj test_obj_t;
begin
obj := test_obj_t;
test_obj_ref.init(obj);
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
test_obj_ref.inc;
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
test_obj_ref.inc;
dbms_output.put_line('obj.num='||obj.num);
dbms_output.put_line('test_obj_ref.get_num='||test_obj_ref.get_num);
end;
giving the output:
obj.num=0
test_obj_ref.get_num=0
obj.num=0
test_obj_ref.get_num=1
obj.num=0
test_obj_ref.get_num=2
It appears that the object held by the test_obj_ref package is being incremented as expected, but I would have expected the object declared in the PL/SQL block to be pointing to the same object and so should report the same incremented values.
I suspect that the object is copied in the call to test_obj_ref.init() so I end up with two object instances, one that is held by the test_obj_ref package and one in the anonymous block. Although, I thought that all IN parameters in PL/SQL are passed by reference and not copied!
Am I right?
Is passing objects by reference possible in PL/SQL, if so how?
I'm using Oracle 10.2.0.3.
Cheers,
Andy.the object being passed to the test_obj_ref.init+ procedure is passed by reference; however, when you assign it to your package variable obj it is being copied to a new instance. you can pass object instances as parameters to procedures using the +IN OUT [NOCOPY]+ *calling mode, in which case modifications to the attributes of the passed object will be reflected in the calling scope's instance variable.
oracle's only other notion of an object reference is the +"REF <object-type>"+ datatype, which holds a reference to an object instance stored in an object table or constructed by an object view.
hope this helps...
gerard -
Does Java Pass by Reference or by Value?
I'm confused about this, please explain
thanxOk new to programming them don't listen to people who say that everything is passed by value, it's just some terminology debate that you don't need to care about at first.
Here are some examples from which you can try to figure out:
Example 1, the primitives:
public class TestPrimitive
public static void main(String[] args)
int value = 5;
foo(value);
System.out.println(value);
public static void foo(int value)
value = 3;
System.out.println(value);
}The output will be:
3
5
showing that the variable "value" was passed by value and therefore was not modified in the calling code by the alteration in the foo method.
Example 2, the arrays:
public class TestArray
public static void main(String[] args)
int[] array = new int[2];
array[0] = 0;
array[1] = 1;
foo(array);
System.out.println(String.valueOf(array[0]) + " " + array[1]);
public static void foo(int[] array)
array[0] = 3;
array[1] = 4;
System.out.println(String.valueOf(array[0]) + " " + array[1]);
}The output will be:
3 4
3 4
This mean that change to the array content get reflected in the calling code
Example 3, the arrays part 2:
public class TestArray
public static void main(String[] args)
int[] array = new int[2];
array[0] = 0;
array[1] = 1;
foo(array);
System.out.println(String.valueOf(array[0]) + " " + array[1]);
public static void foo(int[] array)
array = new int[2];
array[0] = 3;
array[1] = 4;
System.out.println(String.valueOf(array[0]) + " " + array[1]);
}The output will be:
3 4
0 1
Here is why people say everything is passed by value in Java, because if you make the array variable in the foo method to point on a new array, the one in the calling block continue to point on the old one, which is why it keep its [0,1} value.
Object work exactly like arrays.
Clear enough? -
Hi,
I am trying to write a linked list data structure in Java.
But I have a problem with these lines.
ListElement startingElement;
String data[] = new String[10];
private void addData()
ListElement currentElement = startingElement;
int i=0;
while(i < 10)
if(currentElement == null)
currentElement = new ListElement();
currentElement.addData(data);
else
currentElement.addData(data[i]);
currentElement = currentElement.nextElement();
i++;
But the problem is that data do not get added to the main startingElement. So I can not traverse the LinkedList using startingElement.
I think currentElement only gets a copy of data in starting element and not a reference to startingElement(1st line of addData function).
Plz tell me how to get a reference to startingElement. Or is there some other problem in my coding.
Thanks a lot,
Chamal.But the problem is that data do not get added to the
main startingElement. So I can not traverse the
LinkedList using startingElement. That's because you never assign anything to startingElement. What do you expect it to refer to?
I think currentElement only gets a copy of data in
starting element and not a reference to
startingElement(1st line of addData function).Nope. All object variables are references. "ListElement currentElement = startingElement" makes currentElement refer to the same object as startingElement. But like I said above, startingElement doesn't refer to anything. It probably contains the null reference.
Plz tell me how to get a reference to
startingElement. Or is there some other problem in my
coding."startingElement" contains a reference, just like all object variables. There seem to be many problems in your code. You never seem to assign a "next" element. For some mysterious reason you create an array of 10 strings, but never create strings for that array. Then you give each list element the array of 10 strings with no strings. The last line of your if block is duplicated in the else block, so it could be removed from both and moved below the if statement. -
Hi,
when i did C programming,i could pass in 2 values values by reference to a method called change values.
In java how do i pass in 2 values by reference to a method,and in return,the method changes 2 values that are passed in.
Do guide.
Thanks alot.
RahulJava does not pass values by reference at all ever.
You may only pass by value. -
How java extends Object class?
It is true that we cannot extend more than one class, it is true that java inherits Object class implicitly (if not explicitly) and it is also true that we can extend class X in class Y.
My question is if java does not support multiple inheritance (directly, using extends) then how does it extends Object (implicitly) and my class X (explicitly)?
In other words how does java inherits Object along with our specified class?
Thanks in advance.
ManishJava does support multi inheritance!Yes I know java support multiple inheritancethrough
interfaces but what I meant was you cannot inherit
multiple classes using "EXTENDS".and that is correct. Do you still have a question
regarding this?Nop, actually due to over-concentration and over-thinking on this topic while reading I lost the track and asked this question.
Thanks
Message was edited by:
Manish_India_1983 -
When does java deallocate memory for objects;
um i'm working on a midp application that is very memory consuming. i would like to optimise it and make it just the oposite of what it is. now i would like to know when does java dellocate memory for an object, is it when it can find no more references to that object? or some other time, well i know its not when it can find no more references to that object because i've already tried that.
or to make things simpler is there any explicit way to make java deallocate memory for a specific object, like if i have a thread, which is executing a while loop, and i want java to end the thread and free its memory. is there any way to do this?I happen to have quite some J2ME experience and it's not overly wise to count on extensive garbage collection. The garbage collector in limited device VMs isnt as advanced as it's big brothers. Try to avoid excessive object allocation and reuse instances whenever possible.
As for garbage collection, objects will be garbage collected if they can no longer be reached by any of the active application threads and if the garbage collectors deems it necessary to collect garbage, which will probably be when free heap memory becomes sparse or when there's some idle time in your application. -
ExternalInterface: pass object reference across interface - how?
I want to invoke methods on specific Javascript or
ActionScript objects through calls across the ExternalInterface
barrier. I would like to be able to do this either AS -> JS or
JS -> AS.
So I would like to pass an object reference across the
interface. I'm not sure exactly what *is* getting passed (is it the
serialized value of the object?), but it doesn't seem to work as an
object reference.
Here's a notional code sample. I have two symmetric object
definitions, one in Javascript, one in ActionScript. During
initialization, one instance of each object will be created and
given a pointer to the other. Then they should each be able to
invoke a method on the other to "do stuff".
//----------[ code ]---------------------------------
//--- Javascript ---
class JSobj {
var _asObj;
JSobj.prototype.setASObj = function(obj) { _asObj = obj; }
JSobj.prototype.callASObj = function(foo) {
callASObjectMethod(_asObj, foo); } // does: _asObj.asMethod(foo);
JSobj.prototype.jsMethod = function(bar) { /* do stuff */ }
function callJSObjectMethod(obj, args) { obj.jsMethod(args);
//--- ActionScript ---
class ASobj {
var _jsObj;
public function set jsObj (obj:Object):void { _jsObj = obj;
public function callJSObj (foo:Number):void {
ExternalInterface.call("callJSObjectMethod", _jsObj, foo); } //
does: _jsObj.jsMethod(foo);
public function asMethod (bar:Number):void { /* do stuff */
function callASObjectMethod (obj:Object, args) {
obj.asMethod(args); }
ExternalInterface.addCallback("callASObjectMethod",
callASObjectMethod);
//----------[ /code ]---------------------------------
My workaround is to pass a uint as an opaque handle for the
object, then resolve it when it is passed back. I'd rather pass a
real reference if possible. Is there a way to pass object
references between JS and AS?
Thanks,
-e-It's an object of a class that extends Object. I guess the answer is no then.
Thanks for your answer -
What is the use of passing object reference to itself ?
What is the use of passing object reference to itself ?
regards,
namancThere is an use for returning an object reference from itself, for instance:
class C {
public:
C append(C c) {
// do something interesting here, and then:
return this;
}You can "chain" calls, like this:
C c = new C();
C d = new C();
C e = new C();
c.append (d).append (e);Maybe the OP has "inverted" the common usage, or thought about a static method of a class C that requires a parameter of type C (effectively being a sort of "non-static method").
class C {
static void doAnotherThing (C c) {
c.doSomething(); //-- effectively C.doAnotherThing(c) is an "alternative syntax" for c.doSomething() -
What does java.exe do if double pass same classpath to it?
By default, java.exe loads rt.jar as default classpath.
if user explicitly passes rt.jar as classpath in command line to java.exe again, does java.exe load rt.jar twice or only once?
Loading same classpath twice is slower than only once - i need the answer for speeding my application.By default, java.exe loads rt.jar as default
classpath.Not correct. rt.jar is not loaded "as default classpath." It should not be listed on the classpath, as it WILL BE searched, and WILL slow down the tools.
The classpath is used by javac.exe and java.exe (and other tools) to locate your (the user) .java and .class files that they require.
Read these topics to learn how the classpath works and how to use it correctly:
Setting the Classpath and
How Classes are Found
from this page http://java.sun.com/j2se/1.4.2/docs/tooldocs/tools.html -
Passing parameters to Java JT400 object
I need to pass a byte array as my input and an int as the output length for the Class ProgramCall.
My error is
parameterList[0] (null): Parameter value is not valid.
My thoughts are
I think (but I'm not completely sure) I'm having trouble because I'm passing a Coldfusion Array where a Java Array is needed to pass the arguments.
Coldfusion arrays start at index 1 and Java Arrays start at index 0.
(1) Am I correct in what I believe is causing my error?
(2) How can I convert the Coldfusion Array to a Java Array?
Here is the documentation for Java JT400 object Class ProgramCall
http://publib.boulder.ibm.com/iseries/v5r1/ic2924/info/rzahh/javadoc/com/ibm/as400/access/ ProgramCall.html
Here is my code
<!--- I am the system object --->
<cfobject
action="create"
type="java"
class="com.ibm.as400.access.AS400"
name="mysystem">
<!--- I am the program call object --->
<cfobject
action="create"
type="java"
class="com.ibm.as400.access.ProgramCall"
name="myprogram">
<!--- I am the program parameter object --->
<cfobject
action="create"
type="java"
class="com.ibm.as400.access.ProgramParameter"
name="myparameter">
<!--- I am the as400 text object --->
<cfobject
action="create"
type="java"
class="com.ibm.as400.access.AS400Text"
name="mytext">
<!--- Initialize our system object --->
<cfset mysystem.init(AS400system,Trim(UCase(loginname)),Left(Trim(loginpass),10)) />
<!--- Execute our AS400 username validation --->
<cfset mysystem.ValidateSignon() />
<!--- Initialize our as400 text object and convert string to a byte array --->
<cfset mytext.init(5) />
<cfset nametext = mytext.toBytes("hello") />
<!--- Initalize our program parameter object --->
<cfset myparameter.init(2) />
<!--- Set input data and output data length using the Class methods of ProgramParameter --->
<cfset myparameter.setInputData(nametext) />
<cfset myparameter.setOutputDataLength(20) />
<!--- Set parameters to a Coldfusion Array --->
<cfset parameterlist = ArrayNew(1) />
<cfset parameterlist[1] = myparameter.getInputData() />
<cfset parameterlist[2] = myparameter.getOutputDataLength() />
<!--- Initalize our program object and run our program --->
<cfset myprogram.init(iseries,ProgramtoRun, parameterlist) />
<cfset myprogram.run() />reggiejackson44 wrote:
I need to pass a byte array as my input and an int as the output length for the Class ProgramCall.
My error is
parameterList[0] (null): Parameter value is not valid.
My thoughts are
I think (but I'm not completely sure) I'm having trouble because I'm passing a Coldfusion Array where a Java Array is needed to pass the arguments.
Coldfusion arrays start at index 1 and Java Arrays start at index 0.
(1) Am I correct in what I believe is causing my error?
(2) How can I convert the Coldfusion Array to a Java Array?
(1) Yes.
(2) A ColdFusion array and a Java array are 2 entirely different things. You have yourself identified one difference, the starting index. In fact, the following line of code will tell you that a ColdFusion array is essentially a Java vector.
<cfoutput>#arrayNew(1).getClass().getSuperClass().getname()#</cfoutput>
In my opinion, your question should read the other way around: how to convert a Java array into ColdFusion, not necessarily into a ColdFusion array.
Here are some tips and tricks:
http://blogs.adobe.com/cantrell/archives/2004/01/byte_arrays_and_1.html
http://www.bennadel.com/blog/1030-Building-Java-Arrays-In-ColdFusion-Using-Reflection.htm -
Compilation unit indirectly references the missing type java.lang.Object
Hi All,
I am getting the below mentioned error
"This Compilation unit indirectly references the missing type java.lang.Object (typically some required class file is referencing a type outside the class path)"
Please someone help me resolve this issue.
Thanks
UdayI am getting a new type of error
each time i am deleting a method which duplicate, its getting created again.
catch(WDDynamicRFCExecuteException wddree){
wddree.printStackTrace(); }
public void onActionExit(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionExit(ServerEvent)
//@@end
//@@begin javadoc:onActionExit(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionExit(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionExit(ServerEvent)
//@@end
//@@begin javadoc:onActionSelect(ServerEvent)
/** Declared validating event handler. */
//@@end
public void onActionSelect(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionSelect(ServerEvent)
//@@end
The following code section can be used for any Java code that is
not to be visible to other controllers/views or that contains constructs
currently not supported directly by Web Dynpro (such as inner classes or
member variables etc.). </p>
Note: The content of this section is in no way managed/controlled
by the Web Dynpro Designtime or the Web Dynpro Runtime.
//@@begin others
//@@end -
Does Java have an object model for the actual .java files?
OK, you know how you can use the Document Object Model (DOM) in JavaScript or PHP to access and modify specific parts of an HTML document? Is there anything similar for .java files? Can I load a .java file into some kind of Java Code Object Model (JCOM?) and then manipulate that code as if it were an object.
Note: I am not asking how to instantiate and use a regular object as defined by the .java file. I am wondering about modifying the actual .java file itself as an object that represents the actual text of the code in the .java file.GrantSR wrote:
Not the code, per se, but the classes they define... Yessum, most certainly: ASM, among others.
Also Google [java parser|http://www.google.com.au/search?q=java+parser]... one of them might do what you're after.
So, one would parse the Java code into XML using one of these many and
varied parsers, then access that XML via the DOM? Well, I guess a two
step process is good enough.
Thanks for your help.
No wuckers!
But I don't know if I did much. If you do get something working please post back, and outline your approach.
Cheers. Keith. -
Passing Objects to Stored Procedures in SQL Queries: UNREF(REF(o))
To me it seems that passing an object (type) to stored procedure in a SQL query is quite laborious. See:
I created the following simple type:
TYPE LAST AS OBJECT (
id NUMBER
defined a function:
FUNCTION "CHECKLAST" (l LAST)
RETURN NUMBER
AS LANGUAGE JAVA
NAME 'Checker.checkLast(Last) return int';
created a typed table:
CREATE TABLE lastTable OF Last;
inserted some objects:
INSERT INTO lastTable VALUES (1003);
NOW! If want to use the StoredFunction I have to use the following syntax:
SELECT checkLast(DEREF(REF(o)))
FROM lasttable o;
That's not very elegant.
I would expect the follwing to be working:
SELECT checkLast(o)
FROM lasttable o;
Did I do something wrong? Or did Oracle forget to implement the simple syntax?
Even worse, the DEREF(REF(o)) trick does not work for member functions...
Regards,
AndréI did some experiments and can now (partly) answer my own question:
Indeed, it is possible to declare a function with a parameter passed as reference:
CREATE OR REPLACE TYPE Point AS OBJECT
ID INT,
MEMBER FUNCTION distance(q IN REF Point) RETURN NUMBER
Unfortunately, it is not possible to use the REF in PL/SQL directly:
CREATE OR REPLACE TYPE BODY Point is
MEMBER FUNCTION distance(q IN REF Point) RETURN NUMBER
AS
BEGIN
RETURN q.ID - SELF.ID; --Error(5,14): PLS-00536: No navigation through REF
END;
end;
So, for testing purposes I decided to implement a very simple PL/SQL member function:
CREATE OR REPLACE TYPE BODY Point is
MEMBER FUNCTION distance(q IN REF Point) RETURN NUMBER
AS
BEGIN
RETURN -1;
END;
end;
BUT: The SQL query without VALUE is still not possible. The query
SELECT *
FROM PointTable d, PointTable e
WHERE d.distance(e) > 0
renders ORA-00904: "E": invalid identifier
Somehow the 'e' seems to be misinterpreted completely.
Illogically, the following query works fine:
SELECT *
FROM PointTable d, PointTable e
WHERE d.distance(REF(e)) > 0
The illogical thing is that, now 'E' seems to refer to a VALUE and not to REF (because we can use the REF function), whereas in Gaverill's post 'O' seems to refer to a REF (because we can use the VALUE function).
My intent is to avoid both the VALUE(o) from Gaverill's example and the REF(e) from my example, because both is not intuitive for end users...
Maybe I have to define a VIEW holding the object values... But then the end user has to use it in the FROM part.
All in all, there seems to be no elegant solution for passing objects as parameters to functions...
Regards,
André -
Confused !HashMap stores an object or reference ?
HashMap<Integer,Temp> m = new HashMap<Integer, Temp>();
Temp t1 = new Temp(1); /* pass the id in the constructor */
m.put(1, t1);
System.out.println(m.get(1).id); /* This prints out "1" */
t1.id = 100;
System.out.println(m.get(1).id); /* This prints out "100" */
t1 = null;
System.out.println(m.get(1).id); /* This prints out "100" */
Since externally modifying the id value of an object of temp class, which has already been inserted in the map, updates the id value of the object stored in the map, I thought that HashMap actually stores a reference and not the entire object. However if I assign a null pointer to t1 externally , still the object in HashMap is not null which means that hashMap has its own copy ??
Or does java play a smart trick and check whether a non-null object reference is being modified, and if it is, then all of its copies in any of the collections would be updated ?
Or I am missing something really simple ?Remember that t1 is also a reference to the same object as the map. When changing the object through t1's reference the accessing the object through the map will show this change as you specify.
But, when you set the t1 to reference null (point at nothing) it does not mean the actual object is deleted, lost or changed. It still exists, but now only referenced by the map.
Consider this:
Integer a = new Integer(1); // a points to the Integer object
Integer b = a; // b points to this same object. (not pointing to a, but the same object as a)
System.out.println( b );
b = null; // Now b point to null, but the Integer object is still referenced by a
System.out.println( b );
System.out.println( a );- Roy
Maybe you are looking for
-
SAP table for finding Quant from the Handling unit
Hi All, I would like to know the SAP table name - from the handling unit (where the stock received in the Warehouse), i would like to corresponding Quant ? PSS
-
I am having trouble getting rid of the annoying broken up circle going around and around on the right side of "sent" in the left panel. I went into mail preferences and retyped the passwords for the server, but it still keeps going. Also tried a re
-
http://twitvid.com/VNMQT As you can tell from the video, the camera freezes after a few seconds. So far it seems to only be the rear facing part. Also it seems to do it on other apps as well.
-
I am using multi threading with socket programming. One thread uses socket's output stream to send the data and the other thread keeps waiting for the data to arrive from that socket's input stream. Now when the readLine or readObject is excuting on
-
Can we Debug A.E.T? and how?
Hi, Friends can we Debug A.E.T? and how?