Java binary tree : Recursion related questions [duplicate] - java

What is the difference between a member variable and a local variable?
Are they the same?

A local variable is the variable you declare in a function.
A member variable is the variable you declare in a class definiton.

A member variable is a member of a type and belongs to that type's state. A local variable is not a member of a type and represents local storage rather than the state of an instance of a given type.
This is all very abstract, however. Here is a C# example:
class Program
{
static void Main()
{
// This is a local variable. Its lifespan
// is determined by lexical scope.
Foo foo;
}
}
class Foo
{
// This is a member variable - a new instance
// of this variable will be created for each
// new instance of Foo. The lifespan of this
// variable is equal to the lifespan of "this"
// instance of Foo.
int bar;
}

There are two kinds of member variable: instance and static.
An instance variable lasts as long as the instance of the class. There will be one copy of it per instance.
A static variable lasts as long as the class. There is one copy of it for the entire class.
A local variable is declared in a method and only lasts until the method returns:
public class Example {
private int _instanceVariable = 1;
private static int _staticvariable = 2;
public void Method() {
int localVariable = 3;
}
}
// Somewhere else
Example e = new Example();
// e._instanceVariable will be 1
// e._staticVariable will be 2
// localVariable does not exist
e.Method(); // While executing, localVariable exists
// Afterwards, it's gone

public class Foo
{
private int _FooInt; // I am a member variable
public void Bar()
{
int barInt; // I am a local variable
//Bar() can see barInt and _FooInt
}
public void Baz()
{
//Baz() can only see _FooInt
}
}

A local variable is the variable you declare in a function.Its lifespan is on that Function only.
A member variable is the variable you declare in a class definition.Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.

Variables declared within a method are "local variables"
Variables declared within the class not within any methods are "member variables"(global variables).
Variables declared within the class not within any methods and defined as static are "class variables".

A member variable belongs to an object... something which has state. A local variable just belongs to the symbol table of whatever scope you are in. However, they will be represented in memory much the same as the computer has no notion of a class... it just sees bits which represent instructions. Local variables and member variables can both be on the stack or heap.

Related

Consider the code given below, Is there any way to acces the variable "iry" from the innerClassMethod() if the variable name "iry" is changed to "i"? [duplicate]

i'm new in java and i confused for below example
public class Test {
int testOne(){ //member method
int x=5;
class inTest // local class in member method
{
void inTestOne(int x){
System.out.print("x is "+x);
// System.out.print("this.x is "+this.x);
}
}
inTest ins=new inTest(); // create an instance of inTest local class (inner class)
ins.inTestOne(10);
return 0;
}
public static void main(String[] args) {
Test obj = new Test();
obj.testOne();
}
}
why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8
why i can't access to shadowed variable in inTestOne() method with "this" keyword in line 8
Because x is not a member variable of the class; it is a local variable. The keyword this can be used to access a member fields of the class, not local variables.
Once a variable is shadowed, you have no access to it. This is OK, because both the variable and the local inner class are yours to change; if you want to access the shadowed variable, all you need to do is renaming it (or renaming the variable that shadows it, whatever makes more sense to you).
Note: don't forget to mark the local variable final, otherwise you wouldn't be able to access it even when it is not shadowed.
this. is used to access members - a local variable is not a member, so it cannot be accessed this way when it's shadowed.

Method local inner class hides method fields

Given the following class definition
public class MethodLocalAccess {
int m = 10;
String show(){
final int m = 20;
final int n = 30;
class MyClass{
int m = 40;
String someOtherMethod(){
return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
}
}
MyClass object = new MyClass();
return object.someOtherMethod();
}
public static void main(String[] args) {
System.out.println(new MethodLocalAccess().show());
}
}
Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.
Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.
What are you referring to is called variable shadowing (link).
If a declaration of a type (such as a member variable or a parameter
name) in a particular scope (such as an inner class or a method
definition) has the same name as another declaration in the enclosing
scope, then the declaration shadows the declaration of the enclosing
scope. You cannot refer to a shadowed declaration by its name alone.
Once you shadowed a variable, it is not accessible anymore without explicitly specifying its scope, if possible. The only solution in this case is to rename either outer or inner variable.
No you can't. The variable inside the function completely shadowed and you can't refer it anymore as Java doesn't have a way to refer function context.
However you can access top level variables with the context this even though they shadowed (infact you are not shadowing and creating a local variable with same name).
You can't, because it's shadowed.
You can't even with reflection, because reflection works on the type level, not on the byte-code.
You can, with additional tools, if you play with the generated byte-code.
In your case I don't think you can access the local variable m defined in the show method since you already have it declared in your inner class, therefore shadowing it.
Using constructs like ClassName.this.varName allows you to access only the members of that enclosing class. This means you can't use that type of expression to access shadowed local varibles defined in the method since they aren't members of that class.
Yes, the fields declared in method-local inner-class having same name
as that of method-local-variable, will permanently hide the latter.
We can access the local-variable final int m = 20 inside the
inner-class only if you don't have the instance variable of Myclass,
int m = 40 is absent.

Why can't i use static variable in java constructor?

The compiler says illegal modifier for parameter i.
Please tell me what I'm doing wrong. Why can't I use a static variable in a Java constructor?
class Student5{
Student5() {
static int i = 0;
System.out.println(i++);
}
public static void main(String args[]){
Student5 c1 = new Student5();
Student5 c2 = new Student5();
Student5 c3 = new Student5();
}
}
Because of where you are declaring i:
Student5(){
static int i=0;
System.out.println(i++);
}
the compiler treats it as a local variable in the constructor:
Local variables cannot be declared as static. For details on what modifiers are allowed for local variables, see Section 14.4 of the Java Language Specification.
Judging from what the code appears to be trying to do, you probably want i to be a static member of Student5, not a local variable in the constructor:
class Student5{
private static int i = 0;
Student5(){
System.out.println(i++);
}
. . .
}
If you want to declare static variable then declare it outside of the constructor, at class level like this -
public class Student5{
private static int i;
}
You declaration of static occurred at your constructor which is a local variable and local variable can not be static. And that's why you are getting - illegal modifier for parameter i. And finally for initializing static variable you may use a static initialization block (though it's not mandatory) -
public class Student5{
private static int i;
static {
i = 5;
}
}
This is how the language was designed.. What if you wanted to have another int field named i in the constructor?, then which i should be considered?. Also, static fields are initialized before the constructor is called i.e, during class initilization phase. A constructor gets called only when a new instance is created.
Imagine what would happen (supposed to happen) if you load and initialize a class but not create a new instance.
Static variables are variables that can be referenced without having an instance of the class. By defining one instead of a constructor, which is called when you create an instance of the class, you are contradicting yourself. Either make it defined without having an instance (outside of the constructor and static) or make it specific to an instance (inside the constructor and not static).
You might want to rethink what you are actually trying to do and if you really need a static variable.

java. redeclare class field within class initializer and local variable within method nested block(framed braces) differences

