Pass by reference and String
public class Test {
static void method(String str) {
str = "String Changed";
public static void main(String[] args) {
String str = new String("My String");
System.out.println(str);
method(str);
System.out.println(str);
}The output is
My String
My String
How this is possible when objects are passed by reference ?
> How this is possible when objects are passed by reference ?
All parameters to methods are passed "by value." In other words, values of parameter variables in a method are copies of the values the invoker specified as arguments. If you pass a double to a method, its parameter is a copy of whatever value was being passed as an argument, and the method can change its parameter's value without affecting values in the code that invoked the method. For example:
class PassByValue {
public static void main(String[] args) {
double one = 1.0;
System.out.println("before: one = " + one);
halveIt(one);
System.out.println("after: one = " + one);
public static void halveIt(double arg) {
arg /= 2.0; // divide arg by two
System.out.println("halved: arg = " + arg);
}The following output illustrates that the value of arg inside halveIt is divided by two without affecting the value of the variable one in main:before: one = 1.0
halved: arg = 0.5
after: one = 1.0You should note that when the parameter is an object reference, the object reference -- not the object itself -- is what is passed "by value." Thus, you can change which object a parameter refers to inside the method without affecting the reference that was passed. But if you change any fields of the object or invoke methods that change the object's state, the object is changed for every part of the program that holds a reference to it. Here is an example to show the distinction:
class PassRef {
public static void main(String[] args) {
Body sirius = new Body("Sirius", null);
System.out.println("before: " + sirius);
commonName(sirius);
System.out.println("after: " + sirius);
public static void commonName(Body bodyRef) {
bodyRef.name = "Dog Star";
bodyRef = null;
}This program produces the following output: before: 0 (Sirius)
after: 0 (Dog Star)Notice that the contents of the object have been modified with a name change, while the variable sirius still refers to the Body object even though the method commonName changed the value of its bodyRef parameter variable to null. This requires some explanation.
The following diagram shows the state of the variables just after main invokes commonName:
main() | |
sirius------->| idNum: 0 |
| name --------+------>"Sirius"
commonName()----->| orbits: null |
bodyRef |______________|At this point, the two variables sirius (in main) and bodyRef (in commonName) both refer to the same underlying object. When commonName changes the field bodyRef.name, the name is changed in the underlying object that the two variables share. When commonName changes the value of bodyRef to null, only the value of the bodyRef variable is changed; the value of sirius remains unchanged because the parameter bodyRef is a pass-by-value copy of sirius. Inside the method commonName, all you are changing is the value in the parameter variable bodyRef, just as all you changed in halveIt was the value in the parameter variable arg. If changing bodyRef affected the value of sirius in main, the "after" line would say "null". However, the variable bodyRef in commonName and the variable sirius in main both refer to the same underlying object, so the change made inside commonName is visible through the reference sirius.
Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. If the Java programming language actually had pass-by-reference parameters, there would be a way to declare halveIt so that the preceding code would modify the value of one, or so that commonName could change the variable sirius to null. This is not possible. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.
-- Arnold, K., Gosling J., Holmes D. (2006). The Java� Programming Language Fourth Edition. Boston: Addison-Wesley.
~
Similar Messages
-
Confused about passing by reference and passing by valule
Hi,
I am confuse about passing by reference and passing by value. I though objects are always passed by reference. But I find out that its true for java.sql.PreparedStatement but not for java.lang.String. How come when both are objects?
ThanksHi,
I am confuse about passing by reference and passing
by value. I though objects are always passed by
reference. But I find out that its true for
java.sql.PreparedStatement but not for
java.lang.String. How come when both are objects?
ThanksPass by value implies that the actual parameter is copied and that copy is used as the formal parameter (that is, the method is operating on a copy of what was passed in)
Pass by reference means that the actual parameter is the formal parameter (that is, the method is operating on the thing which is passed in).
In Java, you never, ever deal with objects - only references to objects. And Java always, always makes a copy of the actual parameter and uses that as the formal parameter, so Java is always, always pass by value using the standard definition of the term. However, since manipulating an object's state via any reference that refers to that object produces the same effect, changes to the object's state via the copied reference are visible to the calling code, which is what leads some folk to think of java as passing objects by reference, even though a) java doesn't pass objects at all and b) java doesn't do pass by reference. It passes object references by value.
I've no idea what you're talking about wrt PreparedStatement, but String is immutable, so you can't change its state at all, so maybe that's what's tripping you up?
Good Luck
Lee
PS: I will venture a guess that this is the 3rd reply. Let's see...
Ok, second. Close enough.
Yeah, good on yer mlk, At least I beat Jos.
Message was edited by:
tsith -
Drag and Drop - Transferable, how to pass a reference? (URGENT)
I've a tree that supports drag and drop correctly but every time I exchange a node position the old parent instance remaining on the tree is different from the one I was referencing with the dragged child before the drag occurred. I absolutely need to maintain all references and cannot work with copies.
Is there any way to use the Transferable interface to pass the original object instead of a copy?
Thanks to Tedhill who raised the problem, trying to get a quick answer.
;o)hi guys let me close this thread:
Thanks to asjf and sergey35 who helped me.
Actually the isDataFlavorSupported method you suggest passes a reference and not a copy.
Too bad I fell into another problem with the reloading of the
moving-node Object after the DnD.
But finally the working code is:
public class XJTreeDnD extends XJTree implements DragGestureListener, DragSourceListener, DropTargetListener{
private DefaultMutableTreeNode dragNode = null;
private TreePath dragParentPath = null;
private TreePath dragNodePath = null;
private DragSource dragSource;
private DropTarget dropTarget;
private TransferableTreePath transferable;
private boolean DnDEnabled = true;
//private boolean CnPEnabled = false;
public XJTreeDnD(XNode node) {
super(node);
// Set up the tree to be a drop target.
dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, this, true);
// Set up the tree to be a drag source.
dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
private DefaultMutableTreeNode getTreeNode(Point location) {
TreePath treePath = getPathForLocation(location.x, location.y);
if (treePath != null) {
return((DefaultMutableTreeNode) treePath.getLastPathComponent());
} else {
return(null);
//dragGesture implementation
public void dragGestureRecognized(DragGestureEvent e) {
if(DnDEnabled){
TreePath path = this.getSelectionPath();
if (path == null || path.getPathCount() <= 1) {
System.out.println("Error: Path null, or trying to move the Root.");
return;
dragNode = (DefaultMutableTreeNode) path.getLastPathComponent();
dragNodePath = path;
dragParentPath = path.getParentPath();
transferable = new TransferableTreePath(path);
// Start the drag.
e.startDrag(DragSource.DefaultMoveDrop, transferable, this);
//dragSource implementation
public void dragDropEnd(DragSourceDropEvent e) {
try {
if (e.getDropSuccess()) {
((BaseXJTreeModel)this.getModel()).removeNodeFromParent(dragNode);
DefaultMutableTreeNode dragParent = (DefaultMutableTreeNode) dragParentPath.getLastPathComponent();
XNode xnodeParent = (XNode)dragParent.getUserObject();
((BaseXJTreeModel)this.getModel()).valueForPathChanged(dragParentPath, xnodeParent);
} catch (Exception ex) {
ex.printStackTrace();
public void dragEnter(DragSourceDragEvent e) {
// Do Nothing.
public void dragExit(DragSourceEvent e) {
// Do Nothing.
public void dragOver(DragSourceDragEvent e) {
// Do Nothing.
public void dropActionChanged(DragSourceDragEvent e) {
// Do Nothing.
//dropTarget implementation
public void drop(DropTargetDropEvent e) {
try {
Point dropLocation = e.getLocation();
DropTargetContext dtc = e.getDropTargetContext();
XJTreeDnD tree = (XJTreeDnD) dtc.getComponent();
TreePath parentPath = tree.getClosestPathForLocation(dropLocation.x, dropLocation.y);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
Transferable data = e.getTransferable();
DataFlavor[] flavors = data.getTransferDataFlavors();
for (int i=0;i<flavors.length;i++) {
if (data.isDataFlavorSupported(flavors)) {
e.acceptDrop(DnDConstants.ACTION_MOVE);
TreePath movedPath = (TreePath) data.getTransferData(flavors[i]);
DefaultMutableTreeNode treeNodeMoved = (DefaultMutableTreeNode) movedPath.getLastPathComponent();
DefaultMutableTreeNode treeNodeLeft = (DefaultMutableTreeNode) this.dragNodePath.getLastPathComponent();
XNode xnodeParent = (XNode)parent.getUserObject();
XNode xnodeChild = (XNode)treeNodeLeft.getUserObject();
/** @todo check the parent whether to allow the drop or not */
if(xnodeParent.getPath().startsWith(xnodeChild.getPath())){
System.out.println("cannot drop a parent node on one of its children");
return;
if(xnodeParent.getPath().getPath().equals((xnodeChild.getPath().getParentPath()))){
System.out.println("node is already child of selected parent");
return;
// Add the new node to the current node.
xnodeParent.addChild(xnodeChild);
((BaseXJTreeModel)this.getModel()).valueForPathChanged(parentPath, xnodeParent);
((BaseXJTreeModel)this.getModel()).insertNodeInto(treeNodeMoved, parent, parent.getChildCount());
((BaseXJTreeModel)this.getModel()).valueForPathChanged(movedPath, xnodeChild);
e.dropComplete(true);
} else {
System.out.println("drop rejected");
e.rejectDrop();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
public void dragEnter(DropTargetDragEvent e) {
if (isDragOk(e) == false) {
e.rejectDrag();
return;
e.acceptDrag(DnDConstants.ACTION_MOVE);
public void dragExit(DropTargetEvent e) {
// Do Nothing.
public void dragOver(DropTargetDragEvent e) {
Point dragLocation = e.getLocation();
TreePath treePath = getPathForLocation(dragLocation.x, dragLocation.y);
if (isDragOk(e) == false || treePath == null) {
e.rejectDrag();
return;
// Make the node active.
setSelectionPath(treePath);
e.acceptDrag(DnDConstants.ACTION_MOVE);
public void dropActionChanged(DropTargetDragEvent e) {
if (isDragOk(e) == false) {
e.rejectDrag();
return;
e.acceptDrag(DnDConstants.ACTION_MOVE);
private boolean isDragOk(DropTargetDragEvent e) {
/** @todo gestire i casi in cui il drop non sia concesso */
return (true);
public void setDragAndDropEnabled(boolean enabled){
this.DnDEnabled = enabled;
public boolean isDragAndDropEnabled(){
return this.DnDEnabled;
Thanks again.
flat -
Strings are passed by Reference
Since strings are objects, they are passed by reference. I tested this out:
1.in main(): String str="in main"; creates a new string "in main" and has str point to it.
2.Passed str into changeStr(String str2)
3.in changeStr: str2="in changeStr", since str2 is a reference, it should redirect str to point to the new string "changeStr".
4.Back in main I print out str and get "in main".
Why?(When you post source code, please put it in CODE tags; there's a button for that above the textarea.)
Don't think of references as memory addresses; that makes them sound like C pointers, when in fact they're fundamentally different: a pointer points to a memory location, while a reference points to an Object. C lets you dereference a pointer and replace the data at that memory location with something else. Afterward, any existing variable that referred to the data in that section of memory, will see the new value.
A Java reference lets you access the object to call its methods, examine its variables, and so on. If the object is mutable, you can change itss contents, and all existing variables that refer to that object will see those changes. But you can't replace the whole object with something else. Reassigning the variable that was passed into the method has no effect on the original object or on any other variables that pointed to it.
So stop thinking of references as memory addresses. In fact, stop thinking about memory addresses, period. You never need that information in Java, and for that you should be eternally grateful. The absence of C pointers was one of Java's biggest selling points, way back when.
Edited by: uncle_alice on Feb 27, 2008 7:55 AM
Oh well. :-/ At least I may have done some good by asking the OP to use CODE tags. -
BizTalk Stored Proce-passing XML as one of the Input parameter and String as another parameter
I have a requirement in BizTalk that
- I will receive XML from Source and i need to submit this XML data and two other string parameters in SQL storeprocedure as a parameters and submit data
Ex: My_SP(myID Integer INPUT,myXML xml Input,mystring OUT)
Could you please help me how call storeprocedure and submit multiple parameters in BizTalk.you can execute stored procedure by generating schemas from WCF-SQL Adapter.
for passing parameters you will have to do the mapping to the Generated schema for Stored proc.
I would suggest to do this in Message Assignment shape, there you can easily assign all the parameters.
Integer and String parameters can be assigned from normal variables and XML parameter can be inserted as suggested by Abhishek-
xmldoc=requestMsg;
varOuterstring=xmldoc.Outerxml.Tostring();
Please refer the below article.
https://www.packtpub.com/books/content/new-soa-capabilities-biztalk-server-2009-wcf-sql-server-adapter
http://msdn.microsoft.com/en-us/library/dd787968.aspx
Thanks,
Prashant
Please mark this post accordingly if it answers your query or is helpful. -
Kinda urgent please help pass strings to doubles and strings to ints
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doublecupofjava666 wrote:
Need to know how to pass strings to doubles and strings to ints
and to check if a string is null its just if (name == null;) which means black right?
like size as a string and then make the string size a doubleThink he means blank.
Check the Wrapper classes (Double, Integer) in the api.
parseInt() parseDouble() both take a string and return a primitive.
String s = null;
if(s == null) should do the trick!
Regards.
Edited by: Boeing-737 on May 29, 2008 11:08 AM -
Using JNI to pass an array of Strings to C and back from C
I have some C code that I want to integrate with a new Java application and I need to be able to pass an array of strings to the C program and then the C program needs to be able to build an array of strings that is passed back to the Java program. I've got the first part working so that I can pass an array of strings to the C program and display them, but I can't figure out how to build the strings in C so that that when Java gets back control, it can display the strings tha were built in the C program.
Has anyone done this? Do you have some sample code?I have a program which is written in C. I can give you the whole project as it is in a zip file. You'll need VC to work with it. By the way, I am using Windows for development. Should you need it, I'll mail you the same. Give me your mail address.
-
How do you pass vi references from one event to another
I have a vi which gets vi references (thereby loading the vi's into memory) for all the vi's in a given directory when a user clicks a button on the front panel. To do this I use an event structure. My question is whether it is possible to have another event (user button on the front panel) which unloads the vi's from memory. I have tried passing the vi references that are initially generated to the close reference function but whenever I do I get a 'vi reference invalid' error. Does this have to do with trying to pass the vi references between one event and another? If I use a local variable simply pass a reference to another indicator and then probe it, the originally-generated refnum and the local vari
able refnum match up. However once I try to wire that same indicator to the close reference function I get the 'vi reference invalid' error. Is there a different/better way to unload the vi's from memory based on a user button click? Any suggestions would be welcome.
Jason
Attachments:
Load_Directory_of_vi's.vi 57 KBSeveral problems with your code:
1... Bad idea to use lights as buttons. Yes it can be done, but it's not "natural".
2... If you've gotta do that, set their mechanical action to "LATCH WHEN RELEASED"
3... Because of #2, you are getting TWO copies of every array when you click the LOAD VIs light (er... button).
4... No need for the conversion from path to string and back - use BUILD PATH to append each file name to he folder path.
5... Set the BROWSE OPTIONS on your PATH control to EXISTING DIRECTORY to allow browsing of directories, not files.
6... Your code doesn't care whether the file is a .VI file, or a .ZIP file, or a .TXT file, or what. Use the PATTERN input on the LIST function to discriminate.
7... Your code is only storing the latest refer
ence, not the array of references.
8... An ERROR DIALOG on the OPEN REFERENCE function will tell you that you're getting an error. Why? You are asking to prepare a non-reentrant VI for reentrant execution (why use options = 8?)
9... Because of #8, the latest VI reference is invalid.
Steve Bird
Culverson Software - Elegant software that is a pleasure to use.
Culverson.com
Blog for (mostly LabVIEW) programmers: Tips And Tricks -
Passing object references to methods
i got the Foo class a few minutes ago from the other forum, despite passing the object reference to the baz method, it prints "2" and not "3" at the end.
but the Passer3 code seems to be different, "p" is passed to test() , and the changes to "pass" in the test method prints "silver 7".
so i'm totally confused about the whole call by reference thing, can anyone explain?
class Foo {
public int bar = 0;
public static void main(String[] args) {
Foo foo = new Foo();
foo.bar = 1;
System.out.println(foo.bar);
baz(foo);
// if this was pass by reference the following line would print 3
// but it doesn't, it prints 2
System.out.println(foo.bar);
private static void baz(Foo foo) {
foo.bar = 2;
foo = new Foo();
foo.bar = 3;
class Passer2 {
String str;
int i;
Passer2(String str, int i) {
this.str = str;
this.i = i;
void test(Passer2 pass) {
pass.str = "silver";
pass.i = 7;
class Passer3 {
public static void main(String[] args) {
Passer2 p = new Passer2("gold", 5);
System.out.println(p.str+" "+p.i); //prints gold 5
p.test(p);
System.out.println(p.str+" "+p.i); //prints silver 7
}private static void baz(Foo foo) {
foo.bar = 2;
foo = new Foo();
foo.bar = 3;This sets the bar variable in the object reference by
foo to 2.
It then creates a new Foo and references it by foo
(foo is a copy of the passed reference and cannot be
seen outside the method).
It sets the bar variable of the newly created Foo to
3 and then exits the method.
The method's foo variable now no longer exists and
now there is no longer any reference to the Foo
created in the method.thanks, i think i followed what you said.
so when i pass the object reference to the method, the parameter is a copy of that reference, and it can be pointed to a different object.
is that correct? -
Pass by reference? I think not!
As I understand it, Java code automatically passes everything by reference. The code that I've written seems not to do this though.
String benefitID = new String();
String allBenID = new String();
try
benefitInfoDAO.selectIDs(awardCode, i, benefitID, allBenID);
catch (CMSException e)
throw e;
}The strings benefitId and allBenID are assigned values in the selectIDs method. However, when execution returns to the calling method, their values are "". What's going on?You forget that Strings are immutable objects, and when you pass the String into that other method, you are actually passing THAT String object into that method, here is an example.
class Bob()
Bob()
String myString = "Hello";
doSomething(myString);
System.out.println(myString); //Still prints out "Hello"
public void doSomething(String inString)
System.out.println(inString); //Prints out "Hello"
inString = "Bye!";
System.out.println(inString); //Prints out "Bye!"
Why is this? This is because Java passes everything as pointers, and not as C++ "References". Strings are also special, because they are immutable objects, there is no real way to manipulate a String object's memory once it's created. You can however do this to achieve the result you were looking for:
class Bob()
Bob()
StringBuffer myString = new StringBuffer("Hello");
doSomething(myString);
System.out.println(myString.toString()); //Now it prints out "Bye!"
public void doSomething(StringBuffer inString) //inString is a NEW pointer, you can change where it's pointing, but it will not change where myString in pointing!
System.out.println(inString.toString()); //Prints out "Hello"
inString.setLength(0);
inString.append("Bye!");
System.out.println(inString.toString()); //Prints out "Bye!"
} -
Using "Set Control Value" to pass a reference
Hi,
every time I tried to passe a Control Reference using "Set Control Value" I have the Error 1 (invalid input parameter at invoke node). Why is it not possible to pass a control reference using the invoke node??
Thanks
GolzioHi,
This is possible. Trick is, the type of the control reference needs to be
the same as the input. E.g. a string control reference is a different type
as a numeric control reference (, or a control reference).
To avoid this conflic, make sure the input of the vi is a control reference
(and not a e.g. string control reference). Also make sure the to convert the
reference you pass to a control reference (using Application Control>To More
Generic Class).
Regards,
Wiebe.
"Golzio" wrote in message
news:506500000008000000C1F00000-1079395200000@exchange.ni.com...
> Hi,
> every time I tried to passe a Control Reference using "Set Control
> Value" I have the Error 1 (invalid input parameter at invoke node).
> Why is it not possible to pass a control re
ference using the invoke
> node??
>
> Thanks
> Golzio -
I am retrieving high and low limits from step results in VB code that looks something like this:
' (This occurs while processing a UIMsg_Trace event)
Set step = context.Sequence.GetStep(previousStepIndex, context.StepGroup)
'(etc.)
' Get step limits for results
Set oStepProperty = step.AsPropertyObject
If oStepProperty.Exists("limits", 0&) Then
dblLimitHigh = step.limits.high
dblLimitLow = step.limits.low
'(etc.)
So far, so good. I can see these results in
VB debug mode.
Immediately after this is where I try to put the limits into the results list:
'Add Limits to results
call mCurrentExecution.AddExtraResult("Step.Limits.High", "UpperLimit")
call mCurrentExecution.AddExtraResult("Step.Limits.Low", "LowerLimit")
(No apparent errors here while executing)
But in another section of code when I try to extract the limits, I get some of the results, but I do not get any limits results.
That section of code occurs while processing a UIMsg_EndExecution event and looks something like this:
(misc declarations)
'Get the size of the ResultList array
Call oResultList.GetDimensions("", 0, sDummy, sDummy, iElements, eType)
'Step through the ResultList array
For iItem = 0 To iElements - 1
Dim oResult As PropertyObject
Set oResult = oResultList.GetPropertyObject("[" & CStr(iItem) & "]", 0)
sMsg = "StepName = " & oResult.GetValString("TS.StepName", 0) & _
", Status = " & oResult.GetValString("Status", 0)
If oResult.Exists("limits", 0&) Then
Debug.Print "HighLimit: " & CStr(oResult.GetValNumber("Step.Limits.High", 0))
Debug.Print "LowLimit: " & CStr(oResult.GetValNumber("Step.Limits.Low", 0))
End If
'(handle the results)
Next iItem
I can get the step name, I can get the status, but I can't get the limits. The "if" statement above which checks for "limits" never becomes true, because, apparently the limit results never made it to the results array.
So, my question again is how can I pass the low and high limit results to the results list, and how can I retrieve the same from the results list?
Thanks,
GriffGriff,
Hmmmm...
I use this feature all the time and it works for me. The only real
difference between the code you posted and what I do is that I don't
retrieve a property object for each TestStand object, instead I pass the
entire sequence context (of the process model) then retrieve a property
object for the entire sequence context and use the full TestStand object
path to reference sub-properties. For example, to access a step's
ResultList property called "foo" I would use the path:
"Locals.ResultList[0].TS.SequenceCall.ResultList[].Foo"
My guess is the problem has something to do with the object from which
you're retrieving the property object and/or the path used to obtain
sub-properties from the object. You should be able to break-point in the
TestStand sequence editor immediately after the test step in question
executes, then see the extra results in the step's ResultList using the
context viewer.
For example, see the attached sequence file. The first step adds the extra
result "Step.Limits" as "Limits", the second step is a Numeric Limit (which
will have the step property of "Limits") test and the third step pops up a
dialog if the Limits property is found in the Numeric Limit test's
ResultList. In the Sequence Editor, try executing with the first step
enalbled then again with the first step skipped and breakpoint on the third
step. Use the context viewer to observe where the Limits property is added.
That might help you narrow in on how to specify the property path to
retrieve the value.
If in your code, you see the extra results in the context viewer, then the
problem lies in how you're trying to retrieve the property. If the extra
results aren't there, then something is wrong in how you're specifying them,
most likely a problem with the AddExtraResult call itself.
One other thing to check... its hard to tell from the code you posted... but
make sure you're calling AddExtraResult on the correct execution object and
that you're calling AddExtraResult ~before~ executing the step you want the
result to show up for. Another programmer here made the mistake of assuming
he could call AddExtraResult ~after~ the step executed and TestStand would
"back fill" previously executed steps. Thats not the case. Also, another
mistake he made was expecting the extra results to appear for steps that did
not contain the original step properties. For example, a string comparison
step doesn't have a "Step.Limits.High" property, so if this property is
called out explicitly in AddExtraResult, then the extra result won't appear
in the string comparison's ResultList entry. Thats why you should simply
specify "Step.Limits" to AddExtraResul so the Limits container (whose
contents vary depending on the step type) will get copied to the ResultList
regardless of the step type.
I call AddExtraResult at the beginning of my process model, not in a UI
message handler, so there may be some gotcha from calling it that way. If
all else fails, try adding the AddExtraResult near the beginning of your
process model and see if the extra results appear in each step's ResultList.
Good luck,
Bob Rafuse
Etec Inc.
[Attachment DebugExtraResults.seq, see below]
Attachments:
DebugExtraResults.seq 20 KB -
Subroutine Pass by Value, Pass by Reference using xstring
Hi,
I am trying to check the difference between pass by value, pass by reference, pass by return value to a subroutine. When I tried integers as parameters the following functionality worked. When I am using xstring as parameters I am not getting desired results.
Some one please explain me how the xstring's are passed to a subroutine.
Here I am giving the code and output of the code.
data : s_passbyref type xstring,
s_passbyval type xstring,
s_passbyretval type xstring.
* Pass by Value, Pass by Reference, Pass by return value - STRINGS
s_passbyref = 'ABCD'.
s_passbyval = 'ABCD'.
s_passbyretval = 'ABCD'.
write : / 'ByRef :', s_passbyref, 20 'By Val :', s_passbyval, 40 'By Return Value : ', s_passbyretval.
perform call_str_sub using s_passbyref s_passbyval changing s_passbyretval.
write : / 'ByRef :', s_passbyref, 20 'By Val :', s_passbyval, 40 'By Return Value : ', s_passbyretval.
form call_str_sub using ps_passbyref value(ps_passbyval) changing value(ps_passbyretval).
ps_passbyretval = 'XYZ'.
ps_passbyref = 'XYZ'.
ps_passbyval = 'XYZ'.
endform.
OUTPUT
ByRef : ABCD By Val : ABCD By Return Value : ABCD
ByRef : By Val : ABCD By Return Value :
Thanks in advance
Naveentry this
write : / 'ByRef :', s_passbyref, 20 'By Val :', s_passbyval, 40 'By Return Value : ', ps_passbyretval. -
Passing object references via methods
Why is the JFrame object not being created in the following code:
public class Main {
public static void main(String[] args) {
Main main = new Main();
JFrame frame = null;
main.createFrame(frame); // <-- does not create the "frame" object
frame.pack();
frame.setVisible(true);
private void createFrame(JFrame frame) {
frame = new JFrame("createFrame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}Thanks.These explanations are great; real eye openers.
OK. This could be a "way out in left field" question. I am just starting out with Java. But I want to ask:
Objects are stored in the heap?
Object references and primitives are stored on the stack?
Adjusting heap size is straight-forward. A larger heap can store more/larger objects. What about stack sizes?
C:\Dev\java -Xss1024k Main
I assume this refers to method's stacks. But, what about object scoped, and class scoped, object references?
public class Main {
private static List list = new ArrayList(); // class scoped
private JFrame frame = new JFrame(); // object scoped
public static void main(String[] args) { ...... }
private void createFrame() { .... }
}How is the reference to list and frame stored, with regard to memory management?
Do objects have stacks?
Do classes have stacks?
If not, how are the list and frame references stored (which helps me understand reference scoping).
Would the overflow of a method stack (ex. via recurssion) also overflow the method's object and the method's class stacks?
If these questions are stupid, "out of left field", don't matter, etc. Just ignore them.
But the knowledge could help me avoid future memory related mistakes, and maybe pass a "Java Certified Developer" exam?
My original question is already answered, so thanks to all. -
Are Calendar Objects passed by reference?
Consider the following bit O' code:
TimeZone CST = TimeZone.getTimeZone("America/Chicago");
GregorianCalendar g = new GregorianCalendar(CST);
DateFormat D= DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);
D.setTimeZone(CST);
System.out.println(D.format(g.getTime()));
GregorianCalendar g2 = new GregorianCalendar(CST);
g2=g;
g2.add(Calendar.DATE,400);
System.out.println(D.format(g.getTime()));
Note that the last println prints g, not g2. The result is:
Apr 21, 2002 7:11:04 PM
May 26, 2003 7:11:04 PM
So advancing g2 affected g. Why? This doesnt happen with objects like strings.
How can I copy the contents of g into g2 then modify g2 without affecting g?Try g2=(GregorianCalendar)g.clone();Passing by reference has nothing to do with this problem.
When you assign g2 to g, g2=g;then both variables (references) reference the same object. The object that you created in GregorianCalendar g2 = new GregorianCalendar(CST); has gone to the Garbage Collector.
This doesnt happen with objects like stringsStrings are immutable and don't have any methods to change the contents, so the behavior is very different.
Dave
Maybe you are looking for
-
Can you still buy the new iPad(3generation)
I'm going to USA(i'm from sweden) in a couple of days and I flying home 1 november and Ipad 4 generation are relesed 2 november, so I wonder if I can still buy the third ipad now?
-
How to list all files in my system
Hi there, I want to list all files in my system. My system is Windows XP, can anybody help me please? Any can you recommend me if java is suit for such processing? Thx in advance.
-
Dear gurus, I want to block/reserve one invoice number from the existing invoice number range for commercial and excise invoice no. for example comercial invoice last number is 90123456 excise last invoice number is 1000123
-
does anyone know how you can put in your own custom logo? i've heard asus boards can do this and was wondering if i could make my own and use it.
-
How to make a JTextComponent not editable, not focusable but Highlightable?
Hi, When i set a JTextField not focusable, it wont allow me to do the highlight and do the copy and paste thing. can some one give me an example of how to add a highlighter in a JTextCompnent when it's not focusable. thanks in advanced.