Tutorial 1 - Java and Problem Solving

Q2a

Is the expression “y+++++y” legal in Java? What about “y+++y” or “y++++y” ?

The postfix and prefix increment operators are particularly confusing because they modify the value of the variable in addition to returning the value of the variable. Use with caution!

In “Good Ideas, Through the Looking Glass”, Niklaus Wirth (renown language designer) wrote about the increment operator:
The ugliness of a construct usually appears in combination with other language features. In C, we may write, for example, x+++++y, a riddle rather than an expression, and a challenge for a sophisticated parser! Guess what? Is its value is equal to ++x+++y+1? Or is the following correct?
x+++++y+1==++x+++y
x+++y++==x+++++y+1

Q2b

Floating point values are usually not represented precisely. You should avoid the use of the == operator to compare two floating point values. The recommended way is to check whether the absolute difference between the two values you are comparing is smaller than some tolerance, e.g. 1e-6

Q2c

int A[] = {1,2,3,4,....,n};
for (int i : A) {
    A[i] = 0;
}

What is the content of A after executing this loop? This is a generalization of the question to array of length n filled with the numbers from 1 to n.

int A[] = {1,2,3,4,....,n};
for (int i : A) {
    A[i] = i;
}

What is the content of A after executing this loop?

Q4

Superb st = new Test()

The important thing here is to understand that there are two entities here. One is the reference variable st, which has type Superb, the other is an object of type Test (note that objects are not named). The reference variable st refers to the object.

Most of the time, the value is looked up based on the type of the reference variable (st in this case), except for instance methods. A dynamic method lookup based on the type of the object is used for instance methods.

 
cs1102/tut1.txt · Last modified: 2009/02/06 11:19 by melvin
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki