srinivasSri
srinivasSri

Reputation: 11

differentiate variable names

In my class i've got variable name, formal parameter name and also local variable name the same.
In method body i want to assign the parameter to instance variable.
How can i differentiate the variables?

import java.util.Scanner;
class Setts 
{

static int a=50;
void m1(int a)
    {
                  int a=100;
    this.a=a;//here am set the int a value give the solution;
    }
    void disp()
    {
        System.out.println(Setts.a);
        //System.out.println(ts.a);
    }
}
class SetDemo
{

public static void main(String[] args) 
{
    System.out.println("Hello World!");
    Setts ts=new Setts();
    Scanner s=new Scanner(System.in);
    System.out.println("entet the int value");
    int x=s.nextInt();
    ts.m1(x);
    ts.disp();
    //System.out.println(ts.a);
}
}

Upvotes: 1

Views: 80

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533520

In short, you can't have a local variable which hides a parameter. The compiler won't allow it.

e.g.

class A {
   int x;
   void method(int x) {
       int x; // not allowed, it won't compile.

So if you have field and a parameter name you can just use the parameter name.

What you can have is

class A {
   int x;
   void method(int x) {

       int y = x; // the parameter
       int z = this.x; // the field above.

Upvotes: 1

Related Questions