-2

Whenever I run the java code below it compiles but the line that include the replace method seems to be skipped, such so that the inputted string and the output (newMessage) are the same. Why? variable C and variable D are chars...

import java.util.Scanner;

public class javaencrypt
{
    public static void main(String[] args)
        {
            // define and instantiate Scanner object
            Scanner input = new Scanner(System.in);

            //prompt user to enter a string
            System.out.println("Please enter a string: ");
            String message = input.nextLine();
            String newMessage = message;
            char c=' '; // the character at even locations
            char d=' '; // new character
            // go throughout the entire string, and replace characters at even positions by the character shifted by 5.
            // access the even characters with a for loop starting at 0, step 2, and ending at length()-1
            // for( initial value; maximum value; step)
            for(int k=0; k<message.length(); k=k+2)
            {
                c=message.charAt(k);
                d=(char)(c+5);
                /*
                    there will always be characters available, because keyboard is mapped on ASCII which is in the beginning of UNICODE
                */
                newMessage.replace(c,d);
            }
            System.out.println("Message replacement is: " + newMessage);
        }
}
  • Because you are not assigning value again of `newMesssage` because string is immutable in do like `newMesssage = newMessage.replace(c,d);` – Sudhir Ojha Jan 29 '19 at 05:12
  • Because replace method is returning the new String object. You should assign its return object to keep it updated such as newMessage=newMessage.replace(c,d). – Y.Kakdas Jan 29 '19 at 05:13

1 Answers1

-1

In Java, Strings are immutable.

An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified.

When you call newMessage.replace(c, d); this does not update newMessage, but rather creates a new String with all chars c replaced with d instead. If you want newMessage to change to include the replacing of c to d, then you need to reassign the variable. This would look like newMessage = newMessage.replace(c, d);

SizableShrimp
  • 666
  • 7
  • 12