Tuesday, 4 April 2017

Java Program to remove duplicates character from String


Sample Program:
 import java.util.LinkedHashSet;  
 import java.util.Set;  
 public class RemoveStringsDuplicates {  
      public static void main(String[] args) {  
           String string = "abcdanbcd";  
           // Convert String into char array.  
           char[] chars = string.toCharArray();  
           // Set is used to remove duplicates.  
           Set<Character> charSet = new LinkedHashSet<Character>();  
           for (char c : chars) {  
             charSet.add(c);  
           }  
           StringBuilder result = new StringBuilder(charSet.size());  
           for (Character character : charSet) {  
                result.append(character);  
           }  
           System.out.println(result.toString());  
      }  
 }  

Output:
 abcdn  

Enjoy Learning.

Convert Date Object into String Object



Sometimes we have a requirement where we need to convert the date object received from input into String object.

Sample Program:


 import java.text.DateFormat;  
 import java.text.SimpleDateFormat;  
 import java.util.Date;  
 public class ConvertDateToStringExample {  
      public static void main(String[] args) {  
           Date date=new Date();  
           DateFormat dateFormatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
           String strDate=dateFormatter.format(date);  
           System.out.println("Converted Date:" +strDate);  
      }  
 }  

Output:


Converted Date:2017-04-04 08:57:44  


Enjoy Coding.

Program to check if String contains only digits


Sample Program:


 public class CheckDigitString {  
      public static void main(String[] args) {  
           String str1="abcd";  
           String str2="abc1d";  
           String str3="11234567";  
           //provide regex pattern for digits  
           System.out.println(" String str1 :"+str1.matches("[0-9]+"));  
           System.out.println(" String str2 :"+str2.matches("[0-9]+"));  
           System.out.println(" String str3 :"+str3.matches("[0-9]+"));  
      }  
 }  

Output:


  String str1 :false  
  String str2 :false  
  String str3 :true  

Enjoy Learning.