tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Google Guava > Basic > Check State Precondition

Check State Precondition 

Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using Preconditions.checkState() API. It throws IllegalStateException if the given expression evaluates to false.

File Name  :  
com/bethecoder/tutorials/guava/common/Student.java 
   
package com.bethecoder.tutorials.guava.common;

public class Student {

  private String name;
  private int age;
  private String hobby;

  public Student() {
  }

  public Student(String name, int age, String hobby) {
    super();
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }
  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  
  public boolean isKid() {
    return age < 5;
  }
}
   

File Name  :  
com/bethecoder/tutorials/guava/base_tests/CheckStatePreTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.guava.base_tests;

import com.bethecoder.tutorials.guava.common.Student;
import com.google.common.base.Preconditions;

public class CheckStatePreTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    //Throws IllegalStateException - if expression is false
    //Preconditions.checkState(expression, errorMessage)
    
    Student student = new Student("Sriram"2"Chess");
    Student student2 = new Student("Charan"8"Cricket");
    
    /**
     * Negative case
     */
    try {
      Preconditions.checkState(student2.isKid()
        "This program requires Students below 5 years, but found %s", student2.getAge());
    catch (IllegalStateException e) {
      System.out.println(e);
    }
    
    /**
     * Positive case
     */
    Preconditions.checkState(student.isKid()
        "This program requires Students below 5 years, but found %s", student.getAge());
    
    System.out.println("Thanks for providing valid input");
  }

}
   

It gives the following output,
java.lang.IllegalStateException: This program requires Students below 5 years, but found 8
Thanks for providing valid input



 
  


  
bl  br