Click here to Skip to main content
14,580,589 members
Rate this:
Please Sign up or sign in to vote.
See more:

can you please tell me what we use in java call by reference or call by value in java ?

Actually i take example.
package stringapp;

public class StringApp {

     * @param args the command line arguments
    public static void main(String[] args) {
        String ss="Naveen";
         change (ss);
        // TODO code application logic here
    public static void change(String p){

When i take string then call change method after that i print string it will show same "naveen";

But when i take StringBuilder instand of string it will print "naveensharma"
Why ?

why string byilder print naveen sharma ? it call by reference?

[Edit]Code block added[/Edit]
Updated 19-May-13 7:53am
Rate this:
Please Sign up or sign in to vote.

Solution 2

Only by value, in all cases.

This Java limitation is compensated by the fact that most types are reference types. When you pass a primitive type, such as number, you cannot modify the value passed by a caller. If you modify the method parameter, you modify only the value of the copy on stack, and the caller still have the same original value.

Exactly the same happens with reference type, in this case, you cannot modify the reference itself. But you still can modify the referenced object my using some of its members. Say, if you modify some field of referenced object, you don't modify the reference, but modify the object itself. The called code will get the same object (reference), but modified.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100