javarevisited

javarevisited


How to compare Arrays in Java – Equals vs deepEquals Example

Posted: 30 Dec 2012 04:47 AM PST

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded method to compare primitive arrays e.g. int, long, float, double and Object arrays e.g. Arrays.equals(Object[] , Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null, If both array pointing to same Array Object or they must be of same length and contains same element in each index. In all other cases it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays. One of the tricky question in Java related to Array comparison is Difference between Arrays.equals() and Arrays.deepEquals() method.  Since both equals and deepEquals is used for array comparison, what is difference between them becomes important. Short answer of this questions is that, Array's equals() method does not perform deep comparison and fails logical comparison in case of nested Array,  on other hand deepEquals() perform deep comparison and returns logical comparison in case of nested array.
Read more »

How to append text into File in Java – FileWriter Example

Posted: 29 Dec 2012 09:15 PM PST

Some times we need to append text into File in Java instead of creating new File. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create file and directory in Java and how to read and write to text file in Java and in this Java IO tutorial we will see how to append text into file in Java. We are going to use standard FileWriter and  BufferedWriter approach to append text to File. One of the key point to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of File rather than writing on beginning of the File. In next section we will see complete Java program to append text into File in Java.  By the way you can also use FileOutputStream instead of FileWriter if you would like to write bytes, instead of text. Similar to FileWriter, FileOutputStream constructor also takes a boolean append argument to open connection to append bytes into File in Java.
Read more »


Post a Comment