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.

Similar Messages

  • Java function call from Trigger in Oracle

    Moderator edit:
    This post was branched from an eleven-year-old long dead thread
    Java function call from Trigger in Oracle
    @ user 861498,
    For the future, if a forum discussion is more than (let's say) a month old, NEVER resurrect it to append your new issue. Always start a new thread. Feel free to include a link to that old discussion if you think it might be relevant.
    Also, ALWAYS use code tags as is described in the forum FAQ that is linked at the upper corner of e\very page. Your formulae will be so very much more readable.
    {end of edit, what follows is their posting}
    I am attempting to do a similar function, however everything is loaded, written, compiled and resolved correct, however, nothing is happening. No errors or anything. Would I have a permission issue or something?
    My code is the following, (the last four lines of java code is meant to do activate a particular badge which will later be dynamic)
    Trigger:
    CREATE OR REPLACE PROCEDURE java_contact_t4 (member_id_in NUMBER)
    IS LANGUAGE JAVA
    NAME 'ThrowAnError.contactTrigger(java.lang.Integer)';
    Java:
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "ThrowAnError" AS
    // Required class libraries.
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import com.ekahau.common.sdk.*;
    import com.ekahau.engine.sdk.*;
    // Define class.
    public class ThrowAnError {
    // Connect and verify new insert would be a duplicate.
    public static void contactTrigger(Integer memberID) throws Exception {
    String badgeId;
    // Create a Java 5 and Oracle 11g connection.
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    // Create a prepared statement that accepts binding a number.
    PreparedStatement ps = conn.prepareStatement("SELECT \"Note\" " +
    "FROM Users " +
    "WHERE \"User\" = ? ");
    // Bind the local variable to the statement placeholder.
    ps.setInt(1, memberID);
    // Execute query and check if there is a second value.
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
    badgeId = rs.getString("Note");
    // Clean up resources.
    rs.close();
    ps.close();
    conn.close();
    // davids badge is 105463705637
    EConnection mEngineConnection = new econnection("10.25.10.5",8550);
    mEngineConnection.setUserCredentials("choff", "badge00");
    mEngineConnection.call("/epe/cfg/tagcommandadd?tagid=105463705637&cmd=mmt%203");
    mEngineConnection.call("/epe/msg/tagsendmsg?tagid=105463705637&messagetype=instant&message=Hello%20World%20from%20Axium-Oracle");
    Edited by: rukbat on May 31, 2011 1:12 PM

    To followup on the posting:
    Okay, being a oracle noob, I didn't know I needed to tell anything to get the java error messages out to the console
    Having figured that out on my own, I minified my code to just run the one line of code:
    // Required class libraries.
      import java.sql.*;
      import oracle.jdbc.driver.*;
      import com.ekahau.common.sdk.*;
      import com.ekahau.engine.sdk.*;
      // Define class.
      public class ThrowAnError {
         public static void testEkahau(Integer memberID) throws Exception {
         try {
              EConnection mEngineConnection = new EConnection("10.25.10.5",8550);
         } catch (Throwable e) {
              System.out.println("got an error");
              e.printStackTrace();
    }So, after the following:
    SQL> {as sysdba on another command prompt} exec dbms_java.grant_permission('AXIUM',"SYS:java.util.PropertyPermission','javax.security.auth.usersubjectCredsOnly','write');
    and the following as the user
    SQL> set serveroutput on
    SQL> exec dbms_java.set_output(10000);
    I run the procedure and receive the following message.
    SQL> call java_contact_t4(801);
    got an error
    java.lang.NoClassDefFoundError
         at ThrowAnError.testEkahau(ThrowAnError:13)
    Call completed.
    NoClassDefFoundError tells me that it can't find the jar file to run my call to EConnection.
    Now, I've notice when I loaded the sdk jar file, it skipped some classes it contained:
    c:\Users\me\Documents>loadjava -r -f -v -r "axium/-----@axaxiumtrain" ekahau-engine-sdk.jar
    arguments: '-u' 'axium/***@axaxiumtrain' '-r' '-f' '-v' 'ekahau-engine-sdk.jar'
    creating : resource META-INF/MANIFEST.MF
    loading : resource META-INF/MANIFEST.MF
    creating : class com/ekahau/common/sdk/EConnection
    loading : class com/ekahau/common/sdk/EConnection
    creating : class com/ekahau/common/sdk/EErrorCodes
    loading : class com/ekahau/common/sdk/EErrorCodes
    skipping : resource META-INF/MANIFEST.MF
    resolving: class com/ekahau/common/sdk/EConnection
    skipping : class com/ekahau/common/sdk/EErrorCodes
    skipping : class com/ekahau/common/sdk/EException
    skipping : class com/ekahau/common/sdk/EMsg$EMSGIterator
    skipping : class com/ekahau/common/sdk/EMsg
    skipping : class com/ekahau/common/sdk/EMsgEncoder
    skipping : class com/ekahau/common/sdk/EMsgKeyValueParser
    skipping : class com/ekahau/common/sdk/EMsgProperty
    resolving: class com/ekahau/engine/sdk/impl/LocationImpl
    skipping : class com/ekahau/engine/sdk/status/IStatusListener
    skipping : class com/ekahau/engine/sdk/status/StatusChangeEntry
    Classes Loaded: 114
    Resources Loaded: 1
    Sources Loaded: 0
    Published Interfaces: 0
    Classes generated: 0
    Classes skipped: 0
    Synonyms Created: 0
    Errors: 0
    .... with no explanation.
    Can anyone tell me why it would skip resolving a class? Especially after I use the -r flag to have loadjava resolve it upon loading.
    How do i get it to resolve the entire jar file?
    Edited by: themadprogrammer on Aug 5, 2011 7:15 AM
    Edited by: themadprogrammer on Aug 5, 2011 7:21 AM
    Edited by: themadprogrammer on Aug 5, 2011 7:22 AM
    Edited by: themadprogrammer on Aug 5, 2011 7:23 AM
    Edited by: themadprogrammer on Aug 5, 2011 7:26 AM

  • Java programming language uses call by reference for objects?

    Is Java programming language uses call by reference for objects?

    Yes. You make calls to an object via itsreference.
    No.Yes, you're referring to passing a reference into a
    method in which case the value of the
    reference is passed.I believe the OP is using the term "call by reference" to mean "pass by reference." The two are interchangable, AFAIK. So, while "making calls to an object via its reference" is correct, I don't believe it's germane to the question.

  • Can Java Applet Call the ASP Page

    Hi,
    I would like to know whether the Java Applet can call the ASP page.
    If it can be done, how does the Java Applet get the value from ASP page?
    Please provide me some running example.
    Thanks.

    I would like to know whether the Java Applet can
    an call the ASP page.Something like:
    AppletContext.showDocument(new URL("http://wherever/myPage.asp"), "_blank");
    how does the Java Applet get the value from ASP page?What?
    Please provide me some running example.Nope.

  • How advantages of "Call By Reference" can be implemented using Java

    As I know that java doesnot support "Call By Reference" as C++
    does.
    I want to know that how advantages of Call by Reference can be
    implemented using Java.

    There is some misunderstanding here. Method arguments in Java are passed by value. However, if you pass a reference (to an object) by value, you can still modify the object that the (copy of the) reference points to.
    public void method1() {
      StringBuffer buf = new StringBuffer();
      // Here, method2 cannot change the value of the variable buf,
      // but it can modify the object that buf points to.
      method2(buf);
    public void method2(StringBuffer sb) {
      // You can modify the StringBuffer.
      sb.append("hello");
      // But this is useless, it will not change the variable buf
      // in the calling method.
      sb = new StringBuffer();
    }Jesper

  • Java Applet call javascript problem

    Hi I have a web page as follow and embedded a applet. The applet call the java script, and instead of showing an alarm, the browser show the javascript code. Is that strange ? Any suggestion for this problem.
    HTML:
    ================================================================
    <HTML>
         <HEAD>
         function ShowEmbd()
              alert("Test Applet call Javascript");
         </SCRIPT>
         </HEAD>
         <BODY>
         <FORM NAME="AppletEmbdStart">
              <OBJECT classid="clsid:48B2DD7B-6B52-4DB0-97C9-ECB940113B47" id="CIVON_DEmbdObj" width="0" height="0"></OBJECT>
              <APPLET code="MyApplet.class" width="0" height="0"></APPLET>
         </FORM>
         </BODY>
    </HTML>MyApplet.java
    =========================================================================
    import netscape.javascript.*;
    public class MyApplet extends javax.swing.JApplet
         private JSObject m_win = null;
         private JSObject m_doc = null;
         public void init()
              getJSWin().call("ShowEmbd", null);
         private getJSDoc()
              if(m_doc == bull)
                   m_doc = (JSObject) getJSWin().getMember("document");
              return m_doc;
         private JSObject getJSWin()
              if (m_win == null)
                   m_win = netscape.javascript.JSObject.getWindow(this);
              return m_win;
    }The page was load and it should call the applet MyApplet. The MyApplet should do the init() method and call the Javascript "ShowEmbd()", BUT, instead of show alert from ShowEmbd(), the browser show the code of ShowEmbd() itself ...... It did not run the javascript and shows the alert ??
    The browser shows a message from status bar "The applet not initial" ???? why ???
    Can anyone help ?!

    On first look:
    I am not sure about the Object Tag, but the Applet Tag requires the MAYSCRIPT attribute before Java can call Javascript.

  • Using java to call a text file

    I am new to java and was wondering if there is a way of using java to call a text file on my server and use it to create a webpage using a template. Namely to click a link to a poem, and have the java automatically create a page from a text file of the poetry. I need to know if this is even possible, what I would need to look into, (IE: which software or applet to look for), and if there are any sites that anyone knows about that I could learn how to do this. currently I am having to create a page for every poem posted on my site, which takes a great deal of time, and I would like to speed the process up a bit if it is possible. Any suggestions would be greatly appreciated.

    Why a text file? I don't think it is a best practice of doing that. Just use a database, keep your poem collections there, and set up a jsp page that seek the database, and then display it on another jsp page. I guess you can find similar application in the sample projects provided by JSC.

  • Why java is called java2

    why java is called java2 and another thing that i would like to know is why it was renamed to java from its previous name OAK
    Thanx
    Manish

    why java is called java2Not to sure about this one, but I think it was a marketing decision - I guess 'Welcome to the Java 2 platform' sounds better than saying 'Welcome to the JDK 1.2.1 platform' :=)
    and another thing that i
    would like to know is why it was renamed to java from
    its previous name OAKThere was already a patented product named 'OAK', so they had to rename it to something else to avoid the law.
    >
    Thanx
    ManishA brief history of Java:
    http://java.sun.com/features/1998/05/birthday.html
    http://www.ils.unc.edu/blaze/java/javahist.html

  • Why java is called pure object oriented.

    i know that java is called as pure object oriented language.
    why it is called so even though it has primitive datatypes and also it doesnot support multiple inheritance completely. it only supports in the case of interfaces but not in the case of classes. then why it is called pure object oriented.

    Its because you cannot write an executable java program without creating an object. Well, you can:
    public class a
      public static void main( String a[] )
    }In contrary to C++, there can be no variables or functions in the wild (outside a class).
    You can not create an executable java program without creating a class (but not forcibly its instance, an object.)
    The "pure object oriented" wording in this sense has not really much importance, it is rather a marketing ploy.

  • Why java is called as true object oriented language?

    HI Friends,
    Though few oops concepts is not supported , why java is called as truly object oriented language and C++ as not a purely object oriented language???? Please, if any one know , give me the answer.
    Thanks to all.

    few oops concepts is not supportedwhich concepts?
    as far as i know...to be OO, you must supports
    encapsulation, abstraction, inheritancxe, composition (aggretration, et all) and polymorphism. Java supports all those comcept..now..Java is a hybrid due to what Jverd has pointed out.
    the only pure OO language that i know of is SmallTalk. they have Meta class that can create Class object. and all their primitaives are object.
    C# comes close, but their Class are not object.

  • Why java is called platform independent

    Hello
    Why java is called as platform independent?Any body please give a detailed explanation since im a beginner to java technology.
    ThankYou
    Jk

    BigDaddyLoveHandles wrote:
    georgemc wrote:
    SunFred wrote:
    Java is not platform independent since it depends on the Java platform ;)Don't complicate matters!I always thought the phrase should have been "platform agnostic"It's a phrase I've used meself

  • Need help with Java script calling an html page

    Hello -
    I have a bunch of web pages, that call a java script called "header.js". The "header.js" puts a header on the top of each web page. In the Java script, I have a gif (picture) that displays a logo and if you click on it, it will send to you a different website.
    I'd like to replace this gif with an actual web page. So, the "header" would actually be a web page and not some gif.
    Below is a snippet of the code and I'd like to replace the highlighted section with a web page called "header.html". I don't even know if this is possible.
    Can anyone tell me what I need to do? I know pretty much nothing about Javascripting so please be as detailed as you can. Thanks!
    /* Common header across all pages... */
    document.write('            <div id="header" class="clearfix">');
    document.write('                            <div id="left" class="float_left">');
    document.write('                                            <div id="logo"><a href="http://www.xyz.com/" onclick="window.open(this.href);return false;" onkeypress="window.open(this.href);return false;" target=_blank><img src="/images/xyz.gif" width="105" height="75" alt="" border="0" /></a></div>');
    document.write('                                            <div id="mainNav" class="clearfix"> ');
    document.write('                                                             <ul>');
    //document.write('                                                                         <li id="nav_controls"><a href="controls.html">Controls</a></li>');
    document.write('                                                                              <li id="nav_motion"><a href="motion.html">Motion</a></li>');
    document.write('                                                                              <li id="nav_sensor"><a href="sensor.html">Sensor</a></li>');
    document.write('                                                                              <li id="nav_encoder"><a href="encoder.html">Encoder</a></li>');
    document.write('                                                                              <li id="nav_system"><a href="system.html">System</a></li>');
    //document.write('<!--                                                                  <li id="nav_logs"><a href="#">Logs</a></li> -->');
    document.write('                                                             </ul>');
    document.write('                                            </div>');
    document.write('                            </div>');
    document.write('                            <div id="right" class="float_left">');
    document.write('                                            <div id="controls">');

    Well, the problem with this is that I'm not an expert on SSI and I really know nothing about javascripting...so I'm afraid of breaking the whole web site and also having to modify all the web pages that call this header.
    I'll have to read up on server side include...cause I don't know much about it.
    If I could do what I want with this "header.js", it would be a lot easier.

  • Debug java class called from CF?

    I'm experiencing different behaviour with a Java class called from a CF page to the same class called directly from Java code.
    Is it possible for me to step into the Java class and debug it in CF builder if I attach the correct Java source?
    Pressing F5 (step-in) on the line that the method is called just skips straight over.
    Regards,
    Andy

    P5music wrote:
    I would like to be able to make a java application that has a GUI that is a rich web page.That's what applets are for.
    In this case, this page exists on my system and I can open it with my browser.
    This page does many things that are typical of a web page like displaying information and presenting rich and graphical controls
    but some of this controls are connected to a java application, launched from the web page or viceversa.I don't get this "launched from the web page" business. Is that a requirement or are you describing an existing system? Or are you describing somebody else's system whose architecture you want to imitate? Or are you using the word "launched" simply to describe the action of starting an applet?
    It still isn't clear to me what you are trying to describe. But at any rate if you want a Java program to run in your browser, that's an applet. Note that applets can interact with Javascript code in the page they are embedded in. Or if you want to download a Java application which acts as a separate application, i.e. it still runs when the browser is closed, you can use Web Start for that.

  • Coldfusion Java API Call

    Hi,
    I use ColdFusion 7 which provides a nice interface to the java API classes. My knowledge of java is very limitted but I would like to know whether I can do the following:
    1)- from a webpage submit a file to be uploaded to the server;
    2)- on the server side (coldfusiuon) create a java function call which will determine the type of file the form is trying to uload onto the server and based on this restrict/allow th upload.
    That' s it.
    Ok, I can very easily do this with coldfusion alone but cold fusion cannot differentiate between an executable .EXE file and an encrypted .PGP file.
    It sees both as OCTET-STREAM data. Can java tell me which is what?
    If the answer is yes, could you point me to a good example/resource?
    Thank you.
    Adrian

    HTTP automatically sends the content-type and content-encoding information of the file to the server.
    You should be able to pick out that info from the server by asking for the headers or field data such as "content-type: text/plain" and "content-encoding: utf-8"
    Java's input stream reader will make a guess as to what the stream is if it isn't declared - but can be wrong.

  • Java project call ep webservice

    hi experts,
    i deployed a java  webservice including a simple function into EP engin,i created a java to call this webservice but can not success,the exception always is "(400)Bad Request"
    my code like
    public String mycal(String a, String b) {
              try {
                   String endpoint =
                        "http://xxx:80/WS_MyEMICalculator1/Config1?wsdl";
                   Service service = new Service();
                   Call call = (Call) service.createCall();
                   call.setTargetEndpointAddress(new java.net.URL(endpoint));
                   call.setOperationName("EMICalculation");
                   call.addParameter("a", XMLType.XSD_STRING, ParameterMode.IN);
                   call.addParameter("b", XMLType.XSD_STRING, ParameterMode.IN);
                   //call.setUseSOAPAction(true);
                   //call.setSOAPActionURI("?");
                   call.setReturnType(XMLType.XSD_STRING);
                   try {
                        String res = (String) call.invoke(new Object[] { a, b });
                   } catch (Exception ex) {
                        System.out.println(ex.toString());
                   } catch (Exception e) {}
              return "";
         public static void main(String[] args) {
              Wsdltest sd = new Wsdltest();
              sd.mycal("a", "b");
    it is possiable to get ep webservice for external java ?this uri should be set and how to get?//call.setSOAPActionURI("?");

    Hi,
    If you want to use the java file in the project then place the java in src folder with mention proper path in java file.
    then you can call in webdynpro methods.
    If you want seperate java application then you can go with interface controller with Development component(DC).
    Best Regards
    Arun Jaiswal

Maybe you are looking for

  • I have problems with Itunes Match on my Iphone4, It doesnt played any song and is allways on infinite skip!

    Please I need help I cant find anyway to deactivate IMatch on my Iphone 4. Its stucked on a loop of skipping songs on the cloud and even when the music its on the Iphone still doesnt played it. Driven me crazy, because I already turn off  Imatch on t

  • Is Verizon...

    Is verizon pushing the Droid X or something??? I log into my account and it says under neath my picture of my phone..  "order droid x" and I am NOT eligible for an upgrade but it seemed to be giving me upgrade pricing for the Droid X... I find that w

  • Weird OLAP Partition Error

    16:49:12 ***Error Occured in BUILD_DRIVER: In __XML_SEQUENTIAL_LOADER: In __XML_MNG_PARTITIONS: In __XML_MNG_REG_PARTITION: In __XML_CRT_REG_PARTITION_ITEM: AW_OWNER.AW_TEST!TEST_DIMENSION_3 appears more than once in the dimension list. (It is also a

  • "Use Preview Files" works in CS5.5 but is "Useless" in CS6

    I'm a heavy user of the "Use Previews Files" option when exporting files. This has worked great with Premiere CS5.5 but using the same method in CS6 no longer works and reverts back to rerendering the original files in the timeline and rerendering al

  • Managing table titles in FrameMaker 12 does not work

    I have a mysterious problem in FrameMaker 12. When creating a table I am not able to move the table title. When changing the setting to below or above or whatever and pressing Apply nothing happens. The feature works allright in FrameMaker 11. I have