• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Please explain me answer. (static)

 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test14{
static String s ="Instance";
public static void method(String s){
s+="Add";
}
public static void main(String a[]){
Test14 t = new Test14();
s = "New Instance";
String s = "Local";
method(s);
System.out.println(s);
System.out.println(t.s);
}
}
What is output?

1 Local Instance
2 Local New Instance
3 Loca Add New Instance
4 Compiler Error

Answer : -------------------------
Local New Instance

Please explain me answer.

Pankaj Shinde
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Pankaj

In the above code
as we know that String is immutable
so what ever manipulations done in method

public static void method(String s){
s+="Add";
}

will not effect what ever is done on the object passed .
and when you say
s = "New Instance";

you are actually changing the value of static variable of class Test14
and
String s = "Local";
the concept is called shadowing.

and when either of the value is passed thru your "method" method won't affect cause of String immutability.
and after that
System.out.println(s);
System.out.println(t.s);

s will print it's value which is Local
and t.s will print it's value which is New Instance.

so the output is Local New Instance

I hope I cleared your doubt

Thanks
Charandeep
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This particular link has got the clear explanation for the same.

Hope it helps!
 
I knew I would regret that burrito. But this tiny ad has never caused regrets:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic