Guava – Objects Class

Guava – Objects Class ”; Previous Next Objects class provides helper functions applicable to all objects such as equals, hashCode, etc. Class Declaration Following is the declaration for com.google.common.base.Objects class − @GwtCompatible public final class Objects extends Object Class Methods Sr.No Method & Description 1 static boolean equal(Object a, Object b) Determines whether two possibly-null objects are equal. 2 static <T> T firstNonNull(T first, T second) Deprecated. Use MoreObjects.firstNonNull(T, T) instead. This method is scheduled for removal in June 2016. 3 static int hashCode(Object… objects) Generates a hash code for multiple values. 4 static Objects.ToStringHelper toStringHelper(Class<?> clazz) Deprecated. Use MoreObjects.toStringHelper(Class) instead. This method is scheduled for removal in June 2016 5 static Objects.ToStringHelper toStringHelper(Object self) Deprecated. Use MoreObjects.toStringHelper(Object) instead. This method is scheduled for removal in June 2016. 6 static Objects.ToStringHelper toStringHelper(String className) Deprecated. Use MoreObjects.toStringHelper(String) instead. This method is scheduled for removal in June 2016. Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Objects Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java import com.google.common.base.Objects; public class GuavaTester { public static void main(String args[]) { Student s1 = new Student(“Mahesh”, “Parashar”, 1, “VI”); Student s2 = new Student(“Suresh”, null, 3, null); System.out.println(s1.equals(s2)); System.out.println(s1.hashCode()); System.out.println( Objects.toStringHelper(s1) .add(“Name”,s1.getFirstName()+” ” + s1.getLastName()) .add(“Class”, s1.getClassName()) .add(“Roll No”, s1.getRollNo()) .toString()); } } class Student { private String firstName; private String lastName; private int rollNo; private String className; public Student(String firstName, String lastName, int rollNo, String className) { this.firstName = firstName; this.lastName = lastName; this.rollNo = rollNo; this.className = className; } @Override public boolean equals(Object object) { if(!(object instanceof Student) || object == null) { return false; } Student student = (Student)object; // no need to handle null here // Objects.equal(“test”, “test”) == true // Objects.equal(“test”, null) == false // Objects.equal(null, “test”) == false // Objects.equal(null, null) == true return Objects.equal(firstName, student.firstName) // first name can be null && Objects.equal(lastName, student.lastName) // last name can be null && Objects.equal(rollNo, student.rollNo) && Objects.equal(className, student.className); // class name can be null } @Override public int hashCode() { //no need to compute hashCode by self return Objects.hashCode(className,rollNo); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. false 85871 Student{Name=Mahesh Parashar, Class=VI, Roll No=1} Print Page Previous Next Advertisements ”;

Guava – Primitive Utilities

Guava – Primitive Utilities ”; Previous Next As primitive types of Java cannot be used to pass in generics or in collections as input, Guava provided a lot of Wrapper Utilities classes to handle primitive types as Objects. Following is the list of useful primitive processing utilities − Sr.No Utility name & Description 1 Bytes Utility for primitive byte. 2 Shorts Utility for primitive short. 3 Ints Utility for primitive int. 4 Longs Utility for primitive long. 5 Floats Utility for primitive float. 6 Doubles Utility for primitive double. 7 Chars Utility for primitive char. 8 Booleans Utility for primitive boolean. Print Page Previous Next Advertisements ”;

Guava – String Utilities

Guava – String Utilities ”; Previous Next Guava introduces many advanced string utilities based on developers” experience in application development works. Following is the list of useful string based utilities − Sr.No Utility name & Description 1 Joiner Utility to join objects, string etc. 2 Splitter Utility to split string. 3 CharMatcher Utility for character operations. 4 CaseFormat Utility for changing string formats. Print Page Previous Next Advertisements ”;

Guava – Environment Setup

Guava – Environment Setup ”; Previous Next Local Environment Setup If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment. Java SE is freely available from the link Download Java. So you download a version based on your operating system. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories − Setting up the Path for Windows 2000/XP We are assuming that you have installed Java in c:Program Filesjavajdk directory − Right-click on ”My Computer” and select ”Properties”. Click on the ”Environment variables” button under the ”Advanced” tab. Now, alter the ”Path” variable so that it also contains the path to the Java executable. Example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting up the Path for Windows 95/98/ME We are assuming that you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end − ”SET PATH=%PATH%;C:Program Filesjavajdkbin” Setting up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. Example, if you use bash as your shell, then you would add the following line to the end of your ”.bashrc: export PATH=/path/to/java:$PATH” Popular Java Editors To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following − Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad. Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Download Guava Archive Download the latest version of Guava jar file from guava-18.0.jar. At the time of writing this tutorial, we have downloaded guava-18.0.jar and copied it into C:>Guava folder. OS Archive name Windows guava-18.0.jar Linux guava-18.0.jar Mac guava-18.0.jar Set Guava Environment Set the Guava_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we”ve extracted guava-18.0.jar in Guava folder on various Operating Systems as follows. OS Output Windows Set the environment variable Guava_HOME to C:Guava Linux export Guava_HOME=/usr/local/Guava Mac export Guava_HOME=/Library/Guava Set CLASSPATH Variable Set the CLASSPATH environment variable to point to the Guava jar location. Assuming, you have stored guava-18.0.jar in Guava folder on various Operating Systems as follows. OS Output Windows Set the environment variable CLASSPATH to %CLASSPATH%;%Guava_HOME%guava-18.0.jar;.; Linux export CLASSPATH=$CLASSPATH:$Guava_HOME/guava-18.0.jar:. Mac export CLASSPATH=$CLASSPATH:$Guava_HOME/guava-18.0.jar:. Print Page Previous Next Advertisements ”;

Guava – Throwables Class

Guava – Throwables Class ”; Previous Next Throwables class provides utility methods related to Throwable interface. Class Declaration Following is the declaration for com.google.common.base.Throwables class − public final class Throwables extends Object Class Methods Sr.No Method & Description 1 static List<Throwable> getCausalChain(Throwable throwable) Gets a Throwable cause chain as a list. 2 static Throwable getRootCause(Throwable throwable) Returns the innermost cause of throwable. 3 static String getStackTraceAsString(Throwable throwable) Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable. 4 static RuntimeException propagate(Throwable throwable) Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException then propagates. 5 static <X extends Throwable> void propagateIfInstanceOf(Throwable throwable, Class<X> declaredType) Propagates throwable exactly as-is, if and only if it is an instance of declaredType. 6 static void propagateIfPossible(Throwable throwable) Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException or Error. 7 static <X extends Throwable> void propagateIfPossible(Throwable throwable, Class<X> declaredType) Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, or declaredType. 8 static <X1 extends Throwable,X2 extends Throwable>void propagateIfPossible(Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, declaredType1, or declaredType2. Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Throwables Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java import java.io.IOException; import com.google.common.base.Objects; import com.google.common.base.Throwables; public class GuavaTester { public static void main(String args[]) { GuavaTester tester = new GuavaTester(); try { tester.showcaseThrowables(); } catch (InvalidInputException e) { //get the root cause System.out.println(Throwables.getRootCause(e)); } catch (Exception e) { //get the stack trace in string format System.out.println(Throwables.getStackTraceAsString(e)); } try { tester.showcaseThrowables1(); } catch (Exception e) { System.out.println(Throwables.getStackTraceAsString(e)); } } public void showcaseThrowables() throws InvalidInputException { try { sqrt(-3.0); } catch (Throwable e) { //check the type of exception and throw it Throwables.propagateIfInstanceOf(e, InvalidInputException.class); Throwables.propagate(e); } } public void showcaseThrowables1() { try { int[] data = {1,2,3}; getValue(data, 4); } catch (Throwable e) { Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class); Throwables.propagate(e); } } public double sqrt(double input) throws InvalidInputException { if(input < 0) throw new InvalidInputException(); return Math.sqrt(input); } public double getValue(int[] list, int index) throws IndexOutOfBoundsException { return list[index]; } public void dummyIO() throws IOException { throw new IOException(); } } class InvalidInputException extends Exception { } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. InvalidInputException java.lang.ArrayIndexOutOfBoundsException: 4 at GuavaTester.getValue(GuavaTester.java:52) at GuavaTester.showcaseThrowables1(GuavaTester.java:38) at GuavaTester.main(GuavaTester.java:19) Print Page Previous Next Advertisements ”;