Google

Aug 8, 2012

Java logical thinking and coding questions and answers



When coding, the logical operators like &&, ||, and ! can be confucing. Here is an example that will evaluate a candidate's ability to process logic.

Q. What is the opposite of (score < 100) ?
A. Some might think it is (score > 100), but that is wrong. The correct answer is (score >= 100). The opposite of < is >=, and the opposite of > is <=.

Q. What will be the output of the following code snippet if the score is 120?

if (! (score < 100) ) { 
   System.out.println("The score is greater than 100");
}
else{
    System.out.println("The score is less than 100");
}

A. 
Prints "The score is greater than 100".

Q. In the code snippet below, how will you go about implementing the validate logic so that the validation fails (i.e returns false) when the security is
  • Included and
  • SecurityType == OTHER and 
  • SecuritySubType == OTHER
Show with and without using the not (i.e. !) operator


public class LogicalThinking1 {

 public static class Security {

  enum SecurityType {
   WARRANT, OPTION, OTHER
  }

  enum SecuritySubType {
   INVESTMENT, MARGINLENDING, OTHER
  }

  private boolean excluded;
  private SecurityType type;
  private SecuritySubType subType;

  public Security(boolean excluded, SecurityType type, SecuritySubType subType) {
   this.excluded = excluded;
   this.type = type;
   this.subType = subType;
  }

  // getters/setters, equals/hashCode and equals methods are omitted for
  // brevity

  public boolean validate() {
   //logic goes here
  }

 }
}


A. The validate method must return false when the security is  included, and of type OTHER and of subType OTHER. Under all other conditions, it must return true (i.e validation succeeds)

Approach-1: Using the ! operator.


    public boolean validate() {
      //use of && and ! operators
      return !(!excluded && SecurityType.OTHER == this.type && 
                SecuritySubType.OTHER == this.subType) ;
    }

The above code basically constructs the condition which returns "true" within the paranthesis and puts the not outside because it must return "false" (i.e the validation should fail) if the given condition is satisfied.

Approach-2: Now, the tricky bit is to achieve the same results without the the ! operator.


    public boolean validate() {
       return excluded || SecurityType.OTHER != this.type || 
              SecuritySubType.OTHER != this.subType ;
 }

It is achieved by using the reverse of the conditions shown within the paranthesis in the approach 1 with the 'or' operator instead of 'and'.



Here is the full code that you can experiment with

public class LogicalThinking1 {

 public static class Security {

  enum SecurityType {
   WARRANT, OPTION, OTHER
  }

  enum SecuritySubType {
   INVESTMENT, MARGINLENDING, OTHER
  }

  private boolean excluded;
  private SecurityType type;
  private SecuritySubType subType;

  public Security(boolean excluded, SecurityType type, SecuritySubType subType) {
   this.excluded = excluded;
   this.type = type;
   this.subType = subType;
  }

  // getters/setters and equals/hashCode and equals are omitted for
  // brevity

  public boolean validate() {
   //return !(!excluded && SecurityType.OTHER == this.type && SecuritySubType.OTHER == this.subType) ;
   return excluded || SecurityType.OTHER != this.type || SecuritySubType.OTHER != this.subType ;
  }

 }

 public static void main(String[] args) {
  //example only, need to cater for different input arguments like
  //false, OTHER, OTHER --> false
  //true, OTHER, OTHER  --> true
  //false, WARRANT, OTHER --> true
  //true, WARRANT, OTHER --> true
  //true, WARRANT, INVESTMENT --> true
  //false, WARRANT, INVENSTMENT --> true, etc. Basically 2 * 3 * 3 = 18 combinations are possible
  LogicalThinking1.Security security = new LogicalThinking1.Security(Boolean.FALSE, 
                                  LogicalThinking1.Security.SecurityType.WARRANT, 
                                  LogicalThinking1.Security.SecuritySubType.INVESTMENT);
  
  System.out.println("Validation:" + security.validate());
  
 }

}

Note: So, true && true && true is equivalent to !(false || false || false).


Q. Can you give a real life scenario where you may have to use the second form?
A. A typical real life scenario would be to implement the business validation rules. Some validation rules do change frequently due to legislative changes, etc and hard coding those rules within code is not a good idea. A more flexible approach would be to use a business rules engine like Drools or custom write your validation engine by storing the validation rules and relevant error messages in a database. This will enable the validation rules to be modified as it changes due to legislative changes or other business drivers. A very simplified database schema will look like

The rules are comma separated and the logical operator joining the rules is determined by the join_type. The join type can be either OR or AND.  The validation error message is displayed if the validation rule returns false. This means,  if the portfolio is not authorized and the cashAvailable is less than the cashDepletion then display the validation error message "There are insufficient funds". The cashAvailable, cashDepletion, and authorized are fields with corresponding getter methods in the bean "Portfolio". The version flag is important because you might be working in multiple streams of development sharing the same development database and you don't want a new rule that was added in one of the development streams to break the other streams. The validation engine will have code something similar to


boolean ruleResult = evaluateRule( .....);
if(!ruleResult) {
     displayValidationErrorMsg(....);
}


Q. Can you write code that will check if a given string input is a numeric?
A. You could use exception handling for this. If it throws an exception, it is not a numeric value.

public boolean isInteger( String input )  
{  
   try  
   {  
      Integer.parseInt(input);  
      return true;  
   }  
   catch(Exception e)  
   {  
      return false;  
   }  
}  

Alternatively, you could use regex (i.e. Regular Expressions)


public boolean isInteger( String input ) {
    if(input == null || input.length() == 0) {
    return false;
 }

 //using regex and conditional operator. '\d' means digit. Additional '\' to escape '\'.
    return if(input.replaceAll("\\d+","").length() > 0) ? false : true;
}


Labels: ,

2 Comments:

Anonymous Dhung said...

This section focuses on types of interview questions asked by the employers which are based on behavioral and technical questions.

9:20 PM, August 08, 2012  
Blogger javablog said...

I want more logical questions in java

1:33 AM, June 11, 2013  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home