| C++ programmer stumbles over pass by value. Need advice. |
|
 |
Index ‹ java-programmer
|
- Previous
- 3
- Corba java apllet client communication problemI hava a problem with communication between Java/Corba server based on JDK
ORB with Java/Corba client (applet)
based on the same ORB. I`m using IOR to localize server.
client`s ORB i initialize like that:
Dane proxy = null;
ORB orb = ORB.init(parent, null);
org.omg.CORBA.Object obj = orb.string_to_object(sIOR);
proxy = DaneHelper.narrow(obj);
server`s ORB i initialize like that:
ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
DaneImpl oDane = new DaneImpl();
org.omg.CORBA.Object ref = rootpoa.servant_to_reference(oDane);
String ior = orb.object_to_string(ref);
It looks like that:
- if i`m trying to run applet throught web site from the same (192.168.0.1)
computer where Corba sever works
everything works fine, i write it in the browser->
http://192.168.0.1//TestCoraba.html
- if i`m trying to run applet throught web site from an other (192.168.0.2)
computer server receive method call
from client but client can`t receive server`s answer and stops, i write it
in the browser-> http://192.168.0.1//TestCoraba.html
Maybe you what i`m doing wrong.
Thanks form any help.
Best Regards - gRabbi
- 3
- Tomcat, Oracle, connection pooling, BLOBsI have a rather strange problem with Tomcat's connection pooling and
the Oracle JDBC driver when using BLOBs that seems to be related to
class loading.
My configuration:
Tomcat 5.0.27
Oracle 9i
ojdbc14.jar is in $CATALINA_HOME/common/lib (and nowhere else)
The datasource is configured in server.xml
Everything works perfectly as long as I don't configure the datasource
in the server.xml file (including reading/writing BLOBs).
Once I use the datasource configuration in server.xml everything
except Oracle's BLOB implementation works (means: I can access the
tables, insert, select etc., but I can't read/write BLOBs)).
The problem is with class loading:
System.out.println(getConnection() instanceof
oracle.jdbc.driver.OracleConnection);
System.out.println(getConnection().getClass().getName());
results in:
false
oracle.jdbc.driver.OracleConnection
So the connection is of the expected type, but the type has been
loaded with the wrong class loader. This leads to a ClassCastException
in the Oracle JDBC driver (createTemporary()).
As I told you the JDBC driver is in common/lib and nowhere else, so
the class should be available in the application code.
Any hints ?
- 6
- JDOM stringsHi All !
I have some xml file that contain next tag:
<text>ÐоÑ</text>
I get Element text = ... on this tag and want get string that it contain:
String myText = text.getText();
I hope to see in the myText : 0xD09D 0xD0BE .....
but get next set:
0xC390 0xC29D 0xC390 0xC2BE 0xC391 0xC280 0xC390 .... ?????
what is it 0xC390 ??? And how can I get that I want :) ???
--dima
- 6
- Why is creating a simple component with Netbeans IDE fails with an exceptionHi
steps:
using a mounted sub-directory named TESTING
Template: In the Explorer, select the TESTING node and choose File New "Java
Gui Form" Bean Form. click next
Target Location: In Name enter TargetName. click next
Basic Class definition: Superclass select javx.swing.JComponent. click
finish
Why do you get an exception :
Cannot determine form type (javax.swing.JComponent)
Please make sure the class is a JavaBean
The form cannot be opened.
I am trying to build a component similar to a JLabel which is a JavaBean
derived directly from a JComponent.
Which step is missing or am I completly out to lunch.
Thanks in advance
Andre
- 6
- Help using TexPadIs there anyone here who knows how to use TextPad for a programming editor?
I sure could use the help. The instructions in help don't really explain
what to do. It says I'm supposed to see something but it isn't there, i.e.
I'm supposed to click on "Configure" then "Tools" then "Add" and I'm
supposed to click on "Java SDK Commands" and that command is not listed.
What do I do??
Thanks
Pete
- 6
- popupmenu for a cell in a JTableHello
I want to have a popupmenu when I right click on a selected cell in a JTable
(using with a AbtractTableModel). What are steps I should do, please help.
Thank you
S.Hoa
- 9
- Why jdk-1.5.0 and diablo-jdk-1.5.0 does not containOn Tue, Jan 08, 2008 at 01:04:22PM +0300, Alex Pivovarov wrote:
> Could you tell me why jdk-1.5.0 and diablo-jdk-1.5.0 does not contain
> sunpkcs11.jar in jre/lib/ext?
> Or I was doing something wrong when I install them. I use default options --
> the only think I uncheck is browser plugin.
Because the source code and build infrastructure aren't included for either
the JAR or the native library in the source that Sun distributes(*). You
could copy the included Linux/Solaris JARs over, but then you need to build
the corresponding native library somehow.
* - Actually, the source is there, but its bundled up and there is no
build infrastructure.
Thats my recollection at least.
--
Greg Lewis Email : email***@***.com
Eyes Beyond Web : http://www.eyesbeyond.com
Information Technology FreeBSD : email***@***.com
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
- 10
- Java inherited annotationsHello all!
Some times ago the problem was raised... I and my collegs started to
use Java annotations and noticed that our annotations those was made
for java interfaces and their methods didn't accessible in inherited
classes and interfaces... I tried to use the metatag @Inherited but IMHO
it doesn't work correctly. Anyway we have made our own realization of
inherited Java annotations and shared it. So u can use it if you want.
It is free and open source. Can be downloaded from here:
http://www.fusionsoft-online.com/annotation.php
Best Regards,
Michael Milonov
- 10
- problem faced while using setContentType("Application/csv")Hi.
while i am trying to respond my client with the dilaog using which a
client user could save the file , the file which is to be sent from
server .... i am facing some issues in
setContentType("Application/csv") .... (file type is csv) ... here is
the chunk of code ....
System.out.println("This line gets displayed before setting content
type");
httpservletresponse.setContentType("application/csv");
System.out.println("After setting content type") // This line never
gets displayed
httpservletresponse.setHeader("Content-Disposition","inline;
filename=" +strtemp[1]+".csv" );
try {
File uFile = new File(strFilePath);
int fSize = (int) uFile.length();
FileInputStream fis = new
FileInputStream(uFile);
PrintWriter pw =
httpservletresponse.getWriter();
int c = -1;
while ( (c = fis.read()) != -1) {
pw.print( (char) c);
}
// Close output and input resources.
fis.close();
pw.flush();
pw = null;
}
catch (Exception e) {
System.out.println("Exception is caught
");
e.printStackTrace();
Any suggestion regarding the issue will be highly obliged ...
Regards,
Madni
- 12
- Need to know ASAPOur educational counselors are recruiting new people for our home degree program.
We are running this program as an experiment and we feel you may qualify. This program will earn you a fully qualified degree, with transcripts. Currently we are recruiting people with vast knowledge or experience in the field/trade of their choice.
Give our recruiting office a call when you have time.
Thanks
Alexander Piper
Office Number: 1-773-509-4920
We hope to be talking to you soon.
*We are taking calls at anytime in the day or evening.
--
To UNSUBSCRIBE, email to email***@***.com
with a subject of "unsubscribe". Trouble? Contact email***@***.com
- 12
- CeWolf and JSPHi, I'm Claudio, I'm a student and I want to use ceWolf for my graphs
in JSP pages. I visited the web site http://cewolf.sourceforge.net/
and i followed each pass of the tutorial but I don't visualize the
chart, there is an exeption: NullPointerException in cewolf_jsp.java
row 202:
int _jspx_eval_cewolf_img_0 = _jspx_th_cewolf_img_0.doStartTag();
In the JSP, if I delete this row:
<cewolf:img chartid="line" renderer="cewolf" width="400"
height="300"/>
all go ok, but obviously there isn't the chart.
Could you help me, please!
Thanks, Claudio
- 14
- JSP Include IssuesI have a web page using an include file. I am passing params to the
include page using jsp:param but am having some difficulty.
Locally (Windows PC/Tomcat Server, JBuilder) I can include ™ in
the heading1 param - when I put this live (Linux/Tomcat Server) the
heading1 text is cut off after the &. There is no error message from
Java (unless it is a System.out.print type error).
Does anyone have any suggestions as to why this is not working and how
I can resolve it?
<jsp:include flush="true" page="/inc/nav.jsp">
<jsp:param name="heading1" value="Business Web Design:
<em>Functional, Findable, Accessible ™</em>" />
<jsp:param name="pageTitle" value="Home" />
</jsp:include>
Regards,
Rick
www.e-connected.com
- 14
- Vendor independent data sourceI have an application that I deployed to WebSphere using the default
Struts datasource from it's action. I've been reading about this now
and it sounds like this is not the prefered way to make a database
connection pool. They suggest using the containers, but I want to
remain vendor independent and be able to deploy my application in any
container with little or no changes.
I know there must be a standard non-vendor specific way to create a
connection pool. Can someone tell me what that standard is? Searching
the web just provided me with about 100 different ways to do it, but I
want the "Java Standard" way to do this.
Thanks,
Smitty
- 15
- Drawing ImageHi,
I am developing a login application in which i need to have an image
put on to a JFrame which has several internal frames. (The main frame)
when I use the graphics object, it draws up the image and it disappears
in a few seconds.
I tried to change the background color, but i see only a flash of the
color and it disappears.
It would be extremely helpful is someone could sort this problem for
me.
Thank you,
Sumit
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.imageio.*;
import java.awt.Graphics.*;
public class Login extends JPanel implements KeyListener ,
ActionListener
{
JFrame mainFrame;
JDesktopPane desktop, background;
JInternalFrame user;
JButton ok, cancel;
JTextField userName;
TextField pass;
JLabel lname,lpass,message,ms;
JMenuBar mb;
JMenu start,view,options,insert,help;
JMenuItem ocm,ccm,print,exit,about;
Boolean connectionManagerStatus;
Image img;
Login()
{
/*
* Basic Theme
*/
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch (Exception e)
{
System.out.println(e.toString());
}
/*
* Initializations and addition to the program
*/
mb = new JMenuBar();
desktop = new JDesktopPane();
background = new JDesktopPane();
mainFrame = new JFrame (".:: I . C . E ::. Application");
mainFrame.setJMenuBar(mb);
start = new JMenu ("Start");
view = new JMenu ("View");
options = new JMenu ("Options");
insert = new JMenu ("Insert");
help=new JMenu("help");
start.setMnemonic(KeyEvent.VK_S);
view.setMnemonic(KeyEvent.VK_V);
options.setMnemonic(KeyEvent.VK_O);
insert.setMnemonic(KeyEvent.VK_I);
help.setMnemonic(KeyEvent.VK_H);
mb.add(start);
mb.add(view);
mb.add(options);
mb.add(insert);
mb.add(help);
background.setVisible(true);
background.setSize(640,640);
ocm=new JMenuItem("Open Connection Manager",KeyEvent.VK_O);
ccm = new JMenuItem("Close Connection",KeyEvent.VK_C);
print = new JMenuItem("Print",KeyEvent.VK_P);
exit = new JMenuItem("Exit",KeyEvent.VK_X);
about = new JMenuItem("About Us",KeyEvent.VK_A);
start.add(ocm);
start.add(ccm);
start.addSeparator();
start.add(print);
start.add(exit);
help.add(about);
user = new JInternalFrame("Connection Manager");
lname = new JLabel("USERNAME:");
userName = new JTextField (50);
lpass = new JLabel("PASSWORD:");
pass = new TextField(50);
pass.setEchoChar('*');
ms = new JLabel ("Message From Server: ");
message = new JLabel("3 Wrong attempts and account freezes");
ok = new JButton ("Login");
cancel = new JButton ("Cancel");
ok.setBounds(20,180,100,20);
cancel.setBounds(130,180,100,20);
mainFrame.setUndecorated(false);
mainFrame.add(desktop);
mainFrame.setFocusable(true);
options.setEnabled(false);
insert.setEnabled(false);
view.setEnabled(false);
print.setEnabled(false);
ocm.setEnabled(false);
ccm.setEnabled(false);
connectionManagerStatus=true;
mainFrame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
desktop.setSize(640,480);
lname.setBounds(10,40,70,20);
userName.setBounds(100,40,130,20);
lpass.setBounds(10,100,100,20);
pass.setBounds(100,100,130,20);
ms.setBounds(15,270,140,20);
message.setBounds(10,320,240,20);
message.setForeground(Color.darkGray);
user.setLayout(null);
user.getContentPane().add(lname);
user.getContentPane().add(userName);
user.getContentPane().add(lpass);
user.getContentPane().add(pass);
user.getContentPane().add(ok);
user.getContentPane().add(cancel);
user.getContentPane().add(ms);
user.getContentPane().add(message);
user.setResizable(false);
//JLabel s = new JLabel("XXXXXXXXXXXXXXx");
ok.setEnabled(false);
user.setVisible(true);
user.setSize(340,480);
desktop.setLocation(30,200);
desktop.add(user);
user.setLocation(30,200);
//user.setBorder(BorderFactory.createRaisedBevelBorder());
// adding listeners
userName.addKeyListener(this);
exit.addActionListener(this);
cancel.addActionListener(this);
ocm.addActionListener(this);
pass.addKeyListener(this);
ok.addActionListener(this);
mainFrame.setVisible(true);
mainFrame.validate();
l();
}
public void actionPerformed (ActionEvent ae)
{
if ((ae.getSource())==exit)
{
System.exit(0);
}
else if ((ae.getSource())==cancel)
{
user.setVisible(false);
userName.setText(null);
pass.setText(null);
ocm.setEnabled(true);
}
else if ((ae.getSource())==ocm)
{
user.setVisible(true);
ocm.setEnabled(false);
}
else if ((ae.getSource())==ok)
{
user.setVisible(false);
ocm.setEnabled(false);
ccm.setEnabled(true);
System.out.println(pass.getText());
}
}
public void keyPressed (KeyEvent ke)
{
if ((ke.getComponent())==userName)
{
if (userName.getText()!=null)
{
ok.setEnabled(true);
}
else
{
ok.setEnabled(false);
}
}
else if ((ke.getComponent())==pass)
{
}
}
public void keyReleased (KeyEvent ke1)
{
}
public void keyTyped (KeyEvent ke2)
{
}
public static void main (String args [])
{
Login obj = new Login ();
}
public void l()
{
Graphics g = mainFrame.getGraphics();
try
{
img = Toolkit.getDefaultToolkit().getImage("d:\\loge.bmp");
g.drawImage(img,1024,800,null);
System.out.println("Image drawn");
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
}
- 15
- Snake Sex 1827email***@***.com wrote:
> I like to masterbate with my pet python, i hope you enjoy the pics i posted here of me having a wonerfull snakey time !
>
> http://superbabes.sexpartnerbd.com
> cvgixlemtdskrblgjgfeitxfscjzhrcppyxghjowcxfo
>
leave it out! this is a java programming news group!
try comp.lang.python
W'ell just hang here having a wonderful erm.... "Classy" time! [groan]
|
| Author |
Message |
Lenny Wintfeld

|
Posted: 2006-4-19 8:29:00 |
Top |
java-programmer, C++ programmer stumbles over pass by value. Need advice.
Here's a model of my problem. I see what's causing it (thinking in C++,
with pass by reference) but I don't see a Java way to solve it. Probably
because I'm so new to Java.
Here's the problem.
2 methods inside the same class. Method1 passes a String array to
method2, relying on method2 to process the string array and return a
String and a new String array for further processing back to method1.
public boolean method1 (String s1, other args)
{
//do some stuff
String [] sa1 = null; // to be created and returned by method2
String s2 = null; // to be created and returned by method2
Method2(s1, sa1, s2)l
//do some important stuff with sa1 and s2
return true;
}
// C++ type method (unfortunately)
private void method2 (String s1, String [] sa1, String s2)
{
//do some stuff
StringTokenizer st = new StringTokenizer(s1, "/");
String sRemainder;
sRemainder = st.nextToken();
s2 = st.nextToken(); // just a string to be returned
sa1 = sRemainder.split(","); // a string array to be returned
}
The eclipse debugger confirms that method 2 is processing the strings
exactly as I want it to. sa1 and s2 after the processing look great
inside method 2. But they're null after the return to method1. I assume
this is because sa1 and s2 are copies inside method 2 and they go out of
scope on the return. sa2 and s1 are created inside method2 but I need
them for further work in method 1.
I obviously coded this like a C/C++ programmer. What I'd like to know is
what's the conventional methodology (or programming idiom) for passing
back lots of stuff created in one method to it's caller? Feel free to
hack up the above example to show me how, if it's convenient.
Thanks in advance for your help/
Lenny Wintfeld
|
| |
|
| |
 |
Andrew McDonagh

|
Posted: 2006-4-19 8:55:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
Lenny Wintfeld wrote:
> Here's a model of my problem. I see what's causing it (thinking in C++,
> with pass by reference) but I don't see a Java way to solve it. Probably
> because I'm so new to Java.
>
> Here's the problem.
>
> 2 methods inside the same class. Method1 passes a String array to
> method2, relying on method2 to process the string array and return a
> String and a new String array for further processing back to method1.
>
>
>
>
> The eclipse debugger confirms that method 2 is processing the strings
> exactly as I want it to. sa1 and s2 after the processing look great
> inside method 2. But they're null after the return to method1. I assume
> this is because sa1 and s2 are copies inside method 2 and they go out of
> scope on the return. sa2 and s1 are created inside method2 but I need
> them for further work in method 1.
>
> I obviously coded this like a C/C++ programmer. What I'd like to know is
> what's the conventional methodology (or programming idiom) for passing
> back lots of stuff created in one method to it's caller? Feel free to
> hack up the above example to show me how, if it's convenient.
>
> Thanks in advance for your help/
>
> Lenny Wintfeld
>
For starters, try to stop thinking in C++ - easier said than done
admittedly, but worth it.
In Java, References are passed by value. The objects they point to
aren't actually moved or copied at all.
Primitives (ints, boolean, long, etc) are always passed by value.
So this leaves only two ways of returning things from methods.
1) the method's returned type. In your example, you could change the
method signature to return something rather than its current 'void'.
2) Pass in a reference to a Data holder object, inside the method set
the value within the Dataholder to what ever it is you want to return.
Either way works for sending by single or multiple values. For multiple
values it just means you'll have to wrap then in something.
Data holder passed in parameter list example:
class StuffReturnedByMethod2 (
String [] sa1 = null; // to be created and returned by method2
String s2 = null; // to be created and returned by method2
}
public boolean method1 (String s1, other args)
{
//do some stuff
StuffReturnedByMethod2 returnedStuff = new StuffReturnedByMethod2();
Method2(s1, returnedStuff )
//do some important stuff with sa1 and s2
String[] sa1 = returnedStuff.sa1;
String s2 = returnedStuff.s2;
return true;
}
// C++ type method (unfortunately)
private void method2 (String s1, StuffReturnedByMethod2 stuffToReturn)
{
//do some stuff
StringTokenizer st = new StringTokenizer(s1, "/");
String sRemainder = st.nextToken();
stuffToReturn.s2 = st.nextToken(); // just a string to be returned
stuffToReturn.sa1 = sRemainder.split(",");
// a string array to be returned
}
This might look - hacky or cheap, but what we tend to find, is that we
have more smaller classes in Java, which are highly focused upon one
job. These classes might startout being mere data holders, but usually,
very quickly they start attracting behaviour or state too.
|
| |
|
| |
 |
Adam Warner

|
Posted: 2006-4-19 10:24:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
On Tue, 18 Apr 2006 20:29:02 -0400, Lenny Wintfeld wrote:
> Here's a model of my problem. I see what's causing it (thinking in C++,
> with pass by reference) but I don't see a Java way to solve it. Probably
> because I'm so new to Java.
>
> Here's the problem.
>
> 2 methods inside the same class. Method1 passes a String array to
> method2, relying on method2 to process the string array and return a
> String and a new String array for further processing back to method1.
What you're actually after is multiple return values ("return a String and
a new String array" => two return values). Unfortunately Java provides no
efficient construct for multiple return values. They were removed before
the first release of Java. I'd like to locate the 1997 interview
referenced in this Usenet post:
<http://groups.google.com/group/comp.object/msg/580bc83193356221?dmode=source>
Gosling may just be being folksy, but I find the following
answers from a language designer as really poor:
G:> Yeah. I actually had an implementation of Mesa-style
G:> multiple value returns mostly implemented just before
G:> 1.0 that I ripped out because I was uncomfortable with
G:> the semantics, and the schedule was getting tight.
G:> Right now, I really regret it.
The next thing you may try to do with a language that doesn't implement
multiple return values is pass the values upon the stack via a pointer.
This will be less efficient than multiple return values passed in
registers but more efficient than heap-allocated multiple return values.
This approach is also impossible in Java.
This leaves building an object to pass the values in. You have the choice
of whether the caller should pass an object for the callee to mutate or
whether the callee builds a fresh object to hold the multiple return
values.
You may be inclined to pass a container object to the callee to mutate
since the container can be reused by the caller. I suggest the callee
should build a new container for multiple values each time because the
most sophisticated JVMs will soon be able to avoid heap allocation (and
perhaps even stack allocation) via escape analysis. Thus we are close to
the point where Gosling's omission of explicit multiple return values will
no longer be a hindrance to efficiently returning multiple values. While
your code is likely to run slower in the meantime it's the future-proof
option.
Regards,
Adam
|
| |
|
| |
 |
Lenny Wintfeld

|
Posted: 2006-4-19 11:41:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
Thanks very much for your comments and advice. It's been a long day
(about 12 straight hours coding) so I'll try using your suggested "reply
class" or "return class" tomorrow. Though I can't imagine having
trouble with that method.
If there's any trouble (which I doubt) I'll post it back on this thread.
Thanks again
Lenny Wintfeld
In article <email***@***.com>,
email***@***.com says...
> Here's a model of my problem. I see what's causing it (thinking in C++,
> with pass by reference) but I don't see a Java way to solve it. Probably
> because I'm so new to Java.
>
> Here's the problem.
>
> 2 methods inside the same class. Method1 passes a String array to
> method2, relying on method2 to process the string array and return a
> String and a new String array for further processing back to method1.
>
> public boolean method1 (String s1, other args)
> {
> //do some stuff
> String [] sa1 = null; // to be created and returned by method2
> String s2 = null; // to be created and returned by method2
>
> Method2(s1, sa1, s2)l
>
> //do some important stuff with sa1 and s2
>
> return true;
> }
>
>
> // C++ type method (unfortunately)
> private void method2 (String s1, String [] sa1, String s2)
> {
> //do some stuff
> StringTokenizer st = new StringTokenizer(s1, "/");
>
> String sRemainder;
>
> sRemainder = st.nextToken();
> s2 = st.nextToken(); // just a string to be returned
>
> sa1 = sRemainder.split(","); // a string array to be returned
> }
>
>
> The eclipse debugger confirms that method 2 is processing the strings
> exactly as I want it to. sa1 and s2 after the processing look great
> inside method 2. But they're null after the return to method1. I assume
> this is because sa1 and s2 are copies inside method 2 and they go out of
> scope on the return. sa2 and s1 are created inside method2 but I need
> them for further work in method 1.
>
> I obviously coded this like a C/C++ programmer. What I'd like to know is
> what's the conventional methodology (or programming idiom) for passing
> back lots of stuff created in one method to it's caller? Feel free to
> hack up the above example to show me how, if it's convenient.
|
| |
|
| |
 |
Luc The Perverse

|
Posted: 2006-4-19 12:09:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
"Lenny Wintfeld" <email***@***.com> wrote in message
news:email***@***.com...
> Thanks very much for your comments and advice. It's been a long day
> (about 12 straight hours coding) so I'll try using your suggested "reply
> class" or "return class" tomorrow. Though I can't imagine having
> trouble with that method.
>
> If there's any trouble (which I doubt) I'll post it back on this thread.
>
> Thanks again
>
> Lenny Wintfeld
Remember to keep a positive attitude. Remember, this is not an annoying
workaround to fix a problem with the language - but rather simply the way
the language is meant to be used ;)
I imagine that you will find, as I did, that you will find this generally
helps you to make cleaner more readable code.
:)
|
| |
|
| |
 |
Domagoj Klepac

|
Posted: 2006-4-20 3:46:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
On Wed, 19 Apr 2006 14:23:45 +1200, Adam Warner
<email***@***.com> wrote:
>This leaves building an object to pass the values in. You have the choice
>of whether the caller should pass an object for the callee to mutate or
>whether the callee builds a fresh object to hold the multiple return
>values.
>
>You may be inclined to pass a container object to the callee to mutate
>since the container can be reused by the caller. I suggest the callee
>should build a new container for multiple values each time because the
>most sophisticated JVMs will soon be able to avoid heap allocation (and
>perhaps even stack allocation) via escape analysis. Thus we are close to
>the point where Gosling's omission of explicit multiple return values will
>no longer be a hindrance to efficiently returning multiple values. While
>your code is likely to run slower in the meantime it's the future-proof
>option.
Wait a second.
Are you saying that in a future JVMs objects won't be "passed by
reference", and that a program like this:
public class PassByReference {
public static void appendFive(StringBuffer s1, StringBuffer s2) {
s1.append(" two");
s2.append(" three");
}
public static void main(String[] args) {
StringBuffer str = new StringBuffer("one");
PassByReference.appendFive(str, str);
System.out.println(str);
}
}
...won't print "one two three" but "one"?
Of course, using Strings or primitives in this example would print
"one", and this is a bit "dirty", and is not something I'd recommend
as a best practice, and ESPECIALLY to a C++ programmer :)))... but it
is a useful hack in a few rare cases, where it can save you from
creating a class just to return several objects.
Domchi
|
| |
|
| |
 |
