I'm trying to compile this code
public class Foo {
static final int x = 18;
public void go(final int y){
System.out.println(x);
}
}
public class Mixed2 {
public static void main(String[] args){
Foo f = new Foo();
f.go(11);
}
}
And it is compiled. And even gives the result (18)
But this does not have to be. Why is this happening?
I use the idea
Thanks
The fact is, You cannot change the value of a final... However, you are not changing any final numbers, and if you were, you would get compiler errors, not exceptions.
It is important to know the differences between static and final:
Static makes a variable the same between all classes- Changing go() to static will still allow you to access it, but making go() static and removing static from x will prevent you from referencing x, because the go() function does not know which Foo class to find x in.
Final Makes a variable unchangeable- I do not know of any performance reasons for this, but mostly for constants.
For example, you do not want to be able to set the value of Boolean.TRUE to false
public class Foo {
static final int x = 18;
public void go(final int y) {
// This is not possible because 'x' is final,
// however the state of 'y' does not matter,
// because its value is not being changed
x = y;
System.out.println(x);
}
}
public class Mixed2 {
public static void main(String[] args){
Foo f = new Foo();
f.go(11);
}
}
From what I understand, you wonder why the code is valid in the following cases, when you expect it to throw an error.
In this case, you are not changing the field x, but simply adding a new variable with the same name, that override (shadows) the field x:
public class Foo {
static final int x = 18; // field x
// This creates a new variable x which hides the field x above
public void go(final int x /* variable x */) {
System.out.println(x);
}
}
In these next two cases, you are trying to change x, which will result in an error:
public class Foo {
static final int x = 18; // field x
// The field x is final and cannot be changed.
public void go() {
x += 1;
}
}
public class Foo {
static final int x = 18; // field x
// The variable x is final and cannot be changed.
public void go(final int x /* variable x */) {
x += 1;
}
}
Old Answer: If you're trying to have it print 11, you should call System.out.println(y) instead of using x.
Try following some Java tutorials and look closely at the code and at variable names.
Related
import comp102x.IO;
public class testing {
private int x;
public testing(int x) {
x = x;
}
public static void main(String[] args) {
testing q1 = new testing(10);
IO.outputln(q1.x);
}
}
Why is the output 0 instead of 10? This is a JAVA script. The concept of instance and local variables is very confusing to me, can someone help to explain?
public testing(int x) {
x = x;
}
here you only reassign the value of the local variable x to itself, it doesn't change the instance variable.
Either change the name of the local variable, like this:
public testing(int input) {
x = input;
}
or make sure you assign the value to the instance variable, like this:
public testing(int x) {
this.x = x;
}
How do i print the value of variable which is defined inside another method?
This might be a dumb question but please help me out as i am just a beginner in programming
public class XVariable {
int c = 10; //instance variable
void read() {
int b = 5;
//System.out.println(b);
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println("How to print value of b here? ");
//d.read();
}
}
You can't. b is a local variable. It only exists while read is executing, and if read executes multiple times (e.g. in multiple threads, or via recursive calls) each execution of read has its own separate variable.
You might want to consider returning the value from the method, or potentially using a field instead - it depends on what your real-world use case is.
The Java tutorial section on variables has more information on the various kinds of variables.
You need to return value from your read() methods.
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(read());
//d.read();
}
}
Return b from the read method and print it
public class XVariable {
int c = 10; //instance variable
int read() {
int b = 5;
return b;
}
public static void main(String[] args) {
XVariable d = new XVariable();
System.out.println(d.c);
System.out.println(d.read());
}
}
I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?
I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a constructor, or using this. Is it possible?
public class Test {
int x;
public void hello(){
hello(5,x);
}
private void hello(int i, int x2) {
x2 = i;
}
public static void main(String args[]){
Test test = new Test();
test.hello();
System.out.println(test.x);
}
}
When you do
hello(5,x);
and then
private void hello(int i, int x2) {
x2 = i;
}
it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.
(Thanks #Tom for pointing out this interpretation of the question in the comments.)
The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.
Either remove that argument:
private void hello(int i) {
x = 5;
}
Rename the argument:
private void hello(int i, int y) {
x = 5;
}
Or use this.x to set the class property:
private void hello(int i, int x) {
this.x = 5;
}
You can create two methods.
public void setX(int a)//sets the value of x
{
x=a;
}
public int getX()//return the value of x
{
return x;
}
call setX to set the value of x and getx to return the value x.
Essentially these are called getter and setter and we use them to access private members from outside the class.
I have initialized the variables as follows in the code below. Is it okay to initialize like this ?
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
public static int getInt() {
int ret = 10;
System.out.println("ret- " + ret);
return ret;
}
public static int processInt(int toProcess) {
int toRet = toProcess / 2;
System.out.println("toRet- " + toRet);
return toRet;
}
public static void main(String[] args) {
StaticInit sit = new StaticInit();
}
}
You can initialise with the variable declaration or in the constructor. Some will argue that one or the other is better but either works. I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases.
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
}
or
public class StaticInit {
int x;
String z;
public StaticInit() {
x = 10;
z = x / 2;
}
}
For this case in particular though, I would definitely recommend using the constructor since z relies on x. Plus the constructor is much nicer than using static methods.
Personally, instead of having the getInt(), I would just initialise it in the constructor.
Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the reason behind “non-static method cannot be referenced from a static context”?
Cannot make a static reference to the non-static method
cannot make a static reference to the non-static field
I am not able to understand what is wrong with my code.
class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
int fxn(int y) {
y = 5;
return y;
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method fxn(int) from the type Two
Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main to:
Two two = new Two();
x = two.fxn(x);
Read more on static here in the Java Tutorials.
You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:
...
Two two = new Two();
x = two.fxn(x)
...
That is, make a Two-Object and call the method on that object.
...or make the fxn method static.
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
A static method can NOT access a Non-static method or variable.
public static void main(String[] args) is a static method, so can NOT access the Non-static public static int fxn(int y) method.
Try it this way...
static int fxn(int y)
public class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
static int fxn(int y) {
y = 5;
return y;
}
}