StringBuffer method parameter - doesn't change value [duplicate] - java

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I know that String is immutable and it's value can't be changed, but why does the value of the below StringBuffer doesn't change when sent like a method parameter. From my understanding it should have changed with the new value "bb". Thank you for your help.
class Ideone {
public static void main (String[] args) {
String s = "aa";
StringBuffer sb = new StringBuffer("aa");
modify(s, "bb");
modify2(sb, "bb");
System.out.println(s);
System.out.println(sb);
}
public static void modify(String s, String ss) {
s = ss;
}
public static void modify2(StringBuffer sb, String ss) {
sb = new StringBuffer(ss);
}
}

The universal rule in Java is that you cannot change the reference of an object passed into a method, but you can change its contents.
public static void modify2(StringBuffer sb, String ss){
This method takes a copy of a reference to a StringBuffer. Changing that reference to point to an object has no effect whatsoever on the original object. But if you implemented it as
sb.clear();
sb.append(ss);
then it would work.
Again, the rule is that reassigning an object passed into a method with = does nothing to the original object, but you can change the contents of that object just fine.

Related

Why I can't printout value from main method? [duplicate]

This question already has answers here:
Calling Non-Static Method In Static Method In Java [duplicate]
(14 answers)
Closed 2 years ago.
//I'd like to now why I can;t printout the return value in below java code
public class client08 {
public static void main(String[] args) {
String w=test();
System.out.println(w);**// I'd like to print out the return value here but it now work**
}
public String test() {
String result="";
String[] words=new String[5];
words[0]="Amy";
words[2]="Tom";
words[4]="Jane";
for(int i=0; i<words.length;i++) {
if(words[i]!=null) {
result=words[i].toUpperCase();
}else {
result="null";
}
}
return result;
}
First of all class names should start with an upper case character. Learn and follow Java conventions.
Next:
Your code doesn't compile.
You can't invoke a method from your "client08" class unless you create an instance of the class or make the method static.
So the code should be:
//String w=test();
client08 client = new client08();
String w= client.test();
Or you need to make the method static:
public static String test() {
Then you would invoke the method using:
String w = client08.test();
System.out.println(w);

How can I get a string passed from main function to another function back again to main after processing the string? [duplicate]

This question already has answers here:
What does "void" mean as the return type of a method? [duplicate]
(5 answers)
Closed 5 years ago.
I have done a simple code to reverse a string in Java without using the inbuilt functions. But I have observed that unlike C where we can get a changed string back in the same variable using pointers, which it is not possible in Java due to the absence of pointer concept. So please show me what alternative way can I get back the string in the main function in Java.
class RevFun{
public void revFun(StringBuilder str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.println(str.charAt(i));//Here I am able to print it!
}
return;
}
}
class Rev
{
public static void main(String args[])
{
RevFun rev = new RevFun();
StringBuilder str = new StringBuilder("Hello");
System.out.println("Before reversing : "+str);
rev.revFun(str);
System.out.println("After reversing : "+str);//Here what should I do to get the reversed string from RevFun
}
}
give the second method returntype String
public static String handleString(String input){
// modify input
input += " test";
return input;
}
and either use, or assign the (new) value in your main:
public static void main(String[] args){
String a = "hello";
String b = handleString(a);
System.out.println(a);
System.out.println(b);
}
another way is to have your variable on class level:
static String test = "hi";
public static void main(String[] args){
System.out.println(test);
handleString();
System.out.println(test);
}
public static void handleString(){
test += " and bye";
}
both methods have access to the variable, so you won't even need to pass it as a parameter.
In Java Strings are immutable. This means that you can't change them. You can read more here
So if you want to "manipulate" an String you will have to return a new object

String buffer not printing 'Character' [duplicate]

This question already has answers here:
Where did the 'M' go? [duplicate]
(4 answers)
Closed 5 years ago.
I checked the following code found that instead of printing A123 it is priting 123 .
Can some one explain what's going on here.
public class Test{
public static void main(String[] args) {
StringBuffer sb = null;
sb = new StringBuffer('A');
sb.append('1');
sb.append('2');
sb.append('3');
System.out.println(sb);//Printing 123
}
You're calling the constructor that specifys the capacity. Try this
sb = new StringBuffer("A");
You encountered int to char conversion.
You are invoking the constructor StringBuffer(int capacity).
public StringBuffer(int capacity) {
super(capacity);
}
Since you passing the char, it converted to int value (ASCII value) and taking as capacity.

Storing reference to object [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);

Cannot make a static reference to the non-static field contents Java [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 6 years ago.
I am not formally a java programmer, but by looking at other answers, you set the the class variables using this.variablename. I used the this keyword, but I still end up with the error message as the title, as indicated below. Here is where I am constructing the class:
public class DataProcess {
int rows = 252; // there's actually only 252 rows in the new "Nothing.csv"
// file
String[][] contents = new String[rows][7];
DecimalFormat df = new DecimalFormat("####0.00");
public DataProcess(String filename, String[][] contents) {
this.contents = contents;
And when called in main:
public static void main(String[] args) {
String filename = "";
filename = args[0];
DataProcess dp = new DataProcess(filename, contents); <==ERROR HERE
System.out.println(dp.isContiguousWeek("12/30/13", "1/1/14"));
System.out.println(dp.isContiguousWeek("12/30/04", "1/3/05"));
System.out.println(dp.isContiguousWeek("1/3/05", "1/5/05"));
System.out.println(dp.isContiguousWeek("1/7/05", "1/10/05"));
System.out.println(dp.isContiguousWeek("1/31/05", "2/1/05"));
System.out.println(dp.isContiguousWeek("4/29/05", "5/2/06"));
System.out.println(dp.find_weeks(contents)); <== ERROR HERE
}
You should provide a getter method inyour DataProcess class to give access to a non-static contents.
public String[][] getContents(){
return this.contents;
}
Also, change the signature of the DataProcess.find_weeks() method and eliminate the parameter for the String[][] you pass to find_weeks. You don't need to pass the contents, as the instance of DataProcess you created in your main (dp) already has a reference to it's own contents object.
Finally, in your main, just invoke dp.find_weeks()

Categories