Java is pass by value or pass by refrence

Can any one explain whetherjava is pass by value or pass by refrence.

Everything in Java is passed "by value". Everything.
Pass-by-value
- When an argument is passed to a function, the invoked function gets a copy of the original value.
- The local variable inside the method declaration is not connected to the caller's argument; any changes made to the values of the local variables inside the body of the method will have no effect on the values of the arguments in the method call.
- If the copied value in the local variable happens to be a reference (or "pointer") to an object, the variable can be used to modify the object to which the reference points.
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.... 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.
-- James Gosling, et al., The Java Programming Language, 4th Edition
[Pass-by-Value Please (Cup Size continued)|http://www.javaranch.com/campfire/StoryPassBy.jsp]

Similar Messages

  • Is it possible in java to pass reference of object in Java?

    Hello,
    I'm relativily new to Java but I have "solid" knowledge in C+ and C# .NET+.
    Is it possible in java to pass reference of object in Java? I read some articles about weakreferences, softreferences, etc. but it seems that it's not what I'm looking for.
    Here is a little piece of code I wrote:
    package Software;
    import java.util.Random;
    * @author Rodrigue
    public class RandomText
        private Random rand = new Random();
        private Thread t;
        private String rText = "Rodrigue";
        public RandomText()
            t = new Thread()
                @Override
                public void run()
                    try
                        while(true)
                            UpdateText();
                            sleep(100);
                    catch(InterruptedException ex)
            t.start();
        private void UpdateText()
            int i = rand.nextInt();
            synchronized (rText)
                rText = String.valueOf(i);
        public String GetText()
            return rText;
    }It's just a class which start a thread. This class updates a text with a random integer 10 times per second.
    I would like to get a reference on the String rText (like in C++ ;) yes I know, I must think in Java :D). So, like that, I could get one time the reference, thanks to the GetText function, and update the text when my application will repaint. Otherwise, I always have to call the GetText method ... which is slow, no?
    Are objects passed by reference in java? Or, my string is duplicated each time?
    Thank you very much in advance!
    Rodrigue

    disturbedRod wrote:
    Ok, "Everything in Java is passed by value. Objects, however, are never passed at all.". Reference of object is passed by value too.
    But, how to solve my problem in Java_? I have an object which is continually modified in a thread. From an another side, this object is continually repainted in a form.I'm not sure I totally understand your problem. If you pass a reference to an object, then both the caller and the method point to the same object. Changing the internal state of the object (e.g. by calling a setter method) through one reference will be observed through both references, since they both point to the same object.
    No, calling a method is not particularly slow. Especially if it's just a simple getter method that returns the value of a member variable.
    If this is happening in a multithreaded context, you'll have to use proper synchronization to ensure that each thread sees the others' changes.

  • I need to call a batch file from java and pass arguments to that Batch file

    Hi,
    I need to call a batch file from java and pass arguments to that Batch file.
    For example say: The batch file(test.bat) contains this command: mkdir
    I need to pass the name of the directory to the batch file as an argument from My Java program.
    Runtime.getRuntime().exec("cmd /c start test.bat");
    How to pass argument to the .bat file from Java now ?
    regards,
    Krish
    Edited by: Krish4Java on Oct 17, 2007 2:47 PM

    Hi Turing,
    I am able to pass the argument directly but unable to pass as a String.
    For example:
    Runtime.getRuntime().exec("cmd /c start test.bat sample ");
    When I pass it as a value sample, I am able to receive this value sample in the batch file. Do you know how to pass a String ?
    String s1="sample";
    Runtime.getRuntime().exec("cmd /c start test.bat s1 ");
    s1 gets passed here instead of value sample to the batch file.
    Pls let me know if you have a solution.
    Thanks,
    Krish

  • Java is call by value or call by reference

    Hi! friends,
    I want to know,java is call by value and call by reference.
    Please give the the exact explanation with some example code.

    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.

  • FCC error :java.lang.Exception: Column value '   ' too long

    Hi all,
    I am using FCC on receiving File adapter...
    While executing i am getting this error in CC monitor
    com.sap.aii.af.ra.ms.api.RecoverableException: Exception in XML Parser (format problem?):'java.lang.Exception: Message processing failed in XML parser: 'java.lang.Exception: Column value '   ' too long (>1 for 2. column) - must stop',
    i searched in SDN but no luck till now..
    Plz help me out..
    Thanx in advance.

    Hi,
    Check ur FCC parameters,
    File content conversion sites
    /people/venkat.donela/blog/2005/03/02/introduction-to-simplefile-xi-filescenario-and-complete-walk-through-for-starterspart1
    /people/venkat.donela/blog/2005/03/03/introduction-to-simple-file-xi-filescenario-and-complete-walk-through-for-starterspart2
    /people/arpit.seth/blog/2005/06/02/file-receiver-with-content-conversion
    /people/anish.abraham2/blog/2005/06/08/content-conversion-patternrandom-content-in-input-file
    /people/shabarish.vijayakumar/blog/2005/08/17/nab-the-tab-file-adapter
    /people/venkat.donela/blog/2005/03/02/introduction-to-simplefile-xi-filescenario-and-complete-walk-through-for-starterspart1
    /people/venkat.donela/blog/2005/03/03/introduction-to-simple-file-xi-filescenario-and-complete-walk-through-for-starterspart2
    /people/venkat.donela/blog/2005/06/08/how-to-send-a-flat-file-with-various-field-lengths-and-variable-substructures-to-xi-30
    /people/anish.abraham2/blog/2005/06/08/content-conversion-patternrandom-content-in-input-file
    /people/shabarish.vijayakumar/blog/2005/08/17/nab-the-tab-file-adapter
    /people/jeyakumar.muthu2/blog/2005/11/29/file-content-conversion-for-unequal-number-of-columns
    /people/shabarish.vijayakumar/blog/2006/02/27/content-conversion-the-key-field-problem
    /people/michal.krawczyk2/blog/2004/12/15/how-to-send-a-flat-file-with-fixed-lengths-to-xi-30-using-a-central-file-adapter
    /people/arpit.seth/blog/2005/06/02/file-receiver-with-content-conversion
    http://help.sap.com/saphelp_nw04/helpdata/en/d2/bab440c97f3716e10000000a155106/content.htm
    Regards,
    Phani.
    Reward points if Helpful

  • Different behaviour ABAP vs JAVA Runtime for mixed value in total row

    Hello to all
    (BW 7.01 Support package 08)
    I hope you may have anr good idea on my issue as I couldn't find anything in OSS messages or other source to solve the issue.
    Description:
    I have a query ,where we calculate sales variance ( current versus prior year) over several countries. Country is shown in row, where so the key figures (3x)  current sales, prior sales and sales variance is displayed in columns.
    Issue:
    Current and prior sales is not  displayed on 'overall result' as the sum over all countries is a mixed value of different currencies and therefore is displayed as * value. This is totally correct.
    However sales variance is displayed differently in ABAP Web runtme to JAVA WEB runtime
    ABAP Web runtime -> mixed value is displayed as * value
    JAVA Web runtime -> mixed values is calculated and displayed regardless of mixed currencies
    So please let me know, if anyone had the same experience and would have a nice solution or hint for that issue
    Best regards
    Christian

    Hi Christian,
    Did you check the display options in your Qurey Designer?
    If you don't find, please use T-code RSRT may be you may find a helpful option.
    Concerning the display of currencies, I think that you need to configure a parameter in T-Code SPRO.
    finally, the support package 08 of you BW version is old, may be you need to upgrade it.
    In my society, we resolved many issues by updating our support packages.
    But ask your administrators about consequences before making it.
    Hope it helps,
    Best Regards,
    Amine

  • Java.sql.SQLException: Refcursor value is invalid

    Hi,
    I faced this exception. The exception does not always happen, so it is not
    easy to find solution.
    javax.jdo.JDODataStoreException: java.sql.SQLException: Refcursor value is
    invalid [code=17442;state=null]
    NestedThrowables:
    java.sql.SQLException: Refcursor value is invalid
         at
    com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwDataStore(SQLExceptions.java:23)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.initialize(JDBCStoreManager.java:254)
         at
    com.solarmetric.kodo.runtime.StateManagerImpl.loadInitialState(StateManagerImpl.java:112)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.getObjectByIdFilter(PersistenceManagerImpl.java:859)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.getObjectById(PersistenceManagerImpl.java:764)
    Usually, it happens after web application, WAR file, is deployed on the
    Tomcat server.
    After the exception is occurred, Tomcat server is restarted manually. Then
    the exception never happens.
    Do you have any clue?
    My Env:
    Apache 1.3 & Tomcat 1.4.x
    MVC2 Model with Struts
    Oracle 8i database
    Thanks.

    Brient-
    Can you post the complete stack trace (as well as all the nested
    exceptions)?
    In article <cpqh8p$3nr$[email protected]>, Brient Oh wrote:
    Hi,
    I faced this exception. The exception does not always happen, so it is not
    easy to find solution.
    javax.jdo.JDODataStoreException: java.sql.SQLException: Refcursor value is
    invalid [code=17442;state=null]
    NestedThrowables:
    java.sql.SQLException: Refcursor value is invalid
         at
    com.solarmetric.kodo.impl.jdbc.runtime.SQLExceptions.throwDataStore(SQLExceptions.java:23)
         at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.initialize(JDBCStoreManager.java:254)
         at
    com.solarmetric.kodo.runtime.StateManagerImpl.loadInitialState(StateManagerImpl.java:112)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.getObjectByIdFilter(PersistenceManagerImpl.java:859)
         at
    com.solarmetric.kodo.runtime.PersistenceManagerImpl.getObjectById(PersistenceManagerImpl.java:764)
    Usually, it happens after web application, WAR file, is deployed on the
    Tomcat server.
    After the exception is occurred, Tomcat server is restarted manually. Then
    the exception never happens.
    Do you have any clue?
    My Env:
    Apache 1.3 & Tomcat 1.4.x
    MVC2 Model with Struts
    Oracle 8i database
    Thanks.
    Marc Prud'hommeaux
    SolarMetric Inc.

  • Bug? java.sql.SQLException: No value specified for parameter 1

    ENV: Jdev1012+JHS1012(evaluation version)+MySql5.0 Or ORACLE 10.1.2
    ERR INFO:
    20:42:22 DEBUG (JhsDataAction) -Executing action /main
    20:42:22 DEBUG (JhsDataAction) -Created searchBean map and stored on session
    20:42:22 DEBUG (JhsDataAction) -Created new searchBean for SysRoleFirstLevelFuncUIModel and added to quick search bean map
    20:42:22 DEBUG (JhsDataAction) -Stored searchBean for SysRoleFirstLevelFuncUIModel on request
    [red]
    20:42:22 DEBUG (JhsDataAction) -ViewObject SysRoleFirstLevelFuncView1: value of bind param 0 set to S001
    20:42:22 DEBUG (JhsDataAction) -ViewObject SysRoleFirstLevelFuncView1: executing query, bind parameter values have changed
    05/11/22 20:42:23 java.sql.SQLException: No value specified for parameter 1[red]
    05/11/22 20:42:23      at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:1253)
    05/11/22 20:42:23      at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:1201)
    05/11/22 20:42:23      at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:966)
    05/11/22 20:42:23      at oracle.jbo.server.QueryCollection.buildResultSet(QueryCollection.java:691)
    05/11/22 20:42:23      at oracle.jbo.server.QueryCollection.executeQuery(QueryCollection.java:547)
    05/11/22 20:42:23      at oracle.jbo.server.ViewObjectImpl.executeQueryForCollection(ViewObjectImpl.java:3354)
    05/11/22 20:42:23      at oracle.jbo.server.ViewRowSetImpl.execute(ViewRowSetImpl.java:667)
    05/11/22 20:42:23      at oracle.jbo.server.ViewRowSetImpl.executeQueryForMasters(ViewRowSetImpl.java:773)
    05/11/22 20:42:23      at oracle.jbo.server.ViewRowSetImpl.executeQuery(ViewRowSetImpl.java:710)
    05/11/22 20:42:23      at oracle.jbo.server.ViewObjectImpl.executeQuery(ViewObjectImpl.java:3294)
    05/11/22 20:42:23      at oracle.adf.model.bc4j.DCJboDataControl.executeIteratorBindingIfNeeded(DCJboDataControl.java:803)
    05/11/22 20:42:23      at oracle.adf.model.binding.DCIteratorBinding.executeQueryIfNeeded(DCIteratorBinding.java:1587)
    05/11/22 20:42:23      at oracle.adf.model.binding.DCBindingContainer.refreshControl(DCBindingContainer.java:1544)
    05/11/22 20:42:23      at oracle.jheadstart.controller.strutsadf.action.JhsDataAction.applyIterBindParams(JhsDataAction.java:2785)
    05/11/22 20:42:23      at oracle.jheadstart.controller.strutsadf.action.JhsDataAction.prepareModel(JhsDataAction.java:3136)
    05/11/22 20:42:23      at oracle.adf.controller.struts.actions.DataAction.prepareModel(DataAction.java:486)
    05/11/22 20:42:23      at oracle.adf.controller.lifecycle.PageLifecycle.handleLifecycle(PageLifecycle.java:105)
    05/11/22 20:42:23      at oracle.adf.controller.struts.actions.StrutsUixLifecycle.handleLifecycle(StrutsUixLifecycle.java:70)
    05/11/22 20:42:24      at oracle.adf.controller.struts.actions.DataAction.handleLifecycle(DataAction.java:223)
    05/11/22 20:42:24      at oracle.jheadstart.controller.strutsadf.action.JhsDataAction.handleLifecycle(JhsDataAction.java:389)
    05/11/22 20:42:24      at oracle.adf.controller.struts.actions.DataAction.execute(DataAction.java:155)
    05/11/22 20:42:24      at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
    05/11/22 20:42:24      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
    05/11/22 20:42:24      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)
    05/11/22 20:42:24      at oracle.jheadstart.controller.strutsadf.JhsActionServlet.process(JhsActionServlet.java:127)
    05/11/22 20:42:24      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:527)
    05/11/22 20:42:24      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    05/11/22 20:42:24      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    05/11/22 20:42:24      at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
    05/11/22 20:42:24      at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
    05/11/22 20:42:24      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:663)
    05/11/22 20:42:24      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
    05/11/22 20:42:24      at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:222)
    05/11/22 20:42:24      at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
    05/11/22 20:42:24      at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
    05/11/22 20:42:24      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    05/11/22 20:42:24      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1485)
    05/11/22 20:42:24      at oracle.jheadstart.controller.strutsadf.JhsActionServlet.process(JhsActionServlet.java:127)
    05/11/22 20:42:24      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:527)
    05/11/22 20:42:24      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    05/11/22 20:42:24      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    05/11/22 20:42:24      at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:65)
    05/11/22 20:42:24      at oracle.security.jazn.oc4j.JAZNFilter.doFilter(Unknown Source)
    05/11/22 20:42:24      at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
    05/11/22 20:42:24      at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:239)
    05/11/22 20:42:24      at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)
    05/11/22 20:42:24      at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:239)
    05/11/22 20:42:24      at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:20)
    05/11/22 20:42:24      at oracle.jheadstart.controller.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:172)
    05/11/22 20:42:24      at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:659)
    05/11/22 20:42:24      at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:330)
    05/11/22 20:42:24      at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:830)
    05/11/22 20:42:24      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:285)
    05/11/22 20:42:24      at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:126)
    05/11/22 20:42:24      at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
    05/11/22 20:42:24      at java.lang.Thread.run(Thread.java:534)
    the SQL for my VO is :
    SysRoleFirstLevelFuncView :
    SelectList="SysTabFunction.id,
    SysTabFunction.name,
    SysTabFunction.address,
    SysTabFunction.parent_func,
    SysTabRoleRight.ROLE_ID,
    SysTabRoleRight.FUNC_ID,
    SysTabFunction.disp_order"
    FromList="SYS_TAB_FUNCTION SysTabFunction, SYS_TAB_ROLE_RIGHT SysTabRoleRight"
    Where="SysTabFunction.Level=1 and SysTabFunction.id=SysTabRoleRight.FUNC_ID And SysTabRoleRight.Access_Type='Y' And SysTabRoleRight.Role_Id=?
    the Action In my struts-config.xml is :
    <action path="/main" input="/WEB-INF/page/main.uix" type="oracle.jheadstart.controller.strutsadf.action.JhsDataAction" className="oracle.jheadstart.controller.strutsadf.action.JhsDataActionMapping" parameter="/WEB-INF/page/main.uix" name="DataForm" unknown="false">
    <set-property property="modelReference" value="SysRoleFirstLevelFuncUIModel"/>
    ]red]<set-property property="bindParams" value="SysRoleFirstLevelFuncTreeIterator=${sessionScope.UserInfo.roleId}"/>[red] <forward name="SysRoleSecondLevelFunc2" path="/StartSysRoleSecondLevelFunc2.do"/>
    </action>
    we can find the parameter is set in the error message.is it a bug?
    thanks in advance
    best regards.

    Guo,
    I see a question mark in the sql statement, instead of the Oracle-style bind parameter notation which would be ":1". Can you change your VO to use Oracle-Style bind params and see whether it works?
    Steven Davelaar,
    JHeadstart Team.

  • Java & Acces: pass boolean values

    Ok I'm totally new at this so the following text will hopefully be understandable. I hope you guys can give me a hand over here.
    The case:
    I'm making a java function that has to create a new user of my database. This user is supposed to get a name, a password and can have 4 functions (Administrator, Author, Reader, Coreader).
    To identify the 4 functions i used a checkbox in my database. So when the box is checked the person is a Admin/author/... Now I was wondering how i can use Java (using a query) to set these values checked or non-checked.
    I thought I'd use booleans, however, my compiler says there is a General Error (all the names of the columns are right, so that's not the deal, my database is working properly and such, ...)
    So here's my code:
    (note that i used these marks ' ' here for the booleans, i tried all kinds of things such as dropping them, using them, ... it doesn't seem the problem...)
    public void addNewUser(String username, String password, boolean admin, boolean author, boolean reader, boolean coreader)
    String query1 = "UPDATE user SET username = '" + username + "' AND password = '"
    + password + "' AND administrator = '" + admin + "' AND author ='" + author
    + "' AND reader ='" + reader + "' AND coreader ='" + coreader + "'";
    try
    stmt = global.createStatement();
    stmt.executeUpdate(query1);
    global.showMessage("The new user, " + username + ", has been added successfuly", "Succesfuly added");
    catch(Exception e)
    global.showError("An error has occured while connecting to the database" + e.toString(), "SQL Error");
    finally
    global.closeConnection();
    Hope you guys can help. Thanks a lot!

    It's possible to do this; it's just that your SQL syntax is completely wrong. An SQL UPDATE statement looks as follows:
    UPDATE table SET column1 = value1, column2 = value2, column3 = value3 WHERE expression
    You're using 'AND' instead of commas, which is the first thing that goes wrong. The second thing that goes wrong is that you're building the SQL statement from bits of string and values. This is a habit that many novice programmers use, and open the door wide for SQL injection attacks. I you do this sort of thing on a web site, you could end up with your customers' credit card details being exposed.
    But because you're just passing the boolean values into the string, they get expanded to a string value, hence TRUE or FALSE. However, because they are string literals, they should be surrounded by single quotes.
    This brings us to the third problem: you're using an UPDATE statement to insert a new record. Use an INSERT statement instead.
    It would be better to use a PreparedStatement. In this case, your code would look as follows:
    PreparedStatement stmt =
        global.prepareStatement( "INSERT INTO user " +
                "( username, password, administrator, author, reader, coreader ) " +
                "VALUES ( ?, ?, ?, ?, ?, ? )" );
        stmt.setString( 1, username );
        stmt.setString( 2, password );
        stmt.setBoolean( 3, admin );
        stmt.setBoolean( 4, author );
        stmt.setBoolean( 5, reader );
        stmt.setBoolean( 6, coreader );I have no idea whether this will work: I don't know Access, and booleans are not a standard feature of SQL. I also don't know whether Microsoft have created their own flavour of SQL, as they are wont to do with any standard.
    All in all, though, you have to really work on your SQL. Three major mistakes in such a simple piece of code means that you don't understand SQL syntax. You may copy and paste this for your assignment, but unless you understand what you're actually doing, you're going to run into trouble again very soon.
    - Peter

  • Can a java app pass values to a c-shell script?

    hello everyone,
    I'm running a shell script that executes a java app.
    I need to pass values from the java app to the shell script, such that I can code
    java myapp
    echo <value1>
    echo <value2>where value1 and value2 have been set in the app.
    is there a way to do this?
    Thanks for your help.
    Tom

    Wira, I've tried this, and can't get it to work. The
    problem may be that Runtime.getRuntime().exec() is
    running the script on a separate process(?), Yep.
    and I
    never see any output in the same context as the
    script that's running the java app.
    I've tried this from the command line as well, and I
    don't see any output from the script being called
    from the java app.
    I know the script is being run, because if I change
    the script name to a name that doesn't exist, I get
    an ioexception, when I change it back everything runs
    ok.
    Note that I'm testing this under XP with batch files;
    eventually it will run on unix.
    does that make a difference right now?Forget java for right now.
    Start working on a way for the script to hoist the values into itself.
    For example if the script calls another script which does the echo what happens?
    Or can you call another script, set some env variables, and then see them in the original script?

  • How can a Java prg pass data to a SAP table (TStpo)

    Hi All,
    I created a webservice using JAVA.
    Got WSDL for a SAP Funtional Module(CSAP_MAT_BOM_CREATE) and created Java Classes using (WSDL2Java -t XXX.wsdl ).
    While Invoking the service from Java Client program by Passing all the parameters.
    Error:Deserialisation failed
    Exception in thread "main" AxisFault
    faultCode: Client
    faultSubcode:
    faultString: Deserialisation failed
    faultActor:
    faultNode:
    faultDetail:
            SimpleTransformationFault:<
    MainName>/1BCDWB/WSS0080429093947734000</MainName><ProgName>/1BCDWB/WSS008042909
    3947734000</ProgName><Line>209 </Line><Valid>X</Valid><MatchFault><DescriptionTe
    xt>System expected the end of the element 'TStpo'</DescriptionText><TokenType>S<
    /TokenType><TokenName>ItemCateg</TokenName><TokenNameSpace/><TokenValue/></Match
    Fault><Caller><Class>CL_SRG_RFC_PROXY_CONTEXT</Class><Method>IF_SXML_PART~DECODE
    </Method><Positions>1 </Positions></Caller>
    Thanx ,
    Vijay

    Hi Venkat,
    I am passing the value to ItemCateg.. Pls see the portion of XML Sent below..!
    <TStpo xsi:type="ns2:StpoApi01" xmlns="" xmlns:ns2="urn:sap-com:document:sap:soap:functions:mc-style">
      <ItemCateg xsi:type="xsd:string">L</ItemCateg>
      <ItemNo xsi:type="xsd:string" />
      <Component xsi:type="xsd:string">PART008</Component>
      <CompQty xsi:type="xsd:string">1.0</CompQty>
      <CompUnit xsi:type="xsd:string">EA</CompUnit>
    <FixedQty xsi:type="xsd:string" />
      <ItemText1 xsi:type="xsd:string" />
      <ItemText2 xsi:type="xsd:string" />
      <Sortstring xsi:type="xsd:string" />
      <RelCost xsi:type="xsd:string" />
      <RelEngin xsi:type="xsd:string" />
      <RelPmaint xsi:type="xsd:string" />
    </TStpo>
    Thanx,
    Vijay

  • Runtime.getRuntime().exec(java method); - Passing strings between methods

    Hi all,
    I am using Runtime.getRuntime().exec(java xxxxxx); to run a java program from within a java program, i also need to pass a string to the new program. Does anyone know how to do this?
    Matt

    how would i retrive those strings in myApp as i want
    to put the values from them in a JLabelYou have a main method like this, right?
    public static void main(String[] args) { ... }
    args contains the array of strings passed to the app from the command line.

  • Java EXE - Passing Attributes

    Hi,
    I have a java application that performs many functions. I have compiled this application into an exe file. I would like to automate things.
    E.g. using Windows Scheduler to run the app at 2am - execute function1, 4am - execute funtion2. etc..
    Is it possible to pass an attribute to the exe when executing so that the function can be executed automatically.
    At the moment, I am creating 5 different exe files, each one is essentially the same application, but starts at different functions. I would therefore like to simplify this into one app.
    Thanks in advance
    Regards
    Angus

    I am not sure what tool you are using to generate your exe from your java byte code, but i would assume that it would pass variables given with the exe to the java program and as such you can just extract the variable from the args[] string array in your main method.
    i.e.
    "program.exe -func1"
    passes it to your public static void main (String args[])
    so just get the variable from the args array.
    As i have said, since i dont know how your java -> exe tool works this is just a suggestion.

  • Scripting in Java 6: Passing parameters to a factory

    Dear forum members,
    Since recently I am enjoying the new scripting facilities of Java 6. I like the idea of having factory engines. But I am surprised that there is no (obvious) way to pass parameters to the engine. The class javax.script.ScriptEngineFactory does not offer a setParameter method. I wonder how the ScriptEngine.ARGV variable may be initialized without such a facility.
    I think that a good shortcoming is to add a method setGlobalParameters to a ScriptEngineFactory.
    Did I miss anything?
    Regards,
    Alexandre

    Yes, in our case the parameters are not dependent on the datasource.  We wanted to place some of the report setup (setting up page headers, parameter, etc) in a separate thread, independent of the function that gathers our data, to speed up the report processing.

  • Running batch files thraugh java by passing parameters

    Hi
    I want to run a batch file by passing some parameters.
    Eg: copy.bat "D:\live\hoe.txt" "D:\test"
    while doing this from command prompt its working and i have written some java code for running this batch file.
    String live="D:\\live\\how.txt";
    String test="D:\\test";
    String bat="D:\\copy.bat";
    String[] command = new String[3];
    command[0] = bat;
    command[1] = live;
    command[2] = test;
    try {
    Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    but this time its not copying the file;
    Please help.

    Just another cross poster.
    [http://www.java-forums.org/new-java/15005-running-batch-files-thraugh-java-passing-parameters.html]
    db

Maybe you are looking for

  • Error In Running dbms_scheduler.run_job ORA-27369.

    Dear Sir I am trying to execute one batch file from one schedule which imports the data using imp command now my files look like this *****************imp.bat *************** imp treasury/tisnic@orcl FILE="C:\data\gis031164.dmp" LOG="C:\data\imp_gis0

  • CCM 2.0 Catalogue Extract

    Hi, I would need to get an extract of the Supplier Catalog and Procurement Catalog. I know that pressing the button Export Schema in the CAT I can get just the schema of the catalog, but not the content part. Is there any possibility to get an extrac

  • Where do i change the heap size?

    have the application installed and functional, most setup is complete. When i'm working with the application we have running on the app server, i am only able to work for around 30 minutes before heap errors prevent further use with the site. where d

  • AS–ColdFusion confusion

    FB4, so far, so good. I like the new easy features for styling and skinning without having to sign up for a course at NASA. But I am still a little lost with the new ways of connecting Flex to back-end services, so this might be a dumb question: In F

  • Has JavaServer Faces reached beta?

    I know---please forgive my sarcasm. (I'm sure you've been at this point, too, in your programming career. I'll just vent a little.) I've only spent several days trying to create a simple page I could have coded in a couple of hours in any given langu