Woodstock Blog

a tech blog for general algorithmic interview questions

[CC150v4] 11.4 Test Webpage Without Tools

Question

How would you load test a webpage without using any test tools?

Solution

Load testing

Load testing is testing under normal and peak load condition. It’s also called software performance testing, reliability testing, and volume testing.

Steps

First identify the performance-critical scenarios, which might include:

  1. response time
  2. throughput
  3. resource utilization
  4. max load that system can bear

Then, design tests to simulate the load: we can create virtual users by a multi-threaded program with 1000 thread, each acting as a user loading the page. We measure response time of each user.

[CC150v4] 15.2 SQL Types of Join

Question

What are the different types of joins? Please explain how they differ and why certain types are better in certain situations.

Implicit and explicit

The “explicit join notation” uses the JOIN keyword. The “implicit join notation” simply lists the tables for joining, in the FROM clause of the SELECT statement.

Example of an explicit cross join:

SELECT *
FROM employee CROSS JOIN department;

Example of an implicit cross join:

SELECT *
FROM employee, department;

Different Types

  1. INNER JOIN: Returns all rows when there is matching values in BOTH tables.

  2. OUTER JOIN: An outer join) does not require each record in the two joined tables to have a matching record.

    1. LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

    2. RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

    3. FULL JOIN: Return all rows when there is a match in ONE of the tables. If no matching record was found then the corresponding result fields will have a NULL value.

source

[CC150v4] 15.1 SQL Count and Group by Statement

Question

Write a method to find the number of employees in each department.

Answer

select 
    Dept_Name, 
    Departments.Dept_ID, 
    count(*) as ‘num_employees’
from 
    Departments
left join 
    Employees
on 
    Employees.Dept_ID = Departments.Dept_ID
group by 
    Departments.Dept_ID, Dept_Name

[CC150v4] 11.2 Random Error Debugging 2

Question

You are given the source to an application which crashes when it is run After running it ten times in a debugger, you find it never crashes in the same place The application is single threaded, and uses only the C standard library What programming errors could be causing this crash? How would you test each one?

Solution

The solution is from both CC150v4 and CC150v5. My previous post [Testing] Random error debugging 1 already covered this question.

Again, the answer is very similar:

  1. Depends on random variable
    1. RNG
    2. depends on user input
    3. depends on system date/time
  2. Uninitialized variable
    1. can take on arbitrary value
    2. can execute in different path
  3. Memory Leak
    1. out of RAM
    2. heap overflow
    3. stack data corruption
  4. System Dependency
    1. depends on external module
    2. depends on some system attributed that’s being modified by another application (this is especially for hardware-facing applications)

In general, Web server is more prone to Memory Leak, and program that runs close to system level is more prone to system dependency errors.

Additionally, we may be able to use tools to check for specific situations. For example, to investigate issue #2, we can utilize runtime tools which check for uninitialized variables.

[CC150v4] 14.5 Java Reflection

Question

Explain what object reflection is in Java and why it is useful.

Solution

Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to. Like this:

Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

Usage in Junit

One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.

Code

The following example code is covered in this post:

public class JavaReflection {

    public static void main(String[] args) {
        Method[] methods;

        methods = ListNode.class.getMethods();

        for (Method method : methods) {
            System.out.println(formatMethodName(method.getName() + "()")
                    + method.getDeclaringClass());
        }
    }

    private static String formatMethodName(String methodName) {
        for (int i = methodName.length(); i < 30; i++) {
            methodName += ".";
        }
        return methodName;
    }
}

[CC150v4] 14.1 Java Private Constructor

Question

In terms of inheritance, what is the effect of keeping a constructor private?

Solution

If the programmer does not provide a constructor for a class, the system will always provide a default, public no-argument constructor.

To disable this default constructor, simply add a private no-argument constructor to the class.

Two categories of usage:

  1. Object construction is entirely forbidden
    1. class offers only static members (sometimes called utility class)
  2. Object construction is private only
    1. a class needs to prevent the caller from creating objects, like Singleton

[CC150v4] 14.6 Java HashMap Counter

Question

Suppose you are using a map in your program, how would you count the number of times the program calls the put() and get() functions?

Solution

Write a wrapper class upon the HashMap Class, and override the ger() and put() methods.

However, what if we have multiple instance of hashmap? Solution is to use a static variable to count. Some answers are found here.

Good question this is!

Code

public static class MyHashMap<K, V> extends HashMap<K, V> {

    private static final long serialVersionUID = 1L;
    private static int count = 0;

    public V put(K key, V value) {
        count++;
        return super.put(key, value);
    }

    public V get(Object key) {
        count++;
        return super.get(key);
    }

    public static int getCount() {
        return count;
    }
}

[CC150v4] 14.2 Java Finally Statement

Question

In Java, does the finally block gets executed if we insert a return statement inside the try block of a try-catch-finally?

Solution

Yes, it will.

Even when we attempt to exit within the try block (normal exit, return, continue, break or any exception), the finally block will still be executed.

The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.

[CC150v4] 14.3 Java Final, Finally and Finalize

Question

What is the difference between Final, Finally, and finalize?

final

is a keyword.

  1. Variable decleared as final should be initialized only once and cannot be changed.
  2. Classes declared as final cannot be extended.
  3. Methods declared as final cannot be overridden.

Code:

private final String name = "foo";

public final String toString() {  return "NULL"; }

// final can also make a class not "inheritable"
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} 
// Not allowed

finally

is a block.

The finally block always executes when the try block exits (even if an unexpected exception occurs).

lock.lock();
try {
    //do stuff
} catch (SomeException se) {
    //handle se
} finally {
    lock.unlock(); //always executed, even if Exception or Error or se
}

finalize

is a method.

It’s called by Garbage Collector before reclaiming GC eligible objects.

public void finalize() {
    //free resources (e.g. unallocate memory)
    super.finalize();
}

source1

source2

[CC150v4] 10.4 Implement Mathematical Operators

Question

Write a method to implement *, - , / operations You should use only the + operator.

Solution

First it’s important to write a ‘negate’ operator. The code given in the book:

public static int FnNegate(int a) {
    int neg = 0;
    int d = a < 0 ? 1 : -1;
    while (a != 0) {
        neg += d;
        a += d;
    }
    return neg;
}

Updated on Feb 1st, 2015, the negate method:

public static int negate(int a) {
    // plus -1, then do XOR with 111111111
    // eg. 1 -> 0000000 -> 11111111 = -1
    // eg. -1 -> 11111110 -> 00000001 = 1
    return (a + -1) ^ -1;
}

And the check sign method:

public static boolean sameSign(int a, int b) {
    // if first bit is same, then xor = 00000000
    // if first bit is not same, xor = 10000000
    int xor = (a ^ b) & Integer.MIN_VALUE;
    return xor == 0;
}

Although we can only use +, the author also used > and < comparison operators.

Code

public static int negate(int a) {
    // plus -1, then do XOR with 111111111
    // eg. 1 -> 0000000 -> 11111111 = -1
    // eg. -1 -> 11111110 -> 00000001 = 1
    return (a + -1) ^ -1;
}

public static int minus(int a, int b) {
    return a + negate(b);
}

public static boolean sameSign(int a, int b) {
    // if first bit is same, then xor = 00000000
    // if first bit is not same, xor = 10000000
    int xor = (a ^ b) & Integer.MIN_VALUE;
    return xor == 0;
}