Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can two variables have the same name? [duplicate]

Tags:

java

I execute the following code and I get no errors, and in the output I see the Success! message. Can you please explain this strange behaviour.

public class Main {

    public static void main(String[] args) {
        int р = 0;
        int p = 1;
        if(р == 0 && p == 1) {
            System.out.println("Success!");
        }

    }

You can check the online demo

like image 214
ziMtyth Avatar asked Jan 28 '18 07:01

ziMtyth


People also ask

Can two variables have the same name?

Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.

Can you have duplicate variable names in a project?

It is legal for 2 variables in different scope to have same name.

Can we declare two variables or functions with same name in same scope?

We can declare two variables or member functions that have the same name within the same scope using namespace . This will cause several functions to have the same name and we can access all the functions from anywhere in the program by referencing the name of the namespace.

Can two variables have the same address?

You can not have 2 variables at the same address, the standard specifically mandates against this. You can not change the address of an object once it has been assign by the compiler.


Video Answer


1 Answers

both are different variables (but looks similar), you can see the UTF-16 is different

    int р = 0;
    int p = 1;
    if (р == 0 && p == 1) {
        System.out.println("Success!");
        System.out.println("p UTF-16 is " + (int) 'p');
        System.out.println("р UTF-16 is " + (int) 'р');
    }

output

Success!
p UTF-16 is 112
р UTF-16 is 1088
like image 181
Saravana Avatar answered Sep 25 '22 20:09

Saravana