Wednesday, 19 August 2015

Java program to find out available free memory and memory used by the application


               Java program to find out available free memory and memory used by the application



Suppose you want to know the memory used by your application and available system memory in order to check the performance of your application.

Here is the implementation to know free memory and memory used by your application:-


/**  
  * @author Dixit  
  *   
  */  
 public class MemoryUtils {  
      public static void main(String a[]) {  
           System.out.println("Percentage of Memory Used:"  
                     + getPercentageMemoryUsed());  
           System.out.println("Free memory in KBs:" + getFreeMemoryInKBs());  
      }  
      public static float getPercentageMemoryUsed() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           float percentageMemoryUsed = ((memoryUsedByApplication / (float) maximumMemory) * 100);  
           return percentageMemoryUsed;  
      }  
      public static int getFreeMemoryInKBs() {  
           Runtime runtime = Runtime.getRuntime();  
           long memoryUsedByApplication = runtime.totalMemory()  
                     - runtime.freeMemory();  
           long maximumMemory = runtime.maxMemory();  
           long freeMemory = maximumMemory - memoryUsedByApplication;  
           int freeMemoryInKBs = (int) freeMemory / 1024;  
           return freeMemoryInKBs;  
      }  
 }  



Enjoy programming :)

Java program to check if String is Null or Empty



                                    Java program to check if String is Null or Empty


While programming many times we come across the scenario where we have to validate the String object i.e. we need to check whether String is null or empty.

Here is the simple implementation to check whether String is null or empty.

 /**  
  * @author Dixit  
  *  
  */  
 public class EmptyOrNullStringCheck {  
      public static void main(String a[])  
      {  
           String firstString=null;  
           String secondString="abc";  
           String thirdString="";  
           System.out.println("Result of firstString:-"+isNullOrEmpty(firstString));  
           System.out.println("Result of secondString:-"+isNullOrEmpty(secondString));  
           System.out.println("Result of thirdString:-"+isNullOrEmpty(thirdString));  
      }  
      /**  
        * Checks for null or empty.  
        * @author dixit  
        * @param data true/ false  
        */  
        public static boolean isNullOrEmpty(String data) {  
         boolean retStatus = true;  
         if (data != null && !"".equals(data.trim())) retStatus = false;  
         return retStatus;  
        }  
 }  



Enjoy programming:)

Execute Linux commands from Java


                                          Execute Linux commands from Java



Sometime you may get an requirement where you need to run Linux commands inside java program.
For ex: suppose you have to run some script file,so you need to run using sh command of Linux.


 /**  
  * @author Dixit  
  *  
  */  
 public class ExecuteLinuxCommands {  
      public static void main(String a[])  
      {  
           int commandExitCode=executeCmd("ls");  
      }  
      public static int executeCmd( final String command )  
        {  
            int exitCode=-1;  
         Process p = null;  
         InputStream inputstream = null;  
         InputStreamReader inputstreamreader = null;  
         BufferedReader bufferedreader = null;  
         StringBuilder sb = new StringBuilder();  
         try  
         {  
           System.out.println( "Executing : " + command );  
           p = Runtime.getRuntime().exec( command );  
           inputstream = p.getInputStream();  
           inputstreamreader = new InputStreamReader( inputstream );  
           bufferedreader = new BufferedReader( inputstreamreader );  
           String line;  
           while ( ( line = bufferedreader.readLine() ) != null )  
           {  
            sb.append( line );  
            sb.append( "\n" );  
           }  
           System.out.println( sb.toString() );  
           exitCode = p.waitFor();  
         }  
         catch ( Exception e )  
         {  
           // Swallow all exceptions  
           System.out.println( "Command execution failed"+e);  
         }  
         finally  
         {  
           try  
           {  
            if ( p != null ) p.destroy();  
            if ( inputstream != null ) inputstream.close();  
            if ( inputstreamreader != null ) inputstreamreader.close();  
            if ( bufferedreader != null ) bufferedreader.close();  
           }  
           catch ( IOException e )  
           {  
           }  
         }  
         return exitCode;  
        }  
 }  


Note:This program is suitable for Linux environment.You can run any Linux command and view the output.

Enjoy programming :)



Tuesday, 18 August 2015

Java program to find duplicate element between two arrayList




You can find common element between two arrays by two ways i.e. either you can use for loop and compare both the array elements or you can convert array into list and can use retainAll() method.

1) Using For Loop:-

/**  
  * @author Dixit  
  *  
  */  
 public class DuplicateElements {  
      public static void main(String a[]){  
     int[] arr1 = {1,2,3,4,5};  
     int[] arr2 = {4,8,9,7,2};  
     for(int i=0;i<arr1.length;i++){  
       for(int j=0;j<arr2.length;j++){  
         if(arr1[i]==arr2[j]){  
           System.out.println(arr1[i]);  
         }  
       }  
     }  
   }  
 }  

2) Using retainAll() method of List:-

 import java.util.ArrayList;  
 import java.util.Arrays;  
 import java.util.Collections;  
 import java.util.HashSet;  
 import java.util.List;  
 import java.util.Set;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class DuplicateElements {  
      public static void main(String a[]) {  
           int[] arr1 = { 1, 2, 3, 4, 5 };  
           int[] arr2 = { 4, 8, 9, 7, 2 };  
           List<Integer> list1 = new ArrayList<Integer>();  
           for (int index = 0; index < arr1.length; index++) {  
                list1.add(arr1[index]);  
           }  
           List<Integer> list2 = new ArrayList<Integer>();  
           for (int index = 0; index < arr2.length; index++) {  
                list2.add(arr2[index]);  
           }  
           list1.retainAll(list2);  
           System.out.println("CommonElements : " + list1);  
      }  
 }  




Enjoy programming :)


