Search code examples
javastringbuilder

Method result not save in memory how does that work?


I am building a calculator app with the code for backspace/deleting last character as:

JButton btnBackspace = new JButton("\uF0E7");
    btnBackspace.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String backspace = null;
            if (textField.getText().length() > 0) {
                StringBuilder str = new StringBuilder(textField.getText());
                backspace = str.deleteCharAt(textField.getText().length()-1).toString();
                textField.setText(backspace);
            }
        }
    });

Line 7 above code is long and thought of splitting them into two statements.

JButton btnBackspace = new JButton("\uF0E7");
    btnBackspace.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String backspace = null;
            if (textField.getText().length() > 0) {
                StringBuilder str = new StringBuilder(textField.getText());
                backspace = str.deleteCharAt(textField.getText().length()-1);
                backspace = backspace.toString();
                textField.setText(backspace);
            }
        }
    });

The above code gives me a bunch of error but when I try the next code:

JButton btnBackspace = new JButton("\uF0E7");
    btnBackspace.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String backspace = null;
            if (textField.getText().length() > 0) {
                StringBuilder str = new StringBuilder(textField.getText());
                str.deleteCharAt(textField.getText().length()-1);
                backspace = str.toString();
                
                textField.setText(backspace);
            }
        }
    });

The above code works. How was that possible that the result from deleting a character did not need to be saved to a memory and yet successfully converted to string?


Solution

  • deleteCharAt is a mutating method although it also returns a StringBuilder object. This can be easily proved with the following code

    String text = "abcde";
    StringBuilder builder1 = new StringBuilder(text);
    StringBuilder builder2 = builder1.deleteCharAt(text.length() - 1);
      
    System.out.println(builder1.toString() + " - " + builder2.toString());
    

    Output

    abcd - abcd