what is the priority for static block in java? - java

public class Static
{
static
{
int x = 5;
}
static int x,y;
public static void main(String args[])
{
x--; myMethod();
System.out.println(x + y + ++x);
}
public static void myMethod()
{
y = x++ + ++x;
}
}
Could you please somebody help me here why it is displaying out put is 3?

static
{
int x = 5;
}
You redeclare x here, making it a locally scoped variable (not a class member). This assignment will have no affect whatsoever, regardless of when it is run.
Now, you asked about the static block and that's what I answered. If you are confused about why a value of 3 is outputted even assuming that assignment doesn't take place, then this becomes a question about the increment operators (x++ and ++x).
Full explanation
I like Paulo's explanation quite a bit but let's just see if we can simplify the code. To start, let's forget about making x and y a static field (making them local, initialized to the default for a static int: 0) and inline myMethod():
int x = 0, y = 0;
x--;
y = x++ + ++x;
System.out.println(x + y + ++x);
First we should eliminate complex expressions. We can do that by extracting each sub-expression into a temporary variable in the correct order (expressions are evaluated left-to-right):
int x = 0, y = 0;
x--;
int yOperand1 = x++;
int yOperand2 = ++x;
y = yOperand1 + yOperand2;
int resultOperand1 = x;
int resultOperand2 = y;
int resultOperand3 = ++x;
int result = resultOperand1 + resultOperand2 + resultOperand3;
System.out.println(result);
Now we can label the value of x, y and any temporary variables at each step:
int x = 0, y = 0; //x: 0 y: 0
x--; //x: -1 y: 0
int yOperand1 = x++; //x: 0 y: 0 yOperand1: -1
int yOperand2 = ++x; //x: 1 y: 0 yOperand1: -1 yOperand2: 1
y = yOperand1 + yOperand2; //x: 1 y: 0
int resultOperand1 = x; //x: 1 y: 0 resultOperand1: 1
int resultOperand2 = y; //x: 1 resultOperand1: 1 resultOperand2: 0
int resultOperand3 = ++x; //x: 2 resultOperand1: 1 resultOperand2: 0 resultOperand3: 2
int result = resultOperand1 + resultOperand2 + resultOperand3; //result: 3
System.out.println(result);

Your static block has a local variable named x, it does not change the static variable with the same name.
In general, static { ... } blocks will be merged by the compiler with the initializers of static variables in the order they are in the code, and executed on class initialization. (In bytecode, this is a static <clinit> method.)
In your program the following occurs:
the static variables x and y are initialized with their default values (0).
the static block with its local variable is executed, this has no effect on the rest of the program.
the main method will execute.
it sets x = -1.
it invokes myMethod().
myMethod will twice increment x (from -1 to 0 to 1), and set y to 0 (the value before the first incrementing + the value after the second one).
it adds x (1), y (0) and the value after increasing x again (2), and prints the result (3).

Static.x starts with the value 0 since {int x = 5;} creates a new variable that is only visible within the static block. Since that x is never used it does nothing. If you removed it you should be able to trace through and see why your answer is what it is. :)
What you want is either to make the contents of the static block an assignment rather than a declaration ( ie static{ x = 5; }) or to assign x the value 5 at declaration static int x = 5;.

Related

How can I erase the value of my variable inside of a for loop in Java

for(i = 0; i<=timePassed; i++) {
y = r * x * (1 - x)
System.out.println(y)
So how do I reset the value of y every time the for loop loops so that i can assign a new value to it? I cannot wrap my head around it I have already tried to set y to 0 at the end of the loop right after printing y but that didnt seem to work. I also tried setting it to null but that gave me an error(?) I cannot understand why this is happening can someone please explain how to do this and what I did wrong?
Are you able to update your code block to include ALL code from your class.java file? It would help us see what could be wrong, because from this code snippet, y is not saved outside of the loop, therefore for every iteration (cycle) of the loop it would be reset and re-assigned.
As someone else has said, the y value does not change at any time in the loop, as all variables used (other than y) are declared outside of the loop. This loop simply prints the same y value "timePassed" amount of times.
Here's the code that you posted, including line numbers:
1. for(i = 0; i<=timePassed; i++) {
2. y = r * x * (1 - x)
3. System.out.println(y)
4.
Here are various comments + fixes:
Line 1: assume i is declared somewhere, like this: int i
Line 1: assume timePassed is declared somewhere and has a value set, like: int timePassed = 5;
Line 2: assume y is declared somewhere, like: int y;
Line 2: assume r and x are both declared somewhere, and have values set, like: int r = 1, x = 2;
Lines 2-3: need semicolons to terminate each line inside the loop: add ; at the end of each line
Line 4: add closing brace } to the "for" loop
Here is the code with those edits applied:
int timePassed = 5, y, r = 1, x = 2;
for (int i = 0; i <= timePassed; i++) {
y = r * x * (1 - x);
System.out.println(y);
}
Running that code produces this output:
-2
-2
-2
-2
-2
-2
The output doesn't change. Why? Because the calculation to determine each new value of "y" is the same each time: r * x * (1 - x). Despite being inside a loop, and with i changing each iteration through the loop, i is not used in the calculation at all.
Here's an edit to the code, removing the entire "for" loop (and i), and it produces the same -2 value:
int y, r = 1, x = 2;
y = r * x * (1 - x);
System.out.println(y);
-2
To demonstrate that y is being set each time through the loop, here's a variation of the code (including output) where i is included in the calculation for y.
int timePassed = 5, y, r = 1, x = 2;
for (int i = 0; i <= timePassed; i++) {
y = r * x * (1 - x) * i;
System.out.println(y);
}
0
-2
-4
-6
-8
-10

Expressing relationship between two variables in pseudocode?

I have some pseudocode I am trying to analyze:
public static void test(float z) {
float y = 0;
for (float i = 1; i <= z; i++) {
if (y < z) {
y = 4 * i * i + 6;
}
}
return y;
}
From the function, I understand that y = 4i^2 + 6 whenever y < z. However, I am having trouble capturing the relationship between y and z in an equation. I feel that it could be captured as a floor function (step function) -- for a certain range of numbers in z, y will have that specified value.
y becomes greater than z (and stops changing) for the first i such that 2*i^2 + 3 > z. In other words, a minimal i > sqrt((z - 3) / 2), which is floor(sqrt((z - 3)/2)) + 1. Now as you know i, compute y.

Using assignment operator inside of expression

Running this code will return 11 while I was expecting 20. Why is that so?
int x = 1;
int y = x + (x = 10);
System.out.println(y);
Evaluation is from left to right. So
int y = x + (x = 10);
is (with x initially 1):
int y = 1 + 10;
Putting the assignment in () doesn't make it come first. It just ensures that it's a valid expression, since y = x + x = 10 would be y = (x + x) = 10 which would require assigning to something (x + x) that wasn't a variable.
If you want 20, put the assignment first:
int y = (x = 10) + x;
Of course, the vast majority of the time, it's best to avoid these kinds of side-effects and assign x a value outside the expression, breaking the expression up if necessary. Assignment-within-expression can be useful sometimes (particularly while ((blah = getNextBlah()) != null) sort of things), but only in limited situations.

Curious on what this function is doing

Can someone tell me what is this function doing? I just know that it returns the sum of x + y, but I want to know why. Thanks
public static int f(int x, int y){
while( y > 0){
x = x + 1;
y = y - 1;
}
return x;
}
There are two cases:
First case: y <= 0
Because the while loop is false, it just returns x ("it skips the part")
Second case: y > 0
Because the while loop is true, it returns x + y (x + number of iterations)
The number of iterations is the value of y because with every iteration, y will be decreased by 1 until y = 0.
The loop starts at the value of y, and decrements it on each iteration, stopping when y gets to zero.
For each of these iterations, 1 is added to x. Therefore, for 'unit' of y, a 'unit' is added to x.
Edit As noted in the comments, the function will not return the sum of the two numbers if y is less then zero, since the loop will not execute at all.
Addition can be viewed as a series of increments. That's what this function does. It increments x y times and returns the result which is x + y. It is assumed that y is a natural number.

Head First Java program explanation

my program and question are below
public class test {
public static void main(String[] args) {
int x = 0;
int y = 0;
while ( x < 5 ) {
y = x - y;
System.out.println(x + "" + y);
x = x+1;
}
}
}
So output for this is 00 11 21 32 42. I understand what happens when x is even but what when x is odd? Let's move to step 2 and make x=1, then we get
y=1-y
2y=1
y=1/2
For me output should be like 11/2 or sth like that
So how the hell output for this is 11? Do we use approximation? Thanks for answer.
No. You understand it wrong. You are doing math keeping the fact aside that evaluation of Java expression.
y = x - y;
means
y= 1-0;
Which is
y = 1
There's nothing off with your code, the result is correct. When x is 1, we set y to be equal to x - y. That means x and y are both 1, as 1 - 0 is 1. Remember that a = b in programming is an assignment and does not imply equality.
Isn't it obvious? By "=" you assigning new value into variable.
x = 0, y = 0
y = 0 - 0 = 0
print x y -> 0 0
x = 1, y = 0
y = 1 - 0 = 1
print x y -> 1 1
x = 2, y = 1
y = 2 - 1 = 1
print x y -> 2 1
etc...

Categories

Resources