0
public class HelloWorld{

    static class Sample {
        private String n;

        public Sample(String n){
            this.n = n;
        }

        public String toString(){
            return n;
        }
    }
     public static void main(String []args){
        Sample k = new Sample("A");
        System.out.println(k);
        stuff(k);
        System.out.println(k);
     }

     public static void stuff(Sample k){
         k = new Sample("B");
     }
}

Why does this print AA instead of AB? I came across this from a video about C#, but apparantly java also has it.

ckarakoc
  • 45
  • 4

1 Answers1

1

its happen because you are create stuff method as static. other wise it will work.

Use this code for print AB.

public class HelloWorld{

    static class Sample {
        private String n;

        public Sample(String n){
            this.n = n;
        }

        public String toString(){
            return n;
        }
    }
     public static void main(String []args){
        Sample k = new Sample("A");
        System.out.println(k);
        k=stuff(k);
        System.out.println(k);
     }

     public static Sample stuff(Sample k){
         return new Sample("B");
     }
}
Ajmal Muhammad
  • 685
  • 7
  • 25