Wednesday, 21 June 2017

Matrix Addition - Java Program

When you add two matrices addition is done index wise you add the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

As example – If you are adding two matrices of order 3X3

Thus the resultant matrix is -

Also remember these points when adding one matrix with another -

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix added with (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix addition Java program

 
import java.util.Scanner;

public class MatrixAddition {

    public static void main(String[] args) {
        int rowM, colM;
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter Number of Rows and Columns of Matrix : ");
        rowM = in.nextInt();
        colM = in.nextInt();
        
        int M1[][] = new int[rowM][colM];
        int M2[][] = new int[rowM][colM];
        int resMatrix[][] = new int[rowM][colM];
        
        System.out.print("Enter elements of First Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M1[i][j] = in.nextInt();
            }
        }
        System.out.println("First Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M1[i][j]+"\t");
            }
            System.out.println();
        }
        
        System.out.print("Enter elements of Second Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M2[i][j] = in.nextInt();
            }
        }
        System.out.println("Second Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M2[i][j] + "\t");
            }
            System.out.println();
        }
        
        // Addition logic 
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                resMatrix[i][j] = M1[i][j] + M2[i][j];
            }
        }
        
        // Printing the result matrix 
        System.out.println("Result Matrix : " );
        for(int i = 0; i < resMatrix.length; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +resMatrix[i][j]+"\t");
            }
            System.out.println();
        }

    }

}

Output

Enter Number of Rows and Columns of Matrix :  3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1

Result Matrix : 
 3  10  5 
 2  9  12 
 13  11  3 

That's all for this topic Matrix Addition - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Matrix Multiplication Java Program
  2. Array in Java
  3. How to remove duplicate elements from an array - Java Program
  4. How to swap or exchange two numbers without using any temporary variable - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 19 June 2017

Object class in Java

Object class is root class of all classes in Java. All classes descend from object directly or indirectly. It is implicitly extended by a class if it is not extending any other class. In case, a class is extending any other class then also it extends object as a multi-level hierarchy inheritance.

As example if we have a class Employee

public class Employee {

}

It is same as

public class Employee extends Object {

}

Since it is implicitly extended by a class so you don’t need to write explicitly that your class is extending Object class.

Methods in Object class

Every class you use or write inherits the instance methods of Object. In your class you may not need to use any of these methods. In case you need to use methods inherited from the Object class you may need to override them with code that is specific to your class.

Method Description
clone()Creates and returns a copy of this object.
boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
protected void finalize()Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
Class<?> getClass()Returns the runtime class of this Object.
int hashCode()Returns a hash code value for the object.
void notify()Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()Wakes up all threads that are waiting on this object's monitor.
String toString()Returns a string representation of the object.
void wait()Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
void wait(long timeout)Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
void wait(long timeout, int nanos)Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

The clone() Method

If a class, or one of its superclasses, implements the Cloneable interface, you can use the clone() method to create a copy from an existing object. To create a clone, you write:

cloneableObject.clone();

The equals() and hashCode() Method

The equals() method compares two objects for equality and returns true if they are equal.

The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal. If you override the equals() method, you must also override the hashCode() method as well.

The finalize() Method

The Object class provides a callback method, finalize(), that may be invoked on an object when it becomes garbage. Though Object's implementation of finalize() does nothing and you have to override finalize() to do cleanup, such as freeing resources.

The getClass() Method

The getClass() method returns a Class object, which has methods you can use to get information about the class, such as its name (getSimpleName()), its superclass (getSuperclass()), and the interfaces it implements (getInterfaces()).

Note that you cannot override getClass method.

The toString() Method

The Object's toString() method returns a String representation of the object, which is very useful for debugging.

You should always consider overriding the toString() method in your classes. IN your class. You can use toString() along with System.out.println() to display a text representation of an object. In System.out.println() you can provide fields of an object to get all the values and verify those values.

wait() and notify() methods

wait() method causes the currently executing thread to wait.

notify() method wakes up a single thread waiting on this object’s monitor.

Advantages of Object class

  • Since Object class is the super class for all the classes so Object class can be used as a parameter or reference for any class object which helps in making your code more generic and following object oriented principles like polymorphism and dynamic method dispatch.
  • Though with introduction of Generics in Java 5, Object class has lost some of its sheen and now it is not that ubiquitous in code as it used to be. Before generics all collection were storing objects inherently as Object and we needed to typecast them (by downcasting from Object class reference to your class object) to the custom object while retrieving them.
  • Object class also provides some methods that are applicable to all classes and provides basic implementation too which can be overridden by the class wanting to use those methods.

That's all for this topic Object class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. instanceof Operator in Java
  2. String in Java
  3. Type erasure in Java Generics
  4. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  5. final Vs finally Vs finalize

You may also like -

>>>Go to Java Basics page

Friday, 16 June 2017

How to remove duplicate elements from an array - Java Program

How to remove duplicate elements from an array is a frequently asked interview question and you may be asked to do it without using any of the collection data structure like List or Set or you may be asked to do it using Collection API classes first and then without using any of those classes.

In this post we’ll see code for removal of duplicate elements in an array using Collection API classes and without it.

Using Collection API

One way to remove duplicate elements from an array is to copy your array elements to a HashSet. As you know HashSet only stores unique elements so any repetition of an element will be discarded. Using this property of HashSet once you copy all the array elements to a HashSet you’ll have a Set with only unique elements. Now you can again copy the elements from your Set to create an array which will be your array with duplicate elements removed.

Example code with HashSet

 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicatesUsingSet(intArr);
        System.out.println("Original array");
        for(int i : intArr){
            System.out.print(i+" ");
        }
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }
    
    /**
     * 
     * @param input
     * @return
     */
     public static int[] removeDuplicatesUsingSet(int[] input){
      // Adding array elements to a list
      List<Integer> tempList = new ArrayList<Integer>();
      for(int i : input){
          tempList.add(i);
      }
      // creating a set using list     
      Set<Integer> set = new HashSet<Integer>(tempList);
      Integer[] output = new Integer[set.size()];
      int[] arrOut = new int[output.length];
      set.toArray(output);
      int j =0;
      for(Integer i : output){
       arrOut[j++] = i;
      }
      return arrOut;
    }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are -

  1. If you are using Set then ordering with in the array doesn’t matter i.e. Array doesn’t have to be sorted.
  2. Ordering of the original array will not be retained once elements are stored in the Set.
  3. In the above code I have used int[] array (array of primitives) that’s why there are some extra steps like creating Array of Integer[] (Integer objects) as toArray() method of the Set works only with objects. If you have an array of objects then you don’t need these extra steps.

Example code with LinkedHashSet

In the above code with HashSet ordering of the array elements is not retained, if you want ordering to be retained then use LinkedHashSet instead.

 
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicatesUsingSet(intArr);
        System.out.println("Original array");
        for(int i : intArr){
            System.out.print(i+" ");
        }
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }
    
    /**
     * 
     * @param input
     * @return
     */
     public static int[] removeDuplicatesUsingSet(int[] input){
      // Adding array elements to a list
      List<Integer> tempList = new ArrayList<Integer>();
      for(int i : input){
          tempList.add(i);
      }
      // creating a set using list     
      Set<Integer> set = new LinkedHashSet<Integer>(tempList);
      Integer[] output = new Integer[set.size()];
      int[] arrOut = new int[output.length];
      set.toArray(output);
      int j =0;
      for(Integer i : output){
       arrOut[j++] = i;
      }
      return arrOut;
    }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 5 6 12 7 3 8 

Now you can see ordering of the array elements is retained. For duplicate elements first occurrence of the element is retained.

Example code without using Collection

If you have to remove duplicate elements of the array without using any of the Collection API classes then you can use the following code.

public class DuplicateRemoval1 {
    /**
     * 
     * @param input
     * @return
     */
    public static int[] removeDuplicates(int[] intArr){
        int i = 1;
        int j = 0;
        Arrays.sort(intArr);
        System.out.println("Sorted array");
        for(int x : intArr){
            System.out.print(x+" ");
        }
        while(i < intArr.length){
            if(intArr[i] == intArr[j]){
                i++;
            }else{
                intArr[++j] = intArr[i++];
            }   
        }
        // This is required to truncate the size of the array
        // otherwise array will retain its original size
        int[] output = Arrays.copyOf(intArr, j+1);
        return output;
    }

    public static void main(String[] args) {
        int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
        int[] outArr = removeDuplicates(intArr);
        System.out.println("");
        System.out.println("after removal");
        for(int i : outArr){
            System.out.print(i+" ");
        }
    }

}

Output

Sorted array
1 1 2 2 3 5 6 7 8 12 12 12 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are -

  1. Array has to be sorted in order for this code to work properly that is why array is sorted using Arrays.sort() method.
  2. Once an array is created it will have a fixed size that is why Arrays.copyOf() method is used which can truncate the array to given size. That is required as array size may reduce after removing duplicates.

Time and space complexity

As per the description of the Arrays.sort() method its time complexity is O(n log(n)). Then array is traversed in the while loop and then array is copied. That time complexity will be O(2n) thus the time complexity of the above code is O(n log(n))+O(2n). While the space complexity is O(1).

Using Java Stream

Java Stream API (From Java 8) also provides an option to remove duplicate elements from an array.

int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
int tempArr[] = Arrays.stream(intArr).distinct().toArray();
       
System.out.println("");
System.out.println("after removal");
for(int i : tempArr){
 System.out.print(i+" ");
}

Output

after removal
1 2 5 6 12 7 3 8

That's all for this topic How to remove duplicate elements from an array. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to remove duplicate elements from an ArrayList in Java
  2. Matrix Multiplication Java Program
  3. How to Sort elements in different order in TreeSet
  4. Array in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 14 June 2017

How to swap or exchange two numbers without using any temporary variable - Java Program

How to swap or exchange two numbers without using any temporary variable is asked quite frequently in Java interview questions.

This post shows one way to solve this -

public class Swap {
 public static void main(String[] args) {
  int a = 7;
  int b = 8;
  
  System.out.println("value of a - " + a);
  System.out.println("value of b - " + b);
  
  // Swapping logic
  a = a + b;
  b = a - b;
  a = a - b;
  System.out.println("After swap value of a - " + a);
  System.out.println("After swap value of b - " + b);
  
 }
}

Output

value of a - 7
value of b - 8
After swap value of a - 8
After swap value of b - 7

That's all for this topic How to swap or exchange two numbers without using any temporary variable. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and wait-notify
  2. Factorial program in Java
  3. Fibonacci series program in Java
  4. Displaying prime numbers - Java program
  5. How to reverse number - Java Program

You may also like -

>>>Go to Java Programs page

Monday, 12 June 2017

Difference between equals() method and equality operator == in Java

Difference between equals() method and equality operator “==” is a frequently asked interview question. At the same time it may be a bit confusing for the first-time Java programmer to get the subtle differences between equals and “==”.

So in this post let’s try to find the exact differences between the equals() method and equality operator “==” and where does it make sense to use what.

Equality operator “==”

equality operator “==” can be used to compare primitive values as well as objects. Though it works just fine with primitive values but in case of objects “==” will compare the references of the objects not the content of the objects.

equals() method

If you want to compare the actual contents of the objects then you will have to override equals method, which is present in Object class so available to all the other classes. Though the implementation in the Object class is to compare using == operators so default implementation will compare references.

You will have to override equals method in order to compare your custom class objects.

Difference between equals and “==”

Based on what we have seen so far we can surely list some difference between equals and equality operator “==”.

  1. “==” is an operator where as equals is a method.
  2. “==” can be used with primitive values as well as with objects. Equals method can only be used with objects.
  3. When “==” is used for comparing objects it will compare their references not the actual content. Equals method can compare the actual content of the object but you will have to provide your own implementation for determining the equality of two objects.

Example code

Let’s move on to see some hands-on code to test the theory stated so far.

public class EqualsMethodDemo {

 public static void main(String[] args) {
  String str1 = "Test";
  String str2 = new String("Test");
  
  System.out.println(str1 + " == " + str2 + " - " + (str1 == str2));
  
  System.out.println(str1 + " != " + str2 + " - " + (str1 != str2));

 }
}

Output

Test == Test - false
Test != Test – true

Here two strings are created; first one as a string literal and second using new operator so that reference for both the strings are different. Now comparison of these two strings is done using equality “==” operator and not equal (“!=”) operator.

It can be seen that equal returns false even though the content of both the string is same. That is because references of both the strings are different.

Code using equals method

Now if you use equals method to compare the strings then the class used above can be rewritten as -

public class EqualsMethodDemo {

 public static void main(String[] args) {
  String str1 = "Test";
  String str2 = new String("Test");
  
  System.out.println(str1 + " == " + str2 + " - " + str1.equals(str2));
 }
}

Output

Test == Test - true

Now the output is true as equals method is comparing the content of both the strings.

Here note that String class as well as wrapper classes like Integer, Long provide implementation of equals method which compares the content. Same way for your own classes you will have to provide your own implementation of equals method.

Code with Integer

As mentioned above Integer class provides implementation of equals method so that too will compare the content when equal method is used.

public class EqualsMethodDemo {

 public static void main(String[] args) {
  Integer num1 = new Integer(7);
  
  Integer num2 = new Integer(7);
  
  System.out.println(num1 + " == " + num2 + " - " + (num1 == num2));
  
  System.out.println(num1 + " == " + num2 + " - " + num1.equals(num2));
 }
}

Output

7 == 7 - false
7 == 7 - true

That's all for this topic Difference between equals() method and equality operator == in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Equality and Relational Operators in Java
  2. Conditional Operators in Java
  3. String comparison in Java
  4. Overriding hashCode() and equals() method in Java

You may also like -

>>>Go to Java Basics page

Thursday, 8 June 2017

Conditional Operators in Java

The conditional operators Conditional-AND (&&) and Conditional-OR (||) perform operations on two boolean expressions. Result is also a boolean value of true or false based on whether condition is satisfied or not.

How Conditional operator works

Conditional-AND – If any of the two boolean expressions is false then the result is false.

As example - If in condition (A && B), expression A evaluates to false then result is false even if expression B evaluates to true. Let’s make it clear with a table.

A B A&&B
FalseFalseFalse
TrueFalseFalse
TrueTrueTrue
TrueFalseFalse

Conditional-OR - If any of the two boolean expressions is true then the result is true.

As example - If in condition (A || B), expression A evaluates to true then result is true even if expression B evaluates to false. Let’s make it clear with a table.

A B A||B
FalseFalseFalse
TrueFalseTrue
TrueTrueTrue
TrueFalseTrue

Example code

public class ConditionalDemo {

    public static void main(String[] args) {
        int a = 7;
        int b = 8;
        int c = 5;
        
        // This condition evaluates to true
        if((a > c) && (b > c)){
            System.out.println("a and b both are greater than c");
        }
        
        // This condition evaluates to false
        if((a < c) && (b > c)){
            System.out.println("a and b both are greater than c");
        }
        
        // This condition evaluates to true
        if((a < c) || (b > c)){
            System.out.println("OR Condition (a < c) OR (b > c) ");
        }
        
        // This condition evaluates to true
        if(((a > c) && (b > c)) || (c < 3)){
            System.out.println("Both AND and OR used - First 
            expression (a > c) && (b > c) is true so OR 
            condition is true ");
        }
    }
}

Output

a and b both are greater than c
OR Condition (a < c) OR (b > c) 
Both AND and OR used - First expression (a > c) && (b > c) is 
true so OR condition is true 

Short-circuiting behavior

These conditional operators (&&, ||) exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

As explained above Conditional-AND evaluates to false if any of the two expressions is false. In that case if first expression evaluates to false there is no need to evaluate the second expression as result is going to be false anyway.

Same way for Conditional-OR if the first expression evaluates to true there is no need to evaluate the second expression because result is going to be true anyway.

Example code

Let us try to understand this short circuiting behavior with few examples.

In this example class there are two methods getCompValue1() and getCompValue2() and a conditional expression if(getCompValue1(7) && getCompValue2(5)) which is evaluated.

public class SCDemo {

    public static void main(String[] args) {
        if(getCompValue1(7) && getCompValue2(5)){
            System.out.println("Conditional expression evaluates to true");
        }else{
            System.out.println("Conditional expression evaluates to false");
        }

    }
    
    static boolean getCompValue1(int num){
        System.out.println("In getCompValue1 with value " + num);
        return num > 6;
    }
    
    static boolean getCompValue2(int num){
        System.out.println("In getCompValue2 with value " + num);
        return num > 6;
    }
}

Output

In getCompValue1 with value 7
In getCompValue2 with value 5
Conditional expression evaluates to false

Here note that return value of method getCompValue1() is true (7 > 6). That is why second expression (getCompValue2(5)) is also evaluated which evaluates to false (5 > 6). Thus the conditional expression evaluates to false.

Now if expression is changed in the getCompValue1 in such a way that this method returns false then notice what happens.

Class with getCompValue1() method changed

public class SCDemo {

    public static void main(String[] args) {
        if(getCompValue1(7) && getCompValue2(5)){
            System.out.println("Conditional expression evaluates to true");
        }else{
            System.out.println("Conditional expression evaluates to false");
        }

    }
    
    static boolean getCompValue1(int num){
        System.out.println("In getCompValue1 with value " + num);
        return num > 8;
    }
    
    static boolean getCompValue2(int num){
        System.out.println("In getCompValue2 with value " + num);
        return num > 6;
    }
}

Output

In getCompValue1 with value 7
Conditional expression evaluates to false

Now see the output, second expression is not even evaluated, where getCompValue2() method is called. Because first expression itself is false now (7 > 8). That’s what is "short-circuiting" behavior, where second operand is evaluated only if needed.

Another Short-circuiting example

Let us see another example, many times it happens that check for null or zero and we go on to evaluate expression only if value is not zero or null.

As example

 
if(val1 != 0 && (val2/val1 > 5))

Here it is verified if val1’s value is zero or not. If it is zero expression val1 != 0 itself becomes false so the second expression is not evaluated. That saves you from a run-time exception in case val1 is zero.

That's all for this topic Conditional Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Arithmetic and Unary Operators in Java
  2. Equality and Relational Operators in Java
  3. Ternary operator in Java
  4. instanceof Operator in Java
  5. Switch-Case statement in Java

You may also like -

>>>Go to Java Basics page

Tuesday, 6 June 2017

Equality and Relational Operators in Java

The equality and relational operators evaluate the relationship between the values of the operands. These operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

The equality and relational operators generate a boolean result. If the relationship is true then the result is true if relationship is untrue the result is false.

Equality and Relational operators description

Operator Description
==equal to
!=not equal to
>greater than
>=greater than or equal to
<less than
<=less than or equal to

Note that you must use "==" when testing two primitive values for equality, not "=" which is assignment operator.

Example code

public class RealationalDemo {

    public static void main(String[] args) {
        int a = 7;
        int b = 5;
        int c = 7;
        
        // This should get printed
        if(a == c){
            System.out.println("Values of a and c are equal");
        }
        
        // This won't be printed
        if(a == b){
            System.out.println("Values of a and b are equal");
        }
        
        if(a != b){
            System.out.println("Values of and b are not equal");
        }
        
        if(a > b){
            System.out.println("a is greater than b");
        }
        
        if(a >= c){
            System.out.println("a is greater than or equal to c");
        }
        
        // This won't be printed
        if(a < b){
            System.out.println("a is less than b");
        }
        
        if(b < a){
            System.out.println("b is less than a");
        }
    }

}

Output

Values of a and c are equal
Values of and b are not equal
a is greater than b
a is greater than or equal to c
b is less than a

That's all for this topic Equality and Relational Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Arithmetic and Unary Operators in Java
  2. Conditional Operators in Java
  3. Ternary operator in Java
  4. instanceof Operator in Java
  5. BigDecimal in Java

You may also like -

>>>Go to Java Basics page

Thursday, 1 June 2017

Arithmetic and Unary Operators in Java

For basic mathematical operation the Java programming language provides arithmetic operators like addition (+), subtraction (-), division (/), multiplication(*) and modulus (%, which divides one operand by another and returns the remainder as its result).

Arithmetic operators

Operator Description
+Additive operator (also used for String concatenation)
-Subtraction operator
*Multiplication operator
/Division operator
%Remainder operator

Example code for arithmetic operators

public class ArithmeticDemo {

 public static void main(String[] args) {
  int num1 = 3;
  int num2 = 4;
  int result = num1 + num2;
  System.out.println("Addition result - " + result);
  // Subtraction
  result = result - 3;
  System.out.println("Subtraction result - " + result);
  // Division
  result = result/2;
  System.out.println("Division result - " + result);
  // Multiplication
  result = result * 6;
  System.out.println("Multiplication result - " + result);
  // Modulo division
  result = result % 8;
  System.out.println("Modulo division result - " + result);
  
  // overloaded + operator for string concatenation
  String str1 = "This is ";
  String str2 = "a string";
  String concatString = str1 + str2;
  System.out.println("Concatenated String " + concatString);
 }
}

Output

Addition result - 7
Subtraction result - 4
Division result - 2
Multiplication result - 12
Modulo division result - 4
Concatenated String This is a string

Compound assignment operator

You can also combine the arithmetic operator with the assignment operator to create compound assignments. For example x = x + 7; can also be written as x += 7;

Operator Description
+=Addition assignment
–=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment

Compound assignment operator example code

public class OperatorDemo {

 public static void main(String[] args) {
  int x = 5;
  int y = 6;
  int z = 7;
  int p = 4;
  int q = 16;
  
  x += 4;
  System.out.println("x - " + x);
  
  y -= 2;
  System.out.println("y - " + y);
  
  z *= 3;
  System.out.println("z - " + z);
  
  p /= 2;
  System.out.println("p - " + p);
  
  q %= 3;
  System.out.println("q - " + q);

 }
}

Output

x - 9
y - 4
z - 21
p - 2
q – 1

Unary operators

Operator Description
+Unary plus operator; indicates positive value (numbers are positive by default though)
-Unary minus operator; negates an expression
++Increment operator; increments a value by 1
--Decrement operator; decrements a value by 1
!Logical complement operator; inverts the value of a boolean

Example code

Let’s see an example where unary plus operator, unary minus operator and logical component operator are used.

public class OperatorDemo {

 public static void main(String[] args) {
  // unary plus operator
  int x = +5;
  System.out.println("x = " + x);
  
  // unary minus operator
  x = -x;
  System.out.println("x = " + x);
  
  boolean flag = false;
  System.out.println("flag = " + flag);
  // logical component operator
  System.out.println("flag = " + !flag);

 }

}

Output

x = 5
x = -5
flag = false
flag = true

Increment and decrement operator

The increment operator increases its operand value by 1. For example x = x + 1; can be written as x++; using increment operator.

Same way decrement operator decreases its operand value by 1. For example x = x – 1; can be written as x--; using decrement operator.

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. For example prefix code ++x; or the postfix code x++; both will result in x incremented by one.

Difference between prefix and postfix is that in prefix version operand is incremented/decremented and that value is used in the expression. Whereas in postfix version original value is used in the expression and then the operand is incremented/decremented.

As example -

x = 7;
y = ++x;

Here y has the value 8 because the operand is incremented before using it in expression.

X = 7;
y = x++;

Here y has the value 7 because the original value is used in the expression and then the operand is incremented. So x is 8 but y has the original value of x which was 7.

Example code

public class OperatorDemo {

 public static void main(String[] args) {
  // prefix
  int x = 5;
  int y = ++x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  // postfix
  int a = 8;
  int b = a++;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
  y = --x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  b = a--;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
 }

}

Output

x - 6
y - 6
a - 9
b - 8
x - 5
y - 5
a - 8
b - 9

That's all for this topic Arithmetic and Unary Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Conditional Operators in Java
  2. Ternary operator in Java
  3. instanceof Operator in Java
  4. BigDecimal in Java
  5. Switch-Case statement in Java

You may also like -

>>>Go to Java Basics page

Monday, 29 May 2017

Nested class and Inner class in Java

In Java programming language you can define a class within another class. Such a class is called nested class.

Nested class categories

Nested classes are divided into two categories -

  • Static nested classes - Nested classes that are declared static are called static nested classes.
  • Non-static nested classes - Nested classes that are not static are called Non-static nested classes. They are known better as inner classes.

General form of static nested class

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
   
}

General form of inner class

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

Access modifiers for Nested classes

Since nested class is a member of its enclosing class, a nested class can have any of the access modifiers; private, public, protected, or package private. Note that outer classes can only be declared public or package private.

Benefits of using Nested Classes

  1. Nested classes provide a way to logically group classes that are only used in one place.
    If a class is useful to only one other class, then it makes sense to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  2. It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  3. It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

Static nested class example code

public class NestedDemo {
 int num = 10;
 public static class Nested{
  NestedDemo nd = new NestedDemo();
  private int quantity = 10;
  void msg(){
   System.out.println("data is "+ nd.num * quantity);
  }
 }
 public static void main(String[] args) {
  NestedDemo.Nested nested = new NestedDemo.Nested();
  nested.msg();
 }
}

Output

data is 100

Points to note about static nested class

  1. Just like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference.
  2. Static nested classes are accessed using the enclosing class name: NestedDemo.Nested

Inner class

An inner class is a nested class that is not static. Inner class has access to all the members (fields and methods) of the outer class including those with access modifier as private.

Let’s see a simple inner class example here to make it clearer.

Inner class example code

In this example there is a OuterClass with one private field, a method createInner() and an inner class InnerClass. Inner class has one method displayMsg() which takes String as argument.
class OuterClass {
 private int outerVar = 12;
 // Inner class
 class InnerClass{
  void displayMsg(String msg){
   System.out.println("Message is - " + msg);
   System.out.println("Outer class variable - " + outerVar);
  }
 }
 
 void createInner(){
  InnerClass ic = new InnerClass();
  ic.displayMsg("Calling From a method with in the Outer class");
 }
}

public class ICDemo {
 public static void main(String[] args) {
  OuterClass oc = new OuterClass();
  oc.createInner();
  // Creating inner class object using outer class object
  OuterClass.InnerClass oic = oc.new InnerClass();
  oic.displayMsg("Calling from outside the OuterClass scope");
 }
}

Output

Message is - Calling From a method with in the Outer class
Outer class variable - 12
Message is - Calling from outside the OuterClass scope
Outer class variable - 12

Points to note

There are several points of interest to note here about the inner classes –

  1. From the output you can see that inner class has access to fields and methods of the outer class, even if they are private. In the displayMsg() method of the inner class outerVar variable is accessed which is private and resides with in the scope of outer class.
  2. If you want to make an object of the inner class with in a non-static method of the outer class you don’t need to qualify it with Outer class name. Since createInner() method is a method of the outer class and it is not static you can create an object of the inner class directly.
  3. If you want to make an object of the inner class outside the scope of the outer class or from a method with in the outer class which is static you have to qualify inner class with the outer class so the type of the object would be specified as OuterClassName.InnerClassName. You can see example of object creation of inner class that way in the main method as it resides in another class ICDemo.
  4. An inner class can be private, public, protected or package-private. Note that normal class can only be public or package-private (default).

Types of inner classes

Apart from non-static nested class (also known as member inner class) there are two additional types of inner classes.

  • Local inner class
  • Anonymous inner class

Local inner class

Local inner classes are inner classes that can be defined within a block, here block means any group of zero or more statements between balanced braces. Generally you will find local inner classes defined within a method body.

Local inner class example

Let’s see an example of local inner class where inner class is defined in the method msg. Here Local inner class is also implementing an interface Message.

package org.prgm;
// Interface
interface Message{
 String readMsg();
}

class Outer {
 private int outerVar = 12;
 public Message msg(String str){
  // Local variable - it has to be final or
  // effectively final
  String hello = "Hello ";
  // Local Inner class
  class InnerMsg implements Message{
   
   private String msg;
   
   InnerMsg(String msg){
    this.msg = msg;
   }
   @Override
   // implementing interface method
   public String readMsg() {
    //hello = "Hi";
    System.out.println("I can read outer class variable its value is - " + outerVar );
    return hello + msg;
   }
   
  }
  return new InnerMsg(str);
  
 }

}
public class ICLocalDemo {

 public static void main(String[] args) {
  Outer outer = new Outer();
  Message message = outer.msg("Local Inner Class");
  String temp = message.readMsg();
  System.out.println("temp -- " + temp);
  
 }

}

Output

I can read outer class variable its value is - 12
temp -- Hello Local Inner Class

Points to note

There are several points of interest in the above code so let’s go through those points and try to get a better explanation.

  1. Here inner class InnerMsg is defined with in the method msg that is why it is local inner class as it is local to the method msg.
  2. Local inner class can access members of the enclosing class, you can see that int variable outerVar is accessed with in the inner class InnnerMsg.
  3. A local class has access to local variables (variables defined inside the method body). However, a local class can only access local variables that are declared final (before Java 8).
  4. Starting in Java SE 8, local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final. In the method readMsg() if you uncomment the line - //hello = "Hi"; You will get the error “Local variable hello defined in an enclosing scope must be final or effectively final” if you are running this code in Java 8. If you are using version lesser than 8 then it will ask you to declare hello as final.
  5. In the above code one thing to note is that inner class implements an interface. Doing that you are abiding to a very important point of object oriented programming – Abstraction. If you have noticed the return type of the method msg is interface Message. That way your implementation of the inner class is completely hidden.

Anonymous inner class

Anonymous inner class is a type of local inner class that has no name. You will always declare anonymous inner class as subclass or as implementation of an interface. Note that you cannot declare constructors in an anonymous class.

Anonymous inner class example code

Let’s implement the same example as above as an anonymous inner class. There is an interface Message and that is implemented as an anonymous inner class with in the method msg.

//Interface
interface Message{
 String readMsg();
}

class MessageOuter {
 private int outerVar = 12;
 public Message msg(String str){
  // Local variable - it has to be final or
  // effectively final
  String hello = "Hello ";
  return new Message(){
   @Override
   public String readMsg() {
    //hello = "Hi";
    System.out.println("I can read outer class variable its value is - " + outerVar );
    return hello + str;
   }
   
  }; // required to have semicolon
 }
}

/**
 * 
 * 
 *
 */
public class ICAnonymousDemo {

 public static void main(String[] args) {
  MessageOuter mo = new MessageOuter();
  Message msg = mo.msg("Anonymous Inner Class");
  System.out.println("Message is - " + msg.readMsg());

 }
}

Output

I can read outer class variable its value is - 12
Message is - Hello Anonymous Inner Class

Points to note

There are several points of interest in the above code so let’s go through those points and try to get a better explanation.

  1. Here inner class with in the method msg is an anonymous inner class. It contains a new operator, name of the interface it is implementing (it can also extend a class), and class declaration body with in the braces.
  2. Because an anonymous class definition is an expression, it must be part of a statement. That is why there is a semicolon after the closing brace.
  3. Anonymous inner class can access members of the enclosing class, you can see that int variable outerVar is accessed with in the method of the anonymous inner class.
  4. Anonymous inner class has access to local variables (variables defined inside the method body). Same rules apply as in the case of local inner class.
  5. You cannot declare constructors in an anonymous class as it has no name.

That's all for this topic Nested class and Inner class in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Serialization in Java
  2. Object cloning in java
  3. final in Java
  4. effectively final in Java 8
  5. Lambda expressions in Java 8

You may also like -

>>>Go to Java advance topics page

Wednesday, 24 May 2017

How to untar a file - Java Program

This post shows how to untar a tar file. It has both the steps to first uncompress a .tar.gz file and later untar it.

Using Apache Commons Compress

Apache Commons Compress library is used in the code for untarring a file. You can download it from here – https://commons.apache.org/proper/commons-compress/download_compress.cgi.

Make sure to add commons-compress-xxx.jar in your application’s class path. I have used commons-compress-1.13 version.

Example Code

This Java program has two methods deCompressGZipFile() method is used to uncompress a .tar.gz file to get a .tar file. Using unTarFile() method this .tar file is untarred.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;

public class UnTarDemo {

    public static void main(String[] args) {
        // Path to input file, which is a 
        // tar file compressed to create gzip file
        String INPUT_FILE = "G:\\Test.tar.gz";
        // This folder should exist, that's where
        // .tar file will go
        String TAR_FOLDER = "G:\\TarFile";
        // After untar files will go to this folder
        String DESTINATION_FOLDER = "G:\\Temp";
        UnTarDemo unTarDemo = new UnTarDemo();
        try {
            File inputFile = new File(INPUT_FILE);
            String outputFile = getFileName(inputFile, TAR_FOLDER);
            System.out.println("outputFile " + outputFile);
            File tarFile = new File(outputFile);
            // Calling method to decompress file
            tarFile = unTarDemo.deCompressGZipFile(inputFile, tarFile);
            File destFile = new File(DESTINATION_FOLDER);
            if(!destFile.exists()){
                 destFile.mkdir();
            }
            // Calling method to untar file
            unTarDemo.unTarFile(tarFile, destFile);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 
     * @param tarFile
     * @param destFile
     * @throws IOException
     */
    private void unTarFile(File tarFile, File destFile) throws IOException{
        FileInputStream fis = new FileInputStream(tarFile);
        TarArchiveInputStream tis = new TarArchiveInputStream(fis);
        TarArchiveEntry tarEntry = null;
        
        // tarIn is a TarArchiveInputStream
        while ((tarEntry = tis.getNextTarEntry()) != null) {
            File outputFile = new File(destFile + File.separator + tarEntry.getName());
            
            if(tarEntry.isDirectory()){
                
                System.out.println("outputFile Directory ---- " 
                    + outputFile.getAbsolutePath());
                if(!outputFile.exists()){
                    outputFile.mkdirs();
                }
            }else{
                //File outputFile = new File(destFile + File.separator + tarEntry.getName());
                System.out.println("outputFile File ---- " + outputFile.getAbsolutePath());
                outputFile.getParentFile().mkdirs();
                //outputFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(outputFile); 
                IOUtils.copy(tis, fos);
                fos.close();
            }
        }
        tis.close();
    }
    
    /**
     * Method to decompress a gzip file
     * @param gZippedFile
     * @param newFile
     * @throws IOException
     */
    private File deCompressGZipFile(File gZippedFile, File tarFile) throws IOException{
        FileInputStream fis = new FileInputStream(gZippedFile);
        GZIPInputStream gZIPInputStream = new GZIPInputStream(fis);
        
        FileOutputStream fos = new FileOutputStream(tarFile);
        byte[] buffer = new byte[1024];
        int len;
        while((len = gZIPInputStream.read(buffer)) > 0){
            fos.write(buffer, 0, len);
        }
        
        fos.close();
        gZIPInputStream.close();
        return tarFile;
                
    }
    
    /**
     * This method is used to get the tar file name from the gz file
     * by removing the .gz part from the input file
     * @param inputFile
     * @param outputFolder
     * @return
     */
    private static String getFileName(File inputFile, String outputFolder){
        return outputFolder + File.separator + 
                inputFile.getName().substring(0, inputFile.getName().lastIndexOf('.'));
    }
}

That's all for this topic How to untar a file - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating tar file and GZipping multiple files - Java Program
  2. Zipping files in Java
  3. Unzipping files in Java
  4. Compressing and Decompressing File in GZIP Format
  5. How to read file from the last line in Java

You may also like -

>>>Go to Java Programs page

Monday, 22 May 2017

Creating tar file and GZipping multiple files - Java Program

If you want to GZIP multiple files that can’t be done directly as you can only compress a single file using GZIP.

For that you will have to archive multiple files into a tar and then compress it to create a .tar.gz compressed file.

Using Apache Commons Compress

Here I am posting a Java program to create a tar file using Apache Commons Compress library. You can download it from here – https://commons.apache.org/proper/commons-compress/download_compress.cgi

Make sure to add commons-compress-xxx.jar in your application’s class path. I have used commons-compress-1.13 version.

Steps for creating tar files

Steps for creating tar files are as follows -

  1. Create a FileOutputStream to the output file (.tar.gz) file.
  2. Create a GZIPOutputStream which will wrap the FileOutputStream object.
  3. Create a TarArchiveOutputStream which will wrap the GZIPOutputStream object.
  4. Then you need to read all the files in a folder.
  5. If it is a directory then just add it to the TarArchiveEntry.
  6. If it is a file then add it to the TarArchiveEntry and also write the content of the file to the TarArchiveOutputStream.

Folder Structure used

Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories. Your Java code should walk through the whole folder structure and create a tar file with all the entries for the directories and files and then compress it.

Test
  abc.txt
  Test1
     test.txt
     test1.txt
  Test2
     xyz.txt

Example code

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

public class TarGZIPDemo {

 public static void main(String[] args) {
   String SOURCE_FOLDER = "G:\\Test";
   TarGZIPDemo tGzipDemo = new TarGZIPDemo();
   tGzipDemo.createTarFile(SOURCE_FOLDER);
 }
 
 /**
  * 
  * @param source
  */
 private void createTarFile(String source){
  TarArchiveOutputStream tarOs = null;
  try {
    // Using input name to create output name
    FileOutputStream fos = new FileOutputStream(source.concat(".tar.gz"));
    GZIPOutputStream gos = new GZIPOutputStream(new BufferedOutputStream(fos));
    tarOs = new TarArchiveOutputStream(gos);
    File folder = new File(source);
    File[] fileNames = folder.listFiles();
    for(File file : fileNames){
      System.out.println("PATH " + file.getAbsolutePath());
      System.out.println("File name " + file.getName());
      addFilesToTarGZ(file.getAbsolutePath(), file, tarOs);
    }
   
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }finally{
    try {
     tarOs.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 }
 /**
  * 
  * @param source
  * @param file
  * @param tos
  * @throws IOException
  */
 private void addFilesToTarGZ(String source, File file, TarArchiveOutputStream tos) 
                   throws IOException{
   // New TarArchiveEntry
   tos.putArchiveEntry(new TarArchiveEntry(file, source));
   if(file.isFile()){
     FileInputStream fis = new FileInputStream(file);
     BufferedInputStream bis = new BufferedInputStream(fis);
     // Write content of the file
     IOUtils.copy(bis, tos);
     tos.closeArchiveEntry();
     fis.close();
   }else if(file.isDirectory()){
     // no need to copy any content since it is
     // a directory, just close the outputstream
     tos.closeArchiveEntry();
     for(File cFile : file.listFiles()){
       // recursively call the method for all the subfolders
       addFilesToTarGZ(cFile.getAbsolutePath(), cFile, tos);
    
     }
   }
  
 }
}

That's all for this topic Creating tar file and GZipping multiple files - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Zipping files in Java
  2. Unzipping files in Java
  3. Compressing and Decompressing File in GZIP Format
  4. How to convert a file to byte array

You may also like -

>>>Go to Java Programs page

Monday, 1 May 2017

Compressing and Decompressing File in GZIP Format - Java Program

You will mainly use GZIP tool to compress and decompress files in Unix systems. Here note that you can only compress a single file using GZIP not multiple files residing in a folder.

Steps to compress a file

In order to compress a file using GZIP the steps are as follows -

  1. For reading the source file (file which has to be GZIPped) create a FileInputStream.
  2. Create a FileOutputStream to the target file (output GZIPped file).
  3. Create a GZIPOutputStream wrapping the FileOutputStream.
  4. Then you just need to read from the input stream and write to the output stream.

Steps to decompress a file

In order to decompress a file using GZIP the steps are as follows -

  1. For reading the compressed file create a FileInputStream.
  2. Wrap that FileInputStream with in a GZIPInputStream.
  3. Create a FileOutputStream to the new file (created on decompressing GZIP file).
  4. Then you just need to read from the input stream and write to the output stream.

Example code for compressing and decompressing file in GZIP format

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipDemo {

 public static void main(String[] args) {
  // Path to file which is gzipped
  String SOURCE_FILE = "G:\\Test\\abc.txt";
  // Path to gzipped output files
  String GZIP_OUTPUT_FILE = "G:\\Test\\abc.gz";
  // File you get after decompressings
  String GZIP_NEW_FILE = "G:\\Test\\newabc.txt";
  
  GZipDemo gZipDemo = new GZipDemo();
  try {
   // Compressing a file
   gZipDemo.compressGZipFile(SOURCE_FILE, GZIP_OUTPUT_FILE);
   
   // decompressing a file
   gZipDemo.deCompressGZipFile(GZIP_OUTPUT_FILE, GZIP_NEW_FILE);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 /**
  * Method to gzip a file
  * @param sourceFile
  * @param outputFile
  * @throws IOException
  */
 public void compressGZipFile(String sourceFile, String outputFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(sourceFile);
  FileOutputStream fos = new FileOutputStream(outputFile);
  GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(fos); 
  byte[] buffer = new byte[1024];
  int len;
  while((len = fis.read(buffer)) > 0){
   gZIPOutputStream.write(buffer, 0, len);
  }
  
  fis.close();
  gZIPOutputStream.close();
  
 }
 
 /**
  * Method to decompress a gzip file
  * @param gZippedFile
  * @param newFile
  * @throws IOException
  */
 public void deCompressGZipFile(String gZippedFile, String newFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(gZippedFile);
  GZIPInputStream gZIPInputStream = new GZIPInputStream(fis);
  FileOutputStream fos = new FileOutputStream(newFile);
  byte[] buffer = new byte[1024];
  int len;
  while((len = gZIPInputStream.read(buffer)) > 0){
   fos.write(buffer, 0, len);
  }
  
  fos.close();
  gZIPInputStream.close();
 }

}

That's all for this topic Compressing and Decompressing File in GZIP Format - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Zipping files in Java
  2. Unzipping files in Java
  3. Reading all files in a folder - Java Program
  4. Writing file in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 26 April 2017

Reading all files in a folder - Java Program

This post is about how to read all the files in a directory. Suppose you have folder with files in it and there are sub-folders with files in those sub-folders and you want to read or list all the files.

Here is a folder structure used in this post to read the files. Test, Test1 and Test2 are directories here and then you have files with in those directories.

Test
  abc.txt
  Test1
  test.txt
  test1.txt
 Test2
  xyz.txt

Example Code

There are two ways to list all the files one is using the listFiles() method of the File class which is there in Java from 1.2.

Another way is using Files.walk() method which is a recent addition in Java 8.

 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;

public class ListFiles {
    public static void main(String[] args) {
      File folder = new File("G:\\Test");
      ListFiles listFiles = new ListFiles();
      System.out.println("reading files before Java8 - Using listFiles() method");
      listFiles.listAllFiles(folder);
      System.out.println("-------------------------------------------------");
      System.out.println("reading files Java8 - Using Files.walk() method");
      listFiles.listAllFiles("G:\\Test");

     }
         
     public void listAllFiles(File folder){
         System.out.println("In listAllfiles(File) method");
         File[] fileNames = folder.listFiles();
         for(File file : fileNames){
             // if directory call the same method again
             if(file.isDirectory()){
                 listAllFiles(file);
             }else{
                 try {
                     readContent(file);
                 } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
        
             }
         }
     }
         
     public void listAllFiles(String path){
         System.out.println("In listAllfiles(String path) method");
         try(Stream<Path> paths = Files.walk(Paths.get(path))) {
             paths.forEach(filePath -> {
                 if (Files.isRegularFile(filePath)) {
                     try {
                         readContent(filePath);
                     } catch (Exception e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                 }
             });
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } 
     }
     
     public void readContent(File file) throws IOException{
         System.out.println("read file " + file.getCanonicalPath() );
         try(BufferedReader br  = new BufferedReader(new FileReader(file))){
               String strLine;
               // Read lines from the file, returns null when end of stream 
               // is reached
               while((strLine = br.readLine()) != null){
                System.out.println("Line is - " + strLine);
               }
              }
     }
     
     public void readContent(Path filePath) throws IOException{
         System.out.println("read file " + filePath);
         List<String> fileList = Files.readAllLines(filePath);
         System.out.println("" + fileList);
     }
     
}

Output

reading files before Java8 - Using listFiles() method
In listAllfiles(File) method
read file G:\Test\abc.txt
Line is - This file is in Test folder.
In listAllfiles(File) method
read file G:\Test\Test1\test.txt
Line is - This file test is under Test1 folder.
read file G:\Test\Test1\test1.txt
Line is - This file test1 is under Test1 folder.
In listAllfiles(File) method
read file G:\Test\Test2\xyz.txt
Line is - This file xyz is under Test2 folder.
-------------------------------------------------
reading files Java8 - Using Files.walk() method
In listAllfiles(String path) method
read file G:\Test\abc.txt
[This file is in Test folder.]
read file G:\Test\Test1\test.txt
[This file test is under Test1 folder.]
read file G:\Test\Test1\test1.txt
[This file test1 is under Test1 folder.]
read file G:\Test\Test2\xyz.txt
[This file xyz is under Test2 folder.]

Here we have two overloaded methods listAllFiles(). First one take File instance as argument that one is used to read files using the File.listFiles() method. In that method while going through the list of files under a folder you check if the next element of the list is a file or a folder. If it is a folder then you recursively call the listAllFiles() method with that folder name. If it is a file you call the readContent() method to read the file using BufferedReader.

Another version of listAllFiles() method takes String as argument. In this method whole folder tree is traversed using the Files.walk() method. Here again you verify if it is a regular file then you call the readContent() method to read the file.

Note that readContent() method is also overloaded one takes File instance as argument and another Path instance as argument.

That's all for this topic Reading all files in a folder - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Writing file in Java
  2. How to append to a file in Java
  3. How to read file from the last line in Java
  4. How to find last modified date of a file in Java
  5. Unzipping files in Java

You may also like -

>>>Go to Java Programs page