0

I have the following global variable of String type.

static public String rev="hello"

I can read it without any issue from an object of another class. Is there anyway I can update it with another string from an object of another class? I know Java string is immutable. I tried with the following way using StringBuilder:

  static public StringBuilder rev=new StringBuilder("hello");
  static public void setRev(StringBuilder s)
  {
    rev=rev.delete(0,rev.length());
    rev.append(s);
  }

From another class:

MainActivity.setRev(stringBuilderVar); 

But it did not work.

6
  • 1
    Java String values are immutable. StringBuilders aren't. Commented Sep 4, 2017 at 2:38
  • Strings are immutable, but you can reassign a string variable to a different string. But you've earlier used rev (say someOtherVar = MainActivity.rev), reassigning rev won't change anything where you previously copied the reference. Without more information, it's hard to tell what the right way to do things is. But I'm pretty sure that StringBuilder is the wrong solution. Commented Sep 4, 2017 at 2:42
  • Declaring StringBuilder as static might be the cause of immutability? The reason I declare as static is that I am access from another class. Commented Sep 4, 2017 at 2:47
  • No, static has nothing to do with immutability. static means that the variable belongs to the whole class and not to instances of the class. And you can access non-static variables from another class by creating objects of the class, which is the normal way to do things. I strongly suggest you work through a tutorial on Object-Oriented Programming concepts in Java, such as docs.oracle.com/javase/tutorial/java/concepts. Commented Sep 4, 2017 at 2:52
  • Nobody gave any solution. It is very simple task for procedural languages. But for Java? And someone gave me -1 even without offering solution? Commented Sep 4, 2017 at 14:08

1 Answer 1

1

The syntax for updating a field is the same for static and non-static fields. Simply use an assignment statement:

class Global {
    public static String greeting;
}

public class Other {
    public static void main(String[] args) {
        String newGreeting = "hello";
        Global.greeting = newGreeting;
    }
}

That said, once your programs get bigger, you'll likely want to use non-static fields instead.

Sign up to request clarification or add additional context in comments.

1 Comment

The following is not working: Global.greeting=anotherStringVar;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.