Java Programming Exercies

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: 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?

New Content: Composer: Dependency manager for PHP, R Programming