I prepare for scjp exam and noticed surprising behaviour for me.
public class Test {
int k;
{
int k; // it is valid variant
}
public static void main(String[] args) {
int kk;
{
int kk; // NOT VALID.java: variable kk is already defined in method main(java.lang.String[])
}
}
public void method (int var){
int var;//NOT VALID.java: variable var is already defined in method method(int)
}
}
Always in my mind I kept following rule:
I thought that all three variants is possible and inner definition would overlap external.
example shows that it is wrong rule.
Please clarify this situations and explain common rule for familiar situations.
P.S.
public class Test {
int k;
{
int k;
{
int k; //java: variable k is already defined in instance initializer of class Test
}
}
}
Name shadowing is explained in JLS 6.4 Shadowing and Obscuring. I put the relevant parts of it for each of your examples.
Local variables may hide fields
public class Test {
int f; // field declaration
{ // init block
int f; // WARNING: Local variable f is hiding a field from type Test
}
}
Since this piece of code is declared directly in a class, the first int f; defines a field, and the block is in fact an initializer block. The init block declares a local variable that hides the field's name within that init block. This is valid (but discouraged by a warning).
Local variables may not hide method parameters
public void method (int param){
int param; // NOT VALID
}
This is not valid because, as the JLS 6.4 clearly states:
It is a compile-time error if the name of a formal parameter is
redeclared as a local variable of the method or constructor
Local variables may not hide local variables (in the same "local space")
As the JLS 6.4 states:
It is a compile-time error if the name of a local variable v is
redeclared as a local variable of the directly enclosing method,
constructor, or initializer block within the scope of v
public static void main(String[] args) {
int local;
{
int local; // NOT VALID: local declaration in same method
}
}
Here, the second statement tries to declare the same name, as another local variable of the same directly enclosing method, and within the scope of the former declaration. Not valid.
public class Test {
int f; // field declaration
{ // init block
int f; // VALID: local declaration hiding field
{ // nested local block
int f; // NOT VALID: local declaration in same init block
}
}
}
Here, the first statement declares a field. Then an init block starts, and a local variable is declared, obscuring the field's name (this 2nd declaration is valid). Now, a nested block is declared, with another local variable (3rd declaration) of the same directly enclosing init block and within the scope of the 2nd declaration. Not valid.

What is the difference between a local variable, an instance field, an input parameter, and a class field?

What is the difference between a local variable, an instance field, an input parameter, and a class field with respect to a simple Java program?
A local variable is defined within the scope of a block. It cannot be used outside of that block.
Example:
if(x > 10) {
String local = "Local value";
}
I cannot use local outside of that if block.
An instance field, or field, is a variable that's bound to the object itself. I can use it in the object without the need to use accessors, and any method contained within the object may use it.
If I wanted to use it outside of the object, and it was not public, I would have to use getters and/or setters.
Example:
public class Point {
private int xValue; // xValue is a field
public void showX() {
System.out.println("X is: " + xValue);
}
}
An input parameter, or parameter or even argument, is something that we pass into a method or constructor. It has scope with respect to the method or constructor that we pass it into.
Example:
public class Point {
private int xValue;
public Point(int x) {
xValue = x;
}
public void setX(int x) {
xValue = x;
}
}
Both x parameters are bound to different scopes.
A class field, or static field, is similar to a field, but the difference is that you do not need to have an instance of the containing object to use it.
Example:
System.out.println(Integer.MAX_VALUE);
I don't need an instance of Integer to retrieve the globally known maximum value of all ints.
Not quite.
A class field is what you think a local variable is but it is generally a static field and so is the same across all instances.
An instance field is the same as a class field, but is non static and can be different for each instance of the object.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
And a local variable is a variable inside a method or block, that can only be used by that method or block.
Oh and your input parameter definition is correct, an input parameter is a field that is passed to a method as a parameter.
A class field is often called a class variable, and you can find that information here
Start by having a read through Classes and Objects
I know the local variable is a variable that is available to the class it is in, correct?
No, generally a local variable refers to a variable that only has context within the area it was declared. This typically refers to variables declared within methods and {...} blocks (like if statements)
An instance field is an Object that is created in the constructor...?
Not really, an instance field is any field, declared at the class level which is not static, therefore it's value only has meaning to an individual instance of the class
An input parameter is what is passed into a method.
Yes
But I have NO idea about a class field!
A class field and instance field are (generally) the same thing. The only difference would be if the field is declared static, then it can't be a instance field...
A local variable is local to a method.
An instance fields is the field of an instance of a class i.e. an object.
A parameter is passed to a method
A class field, I assume is a static field which is associated with the class. e.g. if you use multiple class loaders, you can have multiple classes with the same name and their own static fields.
A local variable is a variable in a method. It's scope is limited to the scope of the two parenthesis around it. {}
Example:
public void someMethod () {
int localVariable1 = 5;
if (...) {
int localVariable2 = 7;
}
}
With an instance field, I think you mean a member of a a class instance. If you take for example the class Dimension, this would be height or width.
.
An input parameter is a parameter in a method, as you guessed.
A class field is a field in a static method.

Categories