File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Missing Double Pointers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Missing Double Pointers" Watch "Missing Double Pointers" New topic
Author

Missing Double Pointers

Muhammad Ali
Greenhorn

Joined: Dec 04, 2000
Posts: 28
Hi,
I am almost an intermediate level programmer in Java. I come from C++ background and was wondering how can you achieve the following in Java:
void assignString (char **pString)
{
pString = new char[10];
*pString[0] = 'A';
*pString[1] = 'l';
*pString[2] = 'i';
*pString[3] = 0;
}
You can call this code as follows:
char *str;
assignString (&str);


A Java equivalent should have been as follows. But as you know "msg" will be local reference and will exist in this method only.
void assingString (String msg)
{
msg = new String ("Ali");
}
My question is why you don't have double references in Java? And how can you overcome this limitation?
One anoter <big>big</big> question: How can you pass primitive data types by reference? I heard about the wrapper classes but would like to see some code.
Muhammad Ali Shah
Karachi, Pakistan
Peter Tran
Bartender

Joined: Jan 02, 2001
Posts: 783
Muhammand,
From your code example, you want a String to contain "Ali" upon returning from assignString. To do this in Java, I would recommend the following code sample.

You can use the same technique for primitives. Create a primitive array of one element and pass this in. When you pass in the array, you're passing in a reference to the content of the array. With the array reference, you're allowed to change the content of the array, but not what the array points to.
Hope this helps.
-Peter

Muhammad Ali
Greenhorn

Joined: Dec 04, 2000
Posts: 28
Thank you very much. Now I can fully understand how you can use two, three and multi dimensional arrays to have the same affect as two, three or multi level pointers.
There is one question that still needs to be answered. Is there any other way (except arrays) to pass primitives by reference?
Thanks once again...
Ali.
Peter Tran
Bartender

Joined: Jan 02, 2001
Posts: 783
You can create your own primitive wrapper with set/get methods.

Output:
Bef executing modify(): 1.0
Aft executing modify(): 2.0
-Peter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Missing Double Pointers