Dimitri Maziuk

|
Posted: 2006-4-20 4:40:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
Lenny Wintfeld sez:
> Here's a model of my problem. I see what's causing it (thinking in C++,
> with pass by reference) but I don't see a Java way to solve it. Probably
> because I'm so new to Java.
Yes, but Java's fscked-up terminology takes large portion of the
blame. In Java "reference values" are pointers passed by value.
Assignment operator simply re-points the pointer (not like C++
references), whereas dereferencing operator does what you
expect: e.g. you can modify the object by calling its mutator
methods (not like "pass by value").
> Here's the problem.
>
> 2 methods inside the same class. Method1 passes a String array to
> method2, relying on method2 to process the string array and return a
> String and a new String array for further processing back to method1.
>
> public boolean method1 (String s1, other args)
> {
> //do some stuff
> String [] sa1 = null; // to be created and returned by method2
> String s2 = null; // to be created and returned by method2
>
Simple for sa1:
String [] sa1 = new String[N];
(provided N is known beforehand, otherwise use ArrayList). For s2
the trick is that strings are "immutable" (have no mutator methods),
so you need to use a mutable version: StringBuilder (1.5+ only) or
StringBuffer:
StringBuilder s2 = new StringBuilder();
Creating a separate class for return value only makes sense where
you'd return a struct in C++. In this case I'd probably not bother
anyway : you can as easily return s2 as 1st element of your array.
Dima
--
The speed at which a mistyped command executes is directly proportional
to the amount of damage done. -- Joe Zeff
|
| |
|
| |
 |
Adam Warner

|
Posted: 2006-4-20 8:15:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
On Wed, 19 Apr 2006 21:46:26 +0200, Domagoj Klepac wrote:
> On Wed, 19 Apr 2006 14:23:45 +1200, Adam Warner
> <email***@***.com> wrote:
>>This leaves building an object to pass the values in. You have the
>>choice of whether the caller should pass an object for the callee to
>>mutate or whether the callee builds a fresh object to hold the multiple
>>return values.
>>
>>You may be inclined to pass a container object to the callee to mutate
>>since the container can be reused by the caller. I suggest the callee
>>should build a new container for multiple values each time because the
>>most sophisticated JVMs will soon be able to avoid heap allocation (and
>>perhaps even stack allocation) via escape analysis. Thus we are close to
>>the point where Gosling's omission of explicit multiple return values
>>will no longer be a hindrance to efficiently returning multiple values.
>>While your code is likely to run slower in the meantime it's the
>>future-proof option.
>
> Wait a second.
>
> Are you saying that in a future JVMs objects won't be "passed by
> reference", and that a program like this:
[...]
> ...won't print "one two three" but "one"?
Optimisations via escape analysis must not change existing program
semantics. What it will mean is that objects treated like primitives
(where object identity is irrelevant) will likely be as fast as if the JVM
had explicit support for those primitives.
A great example is an immutable complex number class. To return an
immutable complex number one returns a new complex object. In the vast
majority of cases the object's existence is fleeting. All the calling code
does is extract the real and imaginary fields before losing its object
reference. Current the Sun JVM always builds the complex object and this
increases garbage collection activity and reduces locality of reference.
Soon the Sun JVM will be able to deduce that it doesn't need to create the
object. Behind the scenes it will get those fields to the caller via a
different route. This route may be the stack or machine registers.
From another perspective this complex number is the return of TWO values.
These optimisations will also apply to the return of conceptually
discrete multiple values that are wrapped up in a single return object.
Whenever you hold onto a return object past the caller's lifetime it will
continue to be heap allocated to preserve program semantics.
> ... but it is a useful hack in a few rare cases, where it can save you
> from creating a class just to return several objects.
Without an additional syntactic blessing from Sun you'll have to
explicitly wrap up and extract multiple return values.
These optimisations aren't just necessary for a few rare cases. They are
critical for high performance object-oriented operation upon
primitive-style objects.
The remaining critical omission from the JVM is a new set of arrays with
64-bit (long) array indices. This will not affect existing code as long
array indices are currently a compile time error. While easy to implement
and critical for some scientific computing tasks I do not see Sun taking
leadership of this issue. My guess is (an offshoot of) the Harmony project
will eventually force Sun to address this.
Regards,
Adam
|
| |
|
| |
 |
Oliver Wong

|
Posted: 2006-4-20 22:50:00 |
Top |
java-programmer >> C++ programmer stumbles over pass by value. Need advice.
"Domagoj Klepac" <email***@***.com> wrote in message
news:email***@***.com...
> On Wed, 19 Apr 2006 14:23:45 +1200, Adam Warner
> <email***@***.com> wrote:
>>This leaves building an object to pass the values in. You have the choice
>>of whether the caller should pass an object for the callee to mutate or
>>whether the callee builds a fresh object to hold the multiple return
>>values.
>>
>>You may be inclined to pass a container object to the callee to mutate
>>since the container can be reused by the caller. I suggest the callee
>>should build a new container for multiple values each time because the
>>most sophisticated JVMs will soon be able to avoid heap allocation (and
>>perhaps even stack allocation) via escape analysis. Thus we are close to
>>the point where Gosling's omission of explicit multiple return values will
>>no longer be a hindrance to efficiently returning multiple values. While
>>your code is likely to run slower in the meantime it's the future-proof
>>option.
>
> Wait a second.
>
> Are you saying that in a future JVMs objects won't be "passed by
> reference", and that a program like this:
>
> public class PassByReference {
> public static void appendFive(StringBuffer s1, StringBuffer s2) {
> s1.append(" two");
> s2.append(" three");
> }
>
> public static void main(String[] args) {
> StringBuffer str = new StringBuffer("one");
> PassByReference.appendFive(str, str);
> System.out.println(str);
> }
> }
>
> ...won't print "one two three" but "one"?
Obviously, Sun "owns" Java, and they are free do whatever they want with
future versions of the language.
But I think what Adam is saying is that the language and JVM
specifications specify behaviour, not implementation. As long as the above
program prints "one two three", it doesn't matter HOW it does it. It might
do so by passing stuff around by value, or passing stuff around by
reference, or by not passing anything around at all and doing some inlining
magic instead, or maybe something else I haven't come up with yet.
- Oliver
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- Please,HELP ME!!Safe to all.. I have had an urgent need of sapre in that manner I can
create a message of mistake in the case in which a JTextField
contains numbers! I do not know if I have explained, in practice I want
ke in this Jtext alone characters are contained and not
numbers!!! how I do?
- 2
- deploy of servlet problemI am newbie to servlet and I am trying some simple example of servlet in
which I have written
1) a html form to get data saved in webapps/myplace/
2) a servlet which is to return the data got from the request.get of the
html form.
I have deployed the tomcat server, put the compiled servlet class in the
WEB-INF/classes and also make the web.xml file.
However, when I load the page to the servlet from the html form, and click
submit from the form which is supposed to link to the servlet, it returns
404 error which said it cannot load the page.
I would like to know what I have missed that lead to such problem.
Thousands Thanks
- 3
- DocBook Editor ComponentHi,
I am developing an application, which I want to distribute under GPL.
I am looking for a swing component, which will be able to edit docbook
documents in the way jeditorpane does it with HTML files.
Does anyone know anything, which would help me (so that I will not have
to write the component from scratch)?
I also thought about customizing Swing's editor pane. Can I modify the
HTMLEditorKit class so it's capable to handle Docbook files? Could I
then distribute this modified code under GPL or am I facing a conflict
with a kind of Sun license?
Martin Kyselak
- 4
- 5
- NervousText vs NetBeans 4.1Hello,
I'm trying to learn how to create custom property editors for own javabeans.
I'm using sun's tutorial from webpage
http://java.sun.com/developer/onlineTraining/Beans/Beans4/nervous07.html
Everything is going well, i'm able to add this bean as new component
toNetBeans
by Palette Manager, i'm able to add this new component to jFrame,
but when I'm trying to change "text" property in properties editor,
NetBeans adds in initComponents() line:
nervousText071.setText(???);
Does anybody know what is the reason of malfunction? Is it my fault?
this is the property editor class:
package sun.beanbox.beans;
import java.beans.*;
public class NervousText07TextPropertyEditor
extends PropertyEditorSupport {
public String[] getTags() {
String values[] = {
"Nervous Text",
"Anxious Text",
"Funny Text",
"Wobbly Text"};
return values;
}
}
The rest of sources is on that webpage.
Many thanks in advance,
superchumbo
- 6
- FOUND IT !!!
I needed to add mail.jar and activation.jar. :D
Works fine now.
- 7
- Need help with JTabledPaneHello all
I have JTabledPane in my application. In it I have some tabs with titles
"Tab 1", "Tab 2" and "Tab 3". I want to have the color of the title "Tab 3"
is red (so it is easy to recognize). Is it possible?. Could you please
help..
I tried to use add a red label for the title's tab but it does not work.
Thank you
- 8
- Validating parsed XML document against XML-schema*PROBLEM: how to validate parsed XML document against (parsed) XML-schema.
*IN: XML document as org.w3c.dom.Document, XML-schema as stream
*OUT: information if document is valid against schema. If document is not
valid DETAILED information about ALL errors (especially: node that caused
problem).
*Additional information:
- validation is performed quite often,
- XML-document object is changed quite often,
- XML-Schema is fixed.
- XML-document doesn't contain information about related XML-schema
(attr xsi:noNamespaceSchemaLocation)
- XML-Schema is available as file only when the application starts.
It means that schema can be loaded from a file only once.
- must works in Java1.4+
I've tried to implement it using JAXP:
//app start
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSource = new StreamSource(new File(schemaFile));
Schema schema = schemaFactory.newSchema(schemaSource);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
//document is being changed usign .addChild etc.
//
Validator validator = schema.newValidator();
validator.setErrorHandler(new SimpleErrorHandler());
validator.validate(new DOMSource(document));
Unfortunately org.xml.sax.ErrorHandler gets only SAXParseException which
doesn't constant information about node that caused the problem.
Is there any other way to validated DOM-document?
- 9
- Java3D & Stereo OutputHi!
Does anybody know about the support of Stereo output in Java3D? What has
to be done to activate the stereo output?
Cheers,
Thomas
- 10
- Another reason why everyone should killfile Joe AttardiJoe Attardi tries to start a pure attack thread:
> http://groups-beta.google.com/group/comp.text.tex/browse_thread/thread/814dca01faf56429/80585d528a53dd21
>
> The name is different ("Mark Mephinasony") but it's the same Google
> Groups account. He mentions a problem he's having with some software,
> then someone suggests he files a bug with their bug tracker. Watch how
> quickly Twisted/Mark/whoever quickly turns it into a vicious argument.
Well, well, what have we here? Did you really think I wouldn't be
paying attention for something like this? Of course it's stooping
pretty low to create a whole new thread to attack someone (and
attacking them directly in the subject line, of course), even if it's
also bloody predictable.
Go play in traffic.
- 11
- Help: Calling System.exit(0) inside finallyHello everyone,
I am trying to release windowing resource after a try-catch and found
that calling System.exit(0) inside finally may hide the an uncaught
exception. See example below.
What is the *right way* to use finally in this case?
--lc
PS.
(1) Problem with putting System.exit(0) at the end is that the JFrame is not
properly released when an uncaught exception (e.g. divide by zero) is
generated.
(2) Now if I move System.exit(0) inside finally clause, then JFrame is
released OK but the uncaught exception is not even reported!
import javax.swing.*;
public class FinallyTest extends JFrame {
FinallyTest(String title) {
super(title);
JLabel l = new JLabel("Calculates Quotient of 2 Numbers....");
getContentPane().add(l);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,100);
setVisible(true);
}
public static void main( String args[] )
{
String s1, s2;
int number1, number2, quotient;
JFrame f = new FinallyTest("Test Finally Clause");
try {
s1 = JOptionPane.showInputDialog( "Enter integer numerator" );
s2 = JOptionPane.showInputDialog( "Enter integer denominator" );
number1 = Integer.parseInt( s1 );
number2 = Integer.parseInt( s2 );
quotient = number1 / number2;
JOptionPane.showMessageDialog(null, "The quotient is " + quotient,
"Results", JOptionPane.PLAIN_MESSAGE );
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid data! Bye!", "Invalid
data", JOptionPane.ERROR_MESSAGE);
}
/*
catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Exception: " + e + "! Bye!",
"Arithmetic Exception", JOptionPane.ERROR_MESSAGE);
}
*/
finally{
// System.exit(0);
}
System.exit(0); // Should do this in the finally clause???
}
}
- 12
- OMG SPAM IT AGAIN AGAIN!!!!!!! abuse@telus.comemail***@***.com wrote:
>
> http://
email***@***.com
--
Service to my country? Been there, Done that, and I've got my DD214 to
prove it.
Member of DAV #85.
Michael A. Terrell
Central Florida
- 13
- data for specific dayI need to collect data for every day in year (choosing 1 option within 3)
for specific number of persons. What is the simpliest way for from a
component side of problem. I was thinking about putting drop down menu in a
table, but maybe it will be too complicated for me (and preety long table),
so if you have better solution for my web application?
- 14
- How do I slow down my network?This may be a bit off-topic, but still:
I'm working with a Java client/server app.
In my test setup the client and server are connected via the 100 MBit
LAN, so bandwidth is virtually unlimited.
I want to test it in a more realistic setup, where the bandwidth is
only, say, 56 kbit/sec.
Is there a simple way to temporarily limit the bandwidth for test
purposes?
I have thought of putting a delay between every IP packet, on the
trasmitting or the receiving side, but in Java I don't have access to
individual packets, so I can't figure out where to insert the delay.
Maybe the solution should be made on a lower layer, like the ethernet.
Chris
- 15
- Macintosh JTable cellBordersDoes anyone know how to make a JTable display with grid lines under the
Macintosh LnF?
I understand it has something to do with the following, but so far have
had no luck with it.
UIManager.getDefaults().put( "TableHeader.cellBorder", LineBorder );
Mike Sampson
|
|
|