Generate Jasper report into different formats(xls,pdf,csv,odt,rtf,html)


                                Generate Jasper reports into different formats 


You can generate jasper report into different formats like excel sheets(xls),portable document format (pdf) ,comma separated values(csv),rich text format(rtf),hyper text mark up language(html),extensible markup language(xml), open document text(odt) etc.


In order to generate jasper report into specific format,you need to have JasperPrint object.You can make use of jasper report classes for each formats. for ex: to generate csv file ,you can make use of JRCsvExporter class.

1) Generate report in CSV format:-

 private static byte[] generateCsv(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRCsvExporter rtfExporter = new JRCsvExporter();  
    rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    rtfExporter.exportReport();  
    return baos.toByteArray();  
   }  

2) Generate report in PDF format:-

private static byte[] generatePDF(JasperPrint jasperPrint) throws JRException {  
    return JasperExportManager.exportReportToPdf(jasperPrint);  
   }  

3) Generate report in XLS format:-

private static byte[] generateXls(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter xlsExporter = new JExcelApiExporter();  
    xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    xlsExporter.exportReport();  
    return baos.toByteArray();  
   }  

4) Generate report in RTF format:-

private static byte[] generateRtf(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRRtfExporter rtfExporter = new JRRtfExporter();  
    rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    rtfExporter.exportReport();  
    return baos.toByteArray();  
   }  

5) Generate report in HTML format:-

private static byte[] generateHtml(JasperPrint jasperPrint, String reportName) throws JRException {  
  String HTML_REPOT_LOC = "/var/data/sched-ops/kpireports/htmlreport/";  
    JasperExportManager.exportReportToHtmlFile(jasperPrint, HTML_REPOT_LOC + reportName + ".html");  
    return null;  
   }  

6) Generate report in XML format:-

 private static byte[] generateXml(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter xmlExporter = new JRXmlExporter();  
    xmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    xmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    xmlExporter.setParameter(JRXmlExporterParameter.IS_EMBEDDING_IMAGES, Boolean.TRUE);  
    xmlExporter.exportReport();  
    return baos.toByteArray();  
   }  

7) Generate report in ODT format:-

private static byte[] generateOdt(JasperPrint jasperPrint) throws JRException {  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    JRExporter odtExporter = new JROdtExporter();  
    odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    odtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);  
    odtExporter.exportReport();  
    return baos.toByteArray();  
   }  



Make sure you have imported Jasper Report jar into your workspace.

Enjoy programming. :)

Wednesday, 12 August 2015

Java Program to check whether open parenthesis is closed properly or not


              Java Program to check whether open parenthesis is closed properly or not

Many times we want to do a validation on some formula or some string where we need to check whether open parenthesis is closed properly or not.

for ex:- String strFormula=(1+2);

We are going to implement this using stack where we will push the '(' open parenthesis character as soon as it encounters and we will pop out as soon as we encounters closed parenthesis.


 import java.util.Stack;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class ValidateParenthesis {  
      public static void main(String args[]) {  
           String strFormulaCondition = "(1+2)";  
           boolean result = checkForparenthesis(strFormulaCondition);  
           System.out.println("Result:-" + result);  
           String strNewFormulaCondition = "((1+2)";  
           System.out.println("Result:-"  
                     + checkForparenthesis(strNewFormulaCondition));  
      }  
      /**  
       * It checks whether open parenthesis is closed properly or not in report  
       * formula notation  
       *   
       * @param strReportFormula  
       */  
      public static boolean checkForparenthesis(String strReportFormula) {  
           Stack<Integer> stk = new Stack<Integer>();  
           for (int i = 0; i < strReportFormula.length(); i++) {  
                char ch = strReportFormula.charAt(i);  
                if (ch == '(')  
                     stk.push(i);  
                else if (ch == ')') {  
                     try {  
                          int p = stk.pop() + 1;  
                     } catch (Exception e) {  
                     }  
                }  
           }  
           if (!stk.isEmpty()) {  
                return false;  
           } else {  
                return true;  
           }  
      }  
 }  


Enjoy programming:)



Sunday, 9 August 2015

Java program to Swap Two Numbers



There are different ways with which you can implement this program.Its very common question asked in interviews about swapping of two numbers so you must know all the way to do this program.

Here is the implementation below:


 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class SwapNumbers {  
      public static void main(String args[]) {  
           int a = 10;  
           int b = 20;  
           swapNumbersUsingTemporaryVariable(a, b);  
           swapNumbersWithoutUsingTemporaryVariable(a, b);  
           swapNumbersUsingXOROperator(a, b);  
           swapNumbersUsingMuliplicationAndDivisionOperator(a, b);  
      }  
      private static void swapNumbersUsingMuliplicationAndDivisionOperator(int a,  
                int b) {  
           System.out.println("***swapNumbersUsingMuliplicationAndDivisionOperator***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           b = a * b;  
           a = b / a;  
           b = b / a;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersUsingXOROperator(int a, int b) {  
           System.out.println("\n***swapNumbersUsingXOROperator***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           a = a ^ b;  
           b = a ^ b;  
           a = a ^ b;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersWithoutUsingTemporaryVariable(int a, int b) {  
           System.out.println("\n***swapNumbersWithoutUsingTemporaryVariable***\n");  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           a = a + b;  
           b = a - b;  
           a = a - b;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
      private static void swapNumbersUsingTemporaryVariable(int a, int b) {  
           System.out.println("\n***swapNumbersUsingTemporaryVariable***\n");  
           int temp;  
           System.out.println("Before swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
           temp = a;  
           a = b;  
           b = temp;  
           System.out.println("After swap:");  
           System.out.println("a value: " + a);  
           System.out.println("b value: " + b);  
      }  
 }  


Enjoy Coding. :)