Friday 21 April 2017

Reverse given String in java

This question is generally asked to the fresh college pass outs or the java developer with 1-3 years of experience. 

It's quite simple question. The sole purpose of asking it is to find out if you will preserve the immutability of String or not. Many directly apply reverse() method on given String itself forgetting that no such method exists for String operation.

To reverse a immutable String you will need use of StringBuffer or StringBuilder. Both has a difference among them but using any of them will allow you to serve the purpose.

Here we are showing you the example of StringBuffer.


Source fileReverseString .java


package String_Programs;

public class ReverseString {
       public static void main(String[] args) {
              String str = "Rajneesh";  //Remember, String is immutable
              //use StringBuffer(or Builder) for modification
              StringBuffer sb = new StringBuffer(str); 
              sb.reverse();  //reverse the string builder data             
             
              String modifiedStr = sb.toString();  //StringBuffer to String conversion
              System.out.println(str" when reversed :" + modifiedStr);
       }
}


OUTPUT:

Rajneesh when reversed :hseenjaR


Note

If you want to use StringBuilder then replace this line 

StringBuffer sb = new StringBuffer(str); 

in the above program with 

StringBuilder sb = new StringBuilder(str); 




You may like to read:

Java program to parse String to Date format


package DateFormat;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class StringToDate {
 
       public static void main(String[] argsthrows ParseException {
              String dateString = "21/4/2017";
             
              SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
              //this step throws checked exception if main() doesn't throws ParseException
              Date date = sdf.parse(dateString);   
             
              System.out.println("Date:"" " + date);
 
       }
 


OUTPUT

Date: Sat Jan 21 00:04:00 IST 2017
 

Thursday 20 April 2017

Java program to find duplicate strings present in a sentence

Given String: This is Rajneesh This and will That is This
Required OUTPUTThis, is
---------------------------------------------------------


Source File: DuplicateString.java


package String_Programs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DuplicateString {
      
       public static void duplicateString(String str){
             
              Set<String> duplicateSet = new HashSet<String>()
              List<String> duplicateList = new ArrayList<String>();
              String[] strArray = str.split(" ");
             
              for(int i=0;i<strArray.length;i++){
                     for(int j=i+1;j<strArray.length;j++){
                           if(strArray[i].equals(strArray[j])){
                                  //if(duplicateList.contains(o))
                                  duplicateSet.add(strArray[i]);
                                  duplicateList.add(strArray[i]);
                           }
                     }
              }
             
              System.out.println("List bucket data :" +duplicateList);
              System.out.println("Set bucket data :"  +duplicateSet);
       }
       public static void main(String[] args) {
              duplicateString("This is Rajneesh This and will That is This");
       }
}


OUTPUT: 

List bucket data :[This, This, is, This]
Set bucket data :[This, is]

The output between List and Set calls for a discussion. Have a look and try to figure out what's the difference?

Sunday 16 April 2017

Checked and Unchecked Exception in java

Two categories of Exception that we come across are:

Checked Exception:

Checked Exception extends java.lang.Exception

If there is possibility that the code written may result in throwing exception then compiler senses it and reminds programmer to handle such codes in either of these two ways during compilation:
  • enclose code within try/catch
  • declare the exception using throws keyword
At the very basic level you can think of it as exceptions which are caught at the compile time.


For example,

You have a code where you want to read a file from particular location  say ("D:\\JavaFiles\\myFile.txt")


import java.io.*;

class MyFileReader {

    public static void main(String[] args) {

        FileReader file = new FileReader("D:\\JavaFiles\\myFile.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 4 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 4; counter++)
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}

What would be fate of above code?

It is sure to throw compile time error.

Reason being the presence of FileReader which throws Checked Exception FileNotFoundException and readLine & close which throws checked exception IOException.

In order save your code from compile time error enclose the code within try/catch block. Or declare all Exceptions that could possibly occur using throws like this,


 public static void main(String[] args) throws IOException


Since FileNotFoundException is the child (sub class) of IOException so declaring only IOException using throws will serve the purpose here.

ExamplesSQLExceptionClassNotFoundExceptionIOExceptionetc




Unchecked Exceptions:

Unchecked Exceptions extends java.lang.RuntimeException

Unchecked Exceptions are those that goes beyond the range of compilers and escapes their notice. It occurs due to error in programming logic. There are exceptions which can only be detected at run time such as illogical codes. 

Like, a code where you perform division by 0(zero) or you try to access value from an index which is not present in the array. 

These kind of code will compile fine and will look perfect until run. So unchecked Exception are run time exceptions.

For example consider this code,

class MyFile {

    public static void main(String[] args) {
         
        // Division by 0
        int x = 5/0; // illogical code will throw ArithmeticException
        System.out.println(x);
    }
}

The above code will not show any compile time error. But if you run it, you will find ArithmeticException.

So as a programmer you are never expected to write a code like,
int i=5, int j=0;
int k=i/j;

because it is loop hole in coding logic and will show its erroneous face while you run it and will result in abrupt termination of your code if it is not taken care by try/catch block.
And if you write such code then you have to waste lot of time in debugging your code and find out this kind of logical error.

ExamplesArithmeticExceptionArrayIndexOutOfBoundsException,NullPointerExceptionsetc




You may also like to read:


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.