Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backslash (\) behaving differently

I have small code as shown below

public class Testing {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String firstString = sc.next();
        System.out.println("First String : " + firstString);
        String secondString = "text\\";
        System.out.println("Second String : " + secondString);
    }
}

When I provide input as text\\ I get output as

First String : text\\
Second String : text\

Why I am getting two different string when input I provide to first string is same as second string.

Demo at www.ideone.com

like image 923
Fahim Parkar Avatar asked Dec 06 '22 13:12

Fahim Parkar


1 Answers

The double backslash in the console you provide as input on runtime are really two backslashes. You simply wrote two times ASCII character backslash.

The double backslash inside the string literal means only one backslash. Because you can't write a single backslash in the a string literal. Why? Because backslash is a special character that is used to "escape" special characters. Eg: tab, newline, backslash, double quote. As you see, backslash is also one of the character that needs to be escaped. How do you escape? With a backslash. So, escaping a backslash is done by putting it behind a backslash. So this results in two backslashes. This will be compiled into a single backslash.

Why do you have to escape characters? Look at this string: this "is" a string. If you want to write this as a string literal in Java, you might intentionally think that it would look like this:

String str = "this "is" a string";

As you can see, this won't compile. So escape them like this:

String str = "this \"is\" a string";

Right now, the compiler knows that the " doesn't close the string but really means character ", because you escaped it with a backslash.

like image 175
Martijn Courteaux Avatar answered Dec 09 '22 02:12

Martijn Courteaux