Assignment 2

Due Feb 3 on line

Part of the homework for CS:2820, Spring 2021
by Douglas W. Jones
THE UNIVERSITY OF IOWA Department of Computer Science

  1. Which is the best short description of this deliberately undocumented Java class?
    class X {
        public X y = null;
        public X z = null;
        public int v = 0;
        public int w() {
    //      int xv = 0; -- unneeded (this was a typo)
            int yv = 0;
            int zv = 0; // omitted in original version
            if (y != null) yv = y.w();
            if (z != null) zv = z.w();
    //      return v + xv + yv; -- typo
            return v + yv + zv; // intended
        }
    }
    

    Instances of X can be used to hold ...
    a) ... binary trees of integers and the recursive method w traverses and sums the nodes. — correct
    b) ... graphs integers and the recursive method w traverses and sums the nodes.
    c) ... binary trees of integers with an iterative method w that traverses and sums the nodes.
    d) ... graphs of integers with an iterative method w that traverses and sums the nodes.
    e) ... none of the above.

    Two object handles per item immediately suggests a tree, and the integer field suggests a tree of integers, but many other data structures could be made with objects with this structure, depending on how they are linked together. You have to look at the method w to see what assumptions it makes about thee data structure. It uses a recursive algorithm where recursion is terminated by encountering a null, exactly the algorithm for tree traversal and totally unsuited to graph traversal. If used on a tree, w adds zero for nulls, and it sums all the values of the non-null items.

  2. Consider the following code in the context of the code from problem 1:
    X x = new X();
    x.y = x;
    x.z = x;
    x.v = 1;
    System.out.println( x.w() );
    

    What happens when you try to compile and run the above?
    a) There is a compile time error
    b) The code goes into an infinite loop
    c) The code suffers from run-away recursion and dies of a stack overflow — correct
    d) The code outputs the value 1
    e) Something else

    The object x has itself as its left and right (y and z) subtrees. An attempt to traverse such a malformed tree will never terminate, but there is no loop in this program, only recursion. Therefore, it is wrong to say an infinite loop, but it is right to say runaway recursion. Just to check, I ran it and got this error message:

    Exception in thread "main" java.lang.StackOverflowError

    The message was followed by a very long stack trace, hundreds of lines of it, as the Java run-time system obliginly tried to show me the context of my error.

  3. Which of the following declarations in Java creates a new object each time it is executed?
    a) int i = 5;
    b) float x = 1.0;
    c) String s = "Hello World!";
    d) boolean f = false;
    e) String s = "x = " + x; — correct

    First, int, float and boolean are not Classes, and variables of these primitive types are not objects. (Had the class names Integer, Float or Boolean been used, the answer would depend on what was on the right side of the equals sign on these lines.) This rules out a), b) and d).

    Second, String is a real class in Java, so the answer on lines d) and e) depends on whether the right-hand-side of the equals sign creates a new object. The string constant "Hello World!" is a constant. Each time line c) is encountered in a program, the same object is assigned. The object holding the string constant was created just once, when you loaded your program to run, and all uses of this constant refer to the same object. No new object is created at any later time during the execution of your program.

    That leaved option e). Each time the expression "x = " + x is encountered, the variable x is evaluated and concatenated with the string constant "x = ". To do this concatenation, a new String must be created each time this is done. So this line actually does concatenation.

    Note that the expression "x = " + x uses a short-hand notation. The Java compiler treats this as equivalent to the following:
    new StringBuilder("x = ").append( x.toString() ).toString()

  4. Here is a complete Java program that is not properly formatted:
    public class Test {public static void main(String[] arg){}}
    

    All of the following are the same program reformatted. Which of them is best, according to the Sun-Oracle Java style guidelines?
    a) — correct

    public class Test {
        public static void main(String[] arg) {
        }
    }
    

    b)
    public class Test
        {
            public static void main(String[] arg)
                {
                }
        }
    

    c)
    public class Test {
            public static void main(String[] arg) {}
    }
    

    d)
    public class Test
            {
                    public static void main(String[] arg)
                            {
                            }
            }
    

    e)
    public class
    Test {
            public static void
            main(String[] arg) {
                               }
         }
    

    a) and b) use 4-space indenting, as required by section 4 of the guidelines.
    c) and d) use 8-space indenting, while e) uses something weirder. All these violate section 4.
    a) and c) generally use { and } the way section 6.4 recommends.
    b), d) and e) violate 6.4.
    a) does contain a minor violation of 6.4 because the body of main is a null statement, and null statements should be written as {}, as in c).

    Therefore, the big question is, does a) violate the rules more than c) or less. Note, that a main program with a null body, such as this one, is utterly useless. There must be the intent to add code here! Writing {} leaves no room to add code and suggests that a null statement in the final useful version of the code is actually intended. In contrast, a) is written to permit adding code easily. In contrast, c) is both badly indented and does not invite adding code that must obviously be added to make the program useful.

  5. Here is a Java program:
    public class Hw2 {
    
        static final String section = "xxxx";
    
        static final String user = System.getenv( "USER" );
    
        public static void main(String[] args) {
            try {
                Process p = Runtime.getRuntime().exec( new String[] {
                    "/mnt/nfs/clasnetappvm/fs3/dwjones/2820hw2",
                    section,
                    user,
                }, null, null );
            } catch (Exception e) {
                System.out.println( "oops: " + e );
            }
        }
    }
    

    Open a shell window under fastx.divms.uiowa.edu and create a new Java program holding this text, with your discussion section of CS2820 replacing the xxxx in the declaration of the string named section.

    Before you run the program, run this shell command (replacing xxxx as above):

         ~dwjones/2820check2 xxxx
    
    It should tell you that there is "no entry for HawkID" (using your HawkID), verifying that you have yet to solve the assignment.

    Compile and run your edited version of the program. It should produce no output. (If it says "oops" something is wrong.) Then, run the same shell command shown above. It should tell you "problem solved correctly."

    Grading for this problem will be done by manually inspecting the log files and integrating the result into the quizlet score on ICON.

    81 students completed this assignment. 47 completed it on Monday, 10 completed it on Tuesday, 22 completed it on Wednesday, and 2 completed it shortly after midnight Thursday morning (close enough).