Java programmer interview book-I ++, java book-I
What are the output results of the following programs?
public class program2 { static { int x = 5; } static int x,y; public static void main(String[] args) { x--; myMethod(); System.out.println(x + y++ + x); } private static void myMethod() { y=x++ + ++x; }}
The result is 2. If you do not understand the following knowledge points, it is very difficult to do it. If you do not believe it, you can try it.
Static variables (global variables) are different from the loading sequence I ++ and ++ I of various attributes.
Static variable features
1. static member variable 1. belongs to the entire class rather than an object instance, so it can be called directly through the class name and Object Name. 2. static members belong to the entire class. When the system uses this class for the first time, it will allocate memory space for it until the class is detached. the attribute loading sequence is normal. The execution sequence is as follows: static parent variables, static parent code blocks, static subclass variables, static subclass code blocks, non-static parent variables, non-static parent code blocks, parent class constructor methods, non-static subclass variables, the non-static code block of the subclass and the subclass construction method. III. I ++, ++ I difference. Let's talk about the code process. public class program2 {static {int x = 5; // declare a local variable, no effect on the backend} static int x, y; // The default value is 0 public static void main (String [] args) {x --; // x =-1 myMethod (); system. out. println (x + y ++ x); // 1 + 0 + 1} private static void myMethod () {y = x ++ x; // equivalent to y = (x ++) + (++ x) from right to left y = 0 + 0 x = 1 ;}}
Join the study exchange group 569772982 to learn and exchange.