w3resource

Java Exercises: Compare two files lexicographically

Java Input-Output: Exercise-6 with Solution

Write a Java program to compare two files lexicographically.

According to Wikipedia:
In mathematics, the lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters. This generalization consists primarily in defining a total order over the sequences (often called words in computer science) of elements of a finite totally ordered set, often called alphabet.

Sample Solution:

Java Code:

import java.io.File;
public class Exercise6 {
   public static void main(String[] args) 
   {
       String str1 = "Java exercises";
       String str2 = "Java exercises";
       String str3 = "Java examples";

       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);

    }
}

Sample Output:

str1 & str2 comparison: 0                                                                                     
str1 & str3 comparison: 4 

Flowchart:

Flowchart: Compare two files lexicographically

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to check if given pathname is a directory or a file.
Next: Write a Java program to get last modified time of a file.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH