Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to write to a file line by line using Apache Commons-io API in Java ?.

Program to demonstrate how to write to a file line by line using Apache Commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.io.FileUtils;

public class WriteContentsToFile {

    public static void main(String[] args) {

        Collection< String > welcome = new ArrayList< String >();
        welcome.add("Welcome to Hubberspot.com");
        welcome.add("Its a site for Java developers.");
        welcome.add("Learn Java by Examples.");
        welcome.add("Everything you want to know about Java.");
        welcome.add("Tutorials, Source Codes, SCJP, SCWCD, Frameworks,");
        welcome.add("Java EE and Design Patterns.");
        
        File file = new File("D:/hubberspot/welcome.txt");
        
        try {
            
            FileUtils.writeLines(file, welcome);
        
        } catch (IOException e) {
           
            e.printStackTrace();
        }

    }

}



Output of the program :


How to clean contents of a directory using Apache commons-io API in Java ?

Program to demonstrate how to clean contents of a directory using Apache commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CleanDirectoryDemo {

    public static void main(String[] args) {

        // Create a File object and pass path of the directory
        // where files needs to be cleaned
        File file = new File("D:/files");

        // FileUtils class of org.apache.commons.io
        // has a method by name cleanDirectory() which takes in
        // the directory where files need to be 
        // cleaned.

        try {

            FileUtils.cleanDirectory(file);

        } catch (IOException e) {
            
            e.printStackTrace();
        }

    }

}



How to search for files in a directory based on extension using Apache commons-io API in Java ?

Program to demonstrate how to search for files in a directory based on extension using Apache commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;

public class RecursiveFileSearch {

    public static void main(String[] args) {

        // Create a File object and pass path of the directory
        // where files need to be searched
        File file = new File("D:/files");

        try {
            // an array of files extensions to be searched in 
            // the file created above.
            String[] extOfTheFiles = {"jar", "java", "pdf"};

            // FileUtils class of org.apache.commons.io
            // has a method by name listFiles() which takes in
            // three parameters the directory where files need to be 
            // searched , extension of the files to be searched and 
            // boolean value to make a recursive search for the files
            // The method returns back a collection of File objects
            Collection< File > listOfFiles= FileUtils.listFiles(file, extOfTheFiles, true);

            // Create a iterator for the collection of files
            Iterator< File > fileIterator = listOfFiles.iterator();

            // loop over each file in the collection
            while(fileIterator.hasNext()) {

                File searchedFile = fileIterator.next();

                // print the name of the file on the console
                System.out.println(searchedFile.getAbsolutePath());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }        

    }

}



Output of the program :


How to read a file contents and convert it to String using Apache commons-io API in Java ?

Program to demonstrate how to read a file contents and convert it to String using Apache commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class FileContentsToString {

    public static void main(String[] args) {

        // Create a File object and pass name of the file along 
        // with its path whose contents is to be read 
        File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
                "domain1/logs/server.log");

        try {

            // org.apache.commons.io package has a class by name
            // FileUtils which has a method called as readFileToString()
            // This method takes in a file object and return back 
            // contents of file in the form of String representing 
            // file contents as a String object  
            String fileContents = FileUtils.readFileToString(file);

            // In order to print the contents of file on the console
            // we just print the it on the console using 
            // System.out.println(String)
            System.out.println(fileContents);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}



Output of the program :



How to read a file contents line by line using Apache commons-io API in Java ?

Program to demonstrate how to read a file contents line by line using commons-io API in Java.

package com.hubberspot.apache.commons.examples;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class ReadFileLineByLine {

    public static void main(String[] args) {
        
        // Create a File object and pass name of the file along 
        // with its path whose contents is to be read 
        File file = new File("C:/Program Files/glassfish-3.1.2/glassfish/domains/" +
          "domain1/logs/server.log");

        try {
            
            // org.apache.commons.io package has a class by name
            // FileUtils which has a method called as readLines()
            // This method takes in a file object and return back 
            // contents of file in the form of List representing 
            // each line as String object  
            List fileContents = FileUtils.readLines(file);
            
            // In order to print the contents of file on the console
            // we use for loop which iterates over List line by line
            // and prints on the console. 
            for (String line : fileContents) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}



Output of the program : 


 

How to create a simple JTree in Java using Java Swing API ?.

Program to demonstrate how to create a simple JTree in Java using Java Swing API ?.

package com.hubberspot.swing.examples;

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class JTreeDemo
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JTreeFrame();
                frame.setTitle("JTree Demo");               
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}


class JTreeFrame extends JFrame
{
    public JTreeFrame()
    {
        setSize(300, 300);

        DefaultMutableTreeNode country = new DefaultMutableTreeNode("India");
        
        DefaultMutableTreeNode state = new DefaultMutableTreeNode("Maharashtra");
        country.add(state);
        
        DefaultMutableTreeNode city = new DefaultMutableTreeNode("Pune");
        state.add(city);
        city = new DefaultMutableTreeNode("Mumbai");
        state.add(city);
        
        state = new DefaultMutableTreeNode("Madhya Pradesh");
        country.add(state);
        city = new DefaultMutableTreeNode("Indore");
        state.add(city);
        city = new DefaultMutableTreeNode("Bhopal");
        state.add(city);
        
        state = new DefaultMutableTreeNode("Gujrat");
        country.add(state);
        
        city = new DefaultMutableTreeNode("Ahmedabad");
        state.add(city);

        JTree tree = new JTree(country);
        add(new JScrollPane(tree));
    }
}



Output of the program :



Write a Java program to calculate sum of the digits of a number entered by the user.

Program to calculate sum of the digits of a number entered by the user in Java

package com.hubberspot.java.example;

import java.util.Scanner;

public class SumOfDigitsDemo {

    public static void main(String[] args) {

        Integer number;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number whose" +
                " sum of digits is to be calculated : ");

        number = scanner.nextInt();

        System.out.println("Number entered : " + number);

        int sum = 0;

        while(number > 0) { 
            int digit = number % 10;
            sum = sum + digit;
            number = number / 10;
        }

        System.out.println("The sum of the digits of the" +
                " number entered : " + sum);        
    }
}



Output of the program : 


 

How to handle Mouse Click events in Java ?.

Program to demonstrate how to handle Mouse Click events in Java.

package com.hubberspot.swing.examples;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class MouseClickEventHandling extends JFrame {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MouseClickEventHandling().setVisible(true);
            }
        });

    }

    public MouseClickEventHandling() { 
        mouseEventHandling();
    }

    private void mouseEventHandling() {

        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JTextArea textArea = new JTextArea();
        textArea.setText("Browse Text Area Below !!! ");

        textArea.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {

                textArea.setText(" Mouse Released ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());

            }

            @Override
            public void mousePressed(MouseEvent e) {

                textArea.setText(" Mouse Pressed ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());
            }

            @Override
            public void mouseExited(MouseEvent e) {

                textArea.setText("Mouse Exited ... \n Position :" +
                        e.getX() +" , "+ e.getY());

            }

            @Override
            public void mouseEntered(MouseEvent e) {

                textArea.setText("Mouse Entered ... \n Position :" +
                        e.getX() +" , "+ e.getY());

            }

            @Override
            public void mouseClicked(MouseEvent e) {

                textArea.setText(" Mouse Clicked ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());
            }
        });

        getContentPane().add(textArea);        
    }

}



Output of the program : 






 

Pattern problems : Write a Java program to print same character on each line and having character printed in Square shape form.

Program to Pattern problems : Write a Java program to print same character on each line and having character printed in Square Shape form. As shown below :

*  *  *  *  *  *
*               *
*               *
*               *
*  *  *  *  *  * 
 

package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class SquarePattern {

    public static void main(String[] args) {

        String pattern;
        int noOfTimes;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the pattern to print : ");
        pattern = scanner.nextLine();

        System.out.print("Enter number of times it should get printed : ");
        noOfTimes = scanner.nextInt();

        for(int i=1; i<=noOfTimes; i++) {       
            
            System.out.println();

            if(i==1 || i==noOfTimes) {
      
                for(int j=1; j<=noOfTimes; j++){
                
                    System.out.print(pattern+" ");
                
                }
            } 
            else { 
                
                for(int k=1; k<=noOfTimes;k++) { 
                
                    if(k==1 || k == noOfTimes) { 
                    
                        System.out.print(pattern + " ");
                    
                    }                    
                    else { 
                     
                        System.out.print("  ");
                    
                    }
                }
            }
        }
    }
}


Output of the program : 

 

Pattern problems : Write a Java program to print same character on each line and having character printed in Inverted V shape form.

Program to Pattern problems : Write a Java program to print same character on each line and having character printed in Inverted V Shape form. As shown below :


    *
   * *
  *   *
 *     *
*       * 


 


package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class InvertedVPattern {

    public static void main(String[] args) {

        String pattern;
        int noOfTimes;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the pattern to print : ");
        pattern = scanner.nextLine();

        System.out.print("Enter number of times it should get printed : ");
        noOfTimes = scanner.nextInt();

        int spaceBeforePattern = noOfTimes-1;
        int spaceAfterPattern = -1;

        System.out.println();

        for(int i=1; i <= noOfTimes; i++ ) { 

            for(int j = 1; j <= spaceBeforePattern; j++) { 
                System.out.print(" ");
            }

            System.out.print(pattern);

            for(int k = 1; k <=spaceAfterPattern; k++) { 
                System.out.print(" ");
            }

            if(i > 1) { 
                System.out.print(pattern);
            }

            System.out.println();

            spaceAfterPattern = spaceAfterPattern + 2;
            spaceBeforePattern = spaceBeforePattern - 1;

        }   
    }
}



Output of the program : 


 

Pattern problems : Write a Java program to print same character on each line and having character printed in V shape form.

Program to Pattern problems : Write a Java program to print same character on each line and having character printed in V Shape form. As shown below :


*                                *
   *                          *
      *                    *
          *            *     
              *    *
                 *





package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class VPattern {

    public static void main(String[] args) {
        
        String pattern;
        int noOfTimes;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the pattern to print : ");
        pattern = scanner.nextLine();

        System.out.print("Enter number of times it should get printed : ");
        noOfTimes = scanner.nextInt();
        
        int spaceBeforePattern = 0;
        int spaceAfterPattern = 2 * noOfTimes - 3;
        
        System.out.println();
        
        for(int i=1; i <= noOfTimes; i++ ) { 
           
            for(int j = 1; j <= spaceBeforePattern; j++) { 
                System.out.print(" ");
            }
            
            System.out.print(pattern);
            
            for(int k = 1; k <=spaceAfterPattern; k++) { 
                System.out.print(" ");
            }
            
            if(i < noOfTimes) { 
                System.out.print(pattern);
            }
            
            System.out.println();
                        
            spaceAfterPattern = spaceAfterPattern - 2;
            spaceBeforePattern = spaceBeforePattern + 1;
        }
        
    }

}


Output of the program : 

 

Pattern problems : Write a Java program to print same character on each line and having character printed in diagonal form.

Program to Pattern problems : Write a Java program to print same character on each line and having character printed in diagonal form. As shown below :

*
   *
      *
         *
            *
               *



package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class DiagonalPattern {

    public static void main(String[] args) {

        String pattern;
        int noOfTimes;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the pattern to print : ");
        pattern = scanner.nextLine();

        System.out.print("Enter number of times it should get printed : ");
        noOfTimes = scanner.nextInt();

        for(int i = 1; i <= noOfTimes; i++) {

            for(int j = 1; j <= i; j++) { 

                if(j != i) {

                    System.out.print(" ");

                }
                else if(j == i){

                    System.out.print(pattern);    

                }
            }
            System.out.println();
        }


    }

}


Output of the program : 

 

Pattern problems : Write a Java program to print different character on each line and having character increment with each line.

Program to Pattern problems : Write a Java program to print different character on each line and having character increment with each line. As shown below :

1
22
333
4444
55555
666666



package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class MultipleLineDifferentPattern {

    public static void main(String[] args) {

        int pattern;
        int noOfTimes;

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the start number to print : ");
        pattern = scanner.nextInt();

        System.out.print("Enter number of times it should get printed : ");
        noOfTimes = scanner.nextInt();

        for(int i = 1; i <= noOfTimes; i++) {

            for(int j = 1; j <= i; j++) { 
                System.out.print(pattern);
            }
            System.out.println();
            pattern++;
        }
    }
}


Output of the program : 

 

Pattern problems : Write a Java program to print same character on each line and having character increment with each line.

Program to Pattern problems : Write a Java program to print same character on each line and having character increment with each line. As shown below :

*
**
***
****
*****
******



package com.hubberspot.patterns.problems;

import java.util.Scanner;

public class MultipleLinePattern {
 
 public static void main(String[] args) {
  
     String pattern;
     int noOfTimes;
     
     Scanner scanner = new Scanner(System.in);
     
     System.out.print("Enter the pattern to print : ");
     pattern = scanner.nextLine();
     
     System.out.print("Enter number of times it should get printed : ");
     noOfTimes = scanner.nextInt();

     for(int i = 1; i <= noOfTimes; i++) {
         
         for(int j = 1; j <= i; j++) { 
             System.out.print(pattern);
         }
         System.out.println();
     }
 }

}


Output of the program : 


 

Write a program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero.

Program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero in Java.

package com.hubberspot.java.example;

import java.util.Scanner;

public class SumArray {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int [] numbers = new int[0];

        int number;
        String nextLine;
        do {
            System.out.print("Enter the number : ");
            number = scanner.nextInt();
            nextLine = scanner.nextLine();

            if(number != 0) {
                numbers = add(numbers, number);
            }

        } while(number != 0);

        int negativeSum = 0; 
        int oddSum = 0; 
        int evenSum = 0;

        for(int i = 0; i < numbers.length; i++ )
        {
            if( numbers[i] < 0 )
            {
                negativeSum = negativeSum + numbers[i];
            }
            else if( numbers[i] % 2 == 0 )
            {
                evenSum = evenSum + numbers[i];
            }
            else
            {
                oddSum = oddSum + numbers[i];
            }
        }
        System.out.println( "Sum of negative numbers : " + negativeSum );
        System.out.println( "Sum of positive even numbers: " + evenSum );
        System.out.println( "Sum of positive odd numbers: " + oddSum );

    }

    private static int[] add(int[] numbers, int number) {

        int[] tempArray = new int[numbers.length + 1];

        for(int i = 0; i < numbers.length; i++) {
            tempArray[i] = numbers[i];
        }

        tempArray[tempArray.length - 1] = number;
        return tempArray;

    }

}


Output of the program : 

 

Write a Java program to print Padovan Sequence.

Program to implement Padovan sequence in Java.

The Padovan Sequence starts with three 1's and after that moves on with a function as : f(x) = f(x-2)+ f(x-3).

package com.hubberspot.java.sequences;

import java.util.Scanner;

public class Padovan {

    public static void main(String[] args) {
        
        int firstNumber = 1;
        int secondNumber = 1;
        int thirdNumber = 1;
                
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the number of terms for Padovan sequence : ");
        
        int noOfTerms = scanner.nextInt();
        int nextNumber;
        
        System.out.print( firstNumber + " " + secondNumber + " " + thirdNumber);
        
        for(int i = 1; i <= noOfTerms - 3; i++) { 
            
            nextNumber = secondNumber + firstNumber;
            System.out.print(" " + nextNumber);
            firstNumber = secondNumber;
            secondNumber = thirdNumber;
            thirdNumber = nextNumber;
            
        }        


    }

}


Output of the program : 


 

Write a Java program to print Jacobsthal Sequence.

Program to implement Jacobsthal sequence in Java.

The Jacobsthal sequence starts with numbers 0 and 1. After that each successive number is sum of previous number plus twice the number previous to previous number.

package com.hubberspot.java.sequences;

import java.util.Scanner;

public class Jacobsthal {

    public static void main(String[] args) {
       
        int firstNumber = 0;
        int secondNumber = 1;
                
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the number of terms for Jacobsthal sequence : ");
        
        int noOfTerms = scanner.nextInt();
        int nextNumber;
        
        System.out.print( firstNumber + " " + secondNumber);
        
        for(int i = 1; i <= noOfTerms - 2; i++) { 
            
            nextNumber = secondNumber + 2 * firstNumber;
            System.out.print(" " + nextNumber);
            firstNumber = secondNumber;
            secondNumber = nextNumber;
            
        }        

    }

}


Output of the program : 

 

Write a menu‐driven class to accept a number from the user and check whether it is a Automorphic number or not in Java.

Program to demonstrate a menu‐driven class to accept a number from the user and check whether it is a Automorphic number or not in Java.

package com.hubberspot.java.example;

import java.util.Scanner;

public class AutomorphicTest {

    public static void main(String[] args) {

        char program;
        Scanner scanner = new Scanner(System.in);
        do { 

            System.out.println("Press 'A' for Automorphic Number Test or 'E' for Exit");

            program = scanner.nextLine().toUpperCase().charAt(0);

            if(program != 'A' && program != 'E') { 
                System.out.println();
                System.out.println("You entered : " + program);
                System.out.println("Please enter P or E to proceed ... try again");
                System.out.println();
                continue;
            } 
            else { 
                switch( program )
                {
                case 'A': 
                    System.out.print( "Enter number for Automorphic Number checking: " );

                    int number = scanner.nextInt();
                    String line = scanner.nextLine();

                    if( isAutomorphicNumber( number ) )
                    {
                        System.out.println( number + " is a Automorphic number." );
                    }
                    else
                    {
                        System.out.println( number + " is not a Automorphic number." );
                    }
                    break;
                }
            }

            System.out.println();

            if( program == 'E') { 
                System.out.println("Exiting from the program...");
            }
        }
        while(program != 'E');


    }

    private static boolean isAutomorphicNumber(int number) {

        int square = number * number;

        String numberToString = "" + number;
        String squareToString = "" + square;
        
        if( squareToString.endsWith( numberToString ) )
        {
            return true;
        }
        return false;

    }

}



Output of the program : 

 

Write a program to calculate and print the sum of the following series: Sum(x) = x/2 + x/5 + x/8 + … + x/100.

Program to calculate and print the sum of the following series: Sum(x) = x/2 + x/5 + x/8 + … + x/100 in Java.

package com.hubberspot.java.series.problems;

import java.util.Scanner;

public class Series {

    public static void main(String[] args) {
        
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter the value of x : ");
        
        double x = scanner.nextDouble();        
        double sumOfSeries = 0;
        double numerator = x;
        double denominator;
        double term;

        for(int i = 2; i <= 100; i = i + 3) { 
            
            denominator = i;
            term = numerator / denominator;
            sumOfSeries = sumOfSeries + term;
            
        }
        
        System.out.println("Sum of the series : " + sumOfSeries);
        
    }
}


Output of the program : 

 

Write a program to calculate and print the sum of the following series: Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100

Program to demonstrate how to calculate and print the sum of the following series:
Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100 in Java.


package com.hubberspot.java.series.problems;

public class Series {

    public static void main(String[] args) {

        int sumOfSeries = 0;
        
        int i = 2;
        
        while( i <= 100 ) {
            
            if(i % 4 == 0) { 
                
                sumOfSeries = sumOfSeries - i;
            
            }
            else {
                
                sumOfSeries = sumOfSeries + i;
            
            }
            
            i = i + 2;
        }
        
        System.out.println("Sum of the series : " + sumOfSeries);

    }

}


Output of the program : 

 
 
© 2021 Learn Java by Examples Template by Hubberspot