The postfix increment operation increments the value of the variable after the expression is evaluated. Therefore, every Test instance gets its own copy of the field 'b'.ģ. Every instance of a class gets its own copy of the instance fields. Therefore, there is only 1 copy of the field 'a' irrespective of the number of objects of class Test that are created.Ģ. static fields belong to the class and not to the instance of a class. You need to remember the following points to answer this question:ġ. The expression x>a?y>b?y:b:x>z?x:z should be grouped as - x > a ? (y>b ? y : b) : (x>z ? x : z) The final values of the variables are as follows - x=2 y=1 z=1 a=1 b=2 Since z is 0, this will reduce to b = 1 + 1 (applying the prefix rule explained above). Similarly, after the execution of int b = z-, b will be 1 but z will be 0.Įxpand b += ++z to b = b + ++z Thus, b = 1 + (++z). Therefore, after this statement, a will be 1 and y will also be 1. 1 will be the result of the expression -y. So, y will be decremented to 1 and then its new value i.e. Here, the current value of y is 2 (as given in the code). Therefore, after this statement, z will be 1 but x will be 2. So, 1 will be the resulting value of the expression x++. Here, the current value of x is 1 (as given in the code). The basic principle is that in case of the prefix operator, the variable is updated and then its value is used in the expression, while in case of the postfix operator, the current value of the variable is used in the expression and then the variable is update. You also need to be clear about how prefix and postfix increment/decrement operators works. Expect such questions in the exam.įor such questions, it is best to keep track of each variable on the notepad after executing each line of code. This is a simple but frustratingly time consuming question. In the above code, only two string objects are created (not three). String s3 = new String("hello") //new string object is created in the heap area. String s2 = "hello" //no new object is created because the same String already exists in the string pool So, for example, String s1 = "hello" //new interned string object containing hello is created When you create a string using the new operator, interned strings are not used and a new String object is created. If the string exists, then it uses the same String object instead of creating a new one. a string within double quotes), the JVM checks whether that string already exists in the pool or not. The JVM maintains a pool of all the String objects. You should remember the following rules about this topic: It is not mentioned explicitly in exam objectives but a few candidates have reported seeing such questions in the exam. Note: String interning is a complex topic with many nuances.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |