What makes this line of code execute? [duplicate] - java

This question already has answers here:
What is the difference between a static and a non-static initialization code block
(9 answers)
Closed 7 years ago.
What makes this line of code execute?
The code gives an output of 11, but I was expecting
it to be 1
package methodcalling;
public class MethodCalling {
public static int cakes = 1;
public final static int UNIT = 10;
static{cakes += UNIT;} // what makes this line of code execute
public static void main(String[] args) {
System.out.println(cakes);
}
}

A static block is executed as the class gets loaded (i.e. directly after static variables are initialized). Therefore cakes += UNIT; is executed before main.

Related

member inner class variable access [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Why do I get "non-static variable this cannot be referenced from a static context"?
(8 answers)
Closed 4 years ago.
Can you please help me understand java8 compiler error on line k3.
public class Color {
private int hue = 10;
public class Shade {
public int hue = 20;
}
public static void main(String[] args) {
System.out.println(new Color().hue); // k1
System.out.println(new Color().new Shade().hue); //k2
System.out.println(new Shade().hue); //k3
}
}
Above code compiles if I comment out k3.
k1 outputs 10, k2 outputs 20.
With k3, compilation fails saying:
Color.java:11: error: non-static variable this cannot be referenced from a static context
System.out.println(new Shade().hue);
Main method is under static context,understood.
Where is non-static 'this' variable in this picture.
Thanks.

Storing reference to object [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);

non-static method cannot be referenced confusion [duplicate]

This question already has answers here:
Calling Non-Static Method In Static Method In Java [duplicate]
(14 answers)
Closed 6 years ago.
Receiving a non-static method cannot be referenced from static context. In this example I deleted all of the extra "stuff." All of the other examples I found had a lot of distractors that confused me.
This is for studying for a final and is NOT part of an assignment.
I do not understand why there is an issue here - troubles understanding static/non-static issue altogether.
In this case all I expect is for 5207 to be the output.
package testcase;
public class Testcase {
int number = 5207;
public static void main(String[] args) {
//int number = 5207;
int div;
div = divisor(number);
System.out.println(div);
}
private int divisor(int num){
return number;
}
Try to become a static method like this:
private static int divisor(int num){
return number;
}
Or instance the object of class Testcase :
Testcase tsc = new Testcase();
div = tsc.divisor(number);

Java custom method not working [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
I'm a beginner and I'm starting to learn programming by doing some
exercises...
Why this simple java code gives me an error?
class HelloWorldEdited {
public int a = 5;
public int b = 2;
public static int sum() {
return a + b;
}
public static void main(String[] args) {
HelloWorldEdited obj = new HelloWorldEdited();
System.out.println(obj.sum());
}
}
I think it's because you are accessing "non static" properties (a, b) from a static method (sum), this operation is forbidden.
Try to change
public static int sum()
to
public int sum()
To understand the "static" modifier I suggest you to read:
official tutorial
The method sum() is static. In this method you can't access variables "non static".

scope of variable inside main in Java? [duplicate]

This question already has answers here:
Why does Java not have block-scoped variable declarations?
(6 answers)
Closed 9 years ago.
Am I correct that a block inside main() doesn't have separate scope?
For example, if I do the following, I will get compile error:
static int i = 1;
public static void main(String[] args) {
int i = 2;
{
int i = 3;
}
}
Why is this?
When I try to compile this, I get this message:
error: variable i is already defined in method main(String[])
This means that the static int i = 1; does not cause the error. The scope of the first i in main is for the whole main, so when you try to make another one, in the code block, you get an error.
Note that if you declared the i in a block:
public static void main(String[] args){
{
int i = 2;
}
{
int i = 3;
}
}
You don't get a compile error (see here).
The static int can be accessed in one of two ways: this.i (not recommended) or ClassName.i (recommended for accessing of a static variable)
Java does not allow obfuscation of stack (ie. local variables). You can obfuscate an instance or class variable because there are other ways to access them (ie. this.i for instance, or MainClass.i for static).

Categories