Sunday, 19 June 2016

Find Duplicate Characters In String using Java

package com.zia.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class findDuplicateCharacter {

    /**
     * @param args
     */
    public static void findByusingMap(String str) {
        // HashMap with character and number of times they appear in given
        // String argument
        Map<Character, Integer> charMap = new HashMap<Character, Integer>();
        char[] charArr = str.toCharArray();

        for (char value : charArr) {

            if (Character.isLetter(value)) {
                if (charMap.containsKey(value)) {
                    charMap.put(value, charMap.get(value) + 1);

                } else {
                    charMap.put(value, 1);
                }
            }
        }

        Set<Character> charString = charMap.keySet();

        System.out.println("Duplicate Characters In =" + str);
        // set iteration
        for (Character ch : charString) {
            if (charMap.get(ch) > 1) {
                // If any char occur more than 1, printing it's count

                System.out.println(ch + " : " + charMap.get(ch));
            }
        }

    }

    public static void main(String[] args) {

        findDuplicateCharacter.findByusingMap("Hello How are You Doing?");
        findDuplicateCharacter.findByusingMap("Hope you all are doing good");
        findDuplicateCharacter.findByusingMap("Thank you very much for reading this");

    }

}


OutPut:-

Duplicate Characters In =Hello How are You Doing?
e : 2
o : 4
l : 2
H : 2
Duplicate Characters In =Hope you all are doing good
g : 2
d : 2
e : 2
a : 2
o : 5
l : 2
Duplicate Characters In =Thank you very much for reading this
e : 2
a : 2
n : 2
o : 2
h : 3
i : 2
u : 2
r : 3
y : 2




Its very simple program no need to explain,get the character array from String, iterate through that and put it in a Map with character and their count.Then get a Set containing all keys of map and iterate through Set and print characters which have appeared more than once.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Saturday, 18 June 2016

Swap two String variables in java without using a third variable.

First way to do it as below,

String s1 = "First";
String s2 = "Second";
    s1=s1+" "+s2;
s2=s1.split(" ")[0];
s1=s1.split(" ")[1];
System.out.println(s1 + " " + s2);


Another way to do it as,

String a="First";
String b="Second";

    a= a+b;
    b = a.substring(0,(a.length()-b.length())); 
    a = a.substring(b.length());

    System.out.println("a = "+a);
    System.out.println("b = "+b); 

one more way to do this as below,

String returnFirstString(String x, String y) {
    return x;
}

String a = "First"
String b = "Second"
a = returnFirstString(b, b = a); 
System.out.print(a+" "+b);


Another one more way we can do its as,

String s1 = "First";
String s2 = "Second";
AtomicReference<String> String1 = new AtomicReference<String>(s1);
AtomicReference<String> String2 = new AtomicReference<String>(s2);
String1.set(String2.getAndSet(String1.get()));
System.out.println(String1 + " " + String2);

Java Strings are implemented with references, so you need to swap their references.

Finding the first 100 prime numbers using array.

class GeneratePrime{
 public static boolean isPrime(int x)
    {
        for (int i = 2; i <= Math.sqrt(x); i++) {
            if (x % i == 0) {
                return false;
            }
        }

        return true;
    }

public static void main(String args[]){
    int currentNumber = 2;
    int primesFound = 0;

    while (primesFound < 100) {
        if (isPrime(currentNumber)) {
            primesFound++;

            System.out.print (currentNumber + " ");
            if (primesFound % 10 == 0) {
                System.out.println();
            }
        }

        currentNumber++;
    }
}}


Exact usage of “&” Operator in Java

Its bit wise operator ,which can be applied to the integer types, long, int, short, char, and byte. & (bitwise and) Binary AND Operator copies a bit to the result if it exists in both operands means & evaluates both sides of the operation.

Remove special characters(?) from String.

\p{ASCII} is POSIX character classes.It will replace the non ascii string and return the string(Printable ASCII).



String string=givenString.replaceAll("[^\\p{ASCII}]", "");

Thursday, 16 June 2016

How do you test if a word is a palindrome?

A palindrome is a word, or phrase, that when the letters are reversed, the spelling is the same. Some
examples include, “eve,” “level,”.

public static boolean isPalindrome(final String s) {
final String toCheck = s.toLowerCase();
int left = 0;
int right = toCheck.length() - 1;
while (left <= right) {
while(left < toCheck.length() &&
!Character.isLetter(toCheck.charAt(left))) {
left++;
}
while(right > 0 && !Character.isLetter(toCheck.charAt(right))) {
right--;
}
if (left > toCheck.length() || right < 0) {
return false;
}
if (toCheck.charAt(left) != toCheck.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}

Or you may check it also by reversing the string and check the equality,

public static boolean isPalindrome(final String s) {
return s.equals(reverse(s));
}

public static String reverse(final String s) {
final StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < builder.length() / 2; i++) {
final char tmp = builder.charAt(i);
final int otherEnd = builder.length() - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd));
builder.setCharAt(otherEnd, tmp);
}
return builder.toString();
}

Write a method to reverse a String in java.

In Java, a String is immutable, so once it has been constructed it is not possible to change the contents. So when you are asked to reverse a String, you are actually being asked to produce a new String object, with the contents reversed,


public static String reverse(final String s)

Approach to reversing a String is to iterate over the contents in reverse

public static String reverse(final String s) {
final StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}

Or we can do by using Built-in Re verse Methods

Note-This approach, is fine when we do it with small size of data,  It hold the original String and the StringBuilder in memory and occupy large memory. This could be problematic if you were reversing some data of several gigabytes in size.



public static String stringReverse(final String s) {
final StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() / 2; i++) {
final char tmp = sb.charAt(i);
final int otherEnd = sb.length() - i - 1;
sb.setCharAt(i, sb.charAt(otherEnd));
sb.setCharAt(otherEnd, tmp);
}
return sb.toString();
}

Write a method that returns the nth value of the Fibonacci sequence.

int num = 0;
 int num2 = 1; 
 int fibonacci
for (int i= 0; i< n; i++)
{
    fibonacci = num + num2;
    num = num2;
    num2 = fibonacci;
}
System.out.print(num);


to find the nth, you have to iterate the step n times and only print it when you've finished.


Write a method that returns a Fibonacci sequence from 1 to n.

The Fibonacci sequence is a list of numbers, where the next value in the sequence is the sum of the
last two. The sequence defines that the first number is zero, and the next is one.

class FibonacciwithoutRecursion{  
public static void main(String args[])  
{    
   int n1=0,n2=1,n3,i,count=10;    
   System.out.print(n1+" "+n2);//printing 0 and 1    
    
 for(i=2;i<count;++i) {    
  n3=n1+n2;    
  System.out.print(" "+n3);    
  n1=n2;    
  n2=n3;    
 }    
  
}} 


Fibonacci series with using recursive function,

class FibonacciRecursion{  
 static int n1=0,n2=1,n3=0;    
 static void printFib(int count){    
    if(count>0){    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         System.out.print(" "+n3);   
         printFib(count-1);    
     }    
 }    
 public static void main(String args[]){    
  int count=10;    
  System.out.print(n1+" "+n2);//printing 0 and 1    
  printFib(count-2);//n-2 because 2 numbers are already printed   
 }  
}  

Write an algorithm that prints all numbers between 1 and n, replacing multiples of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with FizzBuzz.

Write an algorithm that prints all numbers between 1 and n, replacing multiples
of 3 with the String Fizz, multiples of 5 with Buzz, and multiples of 15 with
FizzBuzz.

This question is  popular, and  one of the most used on Interview. Below is the code block of the problem,
public static List<String> fizzBuzz(final int n) {
final List<String> toReturn = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
if(i % 15 == 0) {
toReturn.add("FizzBuzz");
} else if (i % 3 == 0) {
toReturn.add("Fizz");
} else if (i % 5 == 0) {
toReturn.add("Buzz");
} else {
toReturn.add(Integer.toString(i));
}
}
return toReturn;
}

Java JDBC interview Question

What is the difference between Database and Database management system?
Database is a collection of interrelated data. Database management system is a software which can be used to manage the data by storing it on to the data base and by retrieving it from the data base.  And  DBMS is a collection of interrelated data and some set of programs to access the data.

      There are 3 types of Database Management Systems.
  • Relational DataBase Management Systems(RDBMS):   It is a software system, which can be used to represents data in the form of tables. RDBMS will use SQL2 as a Queries  language.
  • Object Oriented DataBase Management Systems(OODBMS):  It is a software system, which can be used to represent the data in the form of objects. This DBMS will use OQL as a Query language.
  • Object Relational DataBase Management Systems(ORDBMS):  It is a DBMS which will represents some part of the data in the form of tables and some other part of the data in the form of objects. This management system will use SQL3 as a Query Language, it is a combination of  SQL2 and OQL.

How a query could be executed when we send a query to Database?
When we send an SQL Query from SQL prompt to the DataBaseEngine, then Database Engine will take the following steps.
  • Query Tokenization:  This phase will take SQL query as an input and devide into stream of tokens.
  • Query Parsing:   This phase will take stream of tokens as an input, with them it tried to construct a query tree. If query parser constructs query tree successfully then it was an indication that no grammatical mistakes in the taken SQL query. Otherwise there are some syntactical errors in the taken SQL query.
  • Query Optimization:   This phase will take query tree as an input and performs number of query optimization mechanisms to reduce execution time and memory utilization.
  • Query Execution:  This phase will take optimized query as an input and executes that SQL query by using interpreters internally as a result we will get some output on the SQL prompt.

What is  Driver? How many Drivers are available in JDBC? What are the types?
  • It is a process of interacting with the database from a java application.
  • In JDBC applications we must specify the complete database logic in java application as for the java API representations, later on we need to send java represented database logic to the database engine(DBE).
  • DBE must execute the database logic but it was configured as per the java representations but DBE able to understand only Query Language representations.
  • At the above situation if we want to execute our database logic, we need to use one interface in between java application and the database, that interface must convert java representations to query language representations and query language representations to java representations. Now this interface is called as a “Driver”.
Driver:
  • It is a software or an interface existed in between a java application and database, which will map java api calls with query language api calls and vice versa.
  • Initially sun Microsystems has provided “driver interface” to the market with this sun Microsystems has given an intimation to all the database vendors to have their own implementation as per their requirements for the Driver interface.
  • As a response all the database vendors are providing their own implementation for the Driver interface inorder to interact with the respective databases from a java application.
  • The users of the respective databases they must get the respective database provided Driver implementation from the database software and make use as part of the JDBC applications to interact with the respective databases form a java application.
Types of Drivers:
            There are 180+  number of Drivers in the market. But all these Drivers could be classified into the following 4 types.
  • Type 1 Driver
  • Type 2 Driver
  • Type 3 Driver
  • Type 4 Driver
Type 1 Driver:
    • Type 1 Driver is also called as Jdbc-Odbc Driver or Bridge Driver.
    • Jdbc-Odbc Driver is an implementation to Driver interface provided by the sun Microsystems along with the java software.
    • Jdbc-Odbc Driver internally depends on the Microsoft product Odbc Driver.
    • Odbc is nothing but open database connectivity. It is a open specification which can be used to interact with any type of databases.
Advantages:
  • This Driver is already available with java software that’s why no need to bother about how to get the Driver implementation explicitily.
  • Allmost all the databases could support this Driver.
Dis advantages:
  • This Driver internally depends on Odbc Driver that’s why it is not suitable for internet or web applications or network applications.
  • This Driver is a slower Driver, why because Jdbc-Odbc Driver will convert java calls to Odbc calls. Then Odbc Driver has to convert Odbc calls to query language calls.
  • This driver is not portable Driver why because it was not complete the java implementations in Jdbc-Odbc Driver.
  • It we want to use Jdbc-Odbc Driver in our jdbc applications then we must require to install Odbc-Native Library.
Type 2 Driver:
            Type 2 Driver is also called as “part java part native Driver”. i.e., this Driver was designed by using some part of the java implementations and some other part of the database vendor provided native implementations. This Driver is also called as “native driver”.
Advantages:
            When compared to Type 1 driver it is efficient driver why because Type 2 driver directly will convert java api calls to database vendor api calls.
Dis advantages:
  • If we want to use Type 2 Driver in our Jdbc applications then we must require to install database vendor native api.
  • It is a costful Driver.
  • It is not suitable for web applicadtions, distributed applications and web applications.
  • Type 2 Driver performance is low when compared to Type 3 and Type 4 drivers.
  • This driver is not portable driver. Why because this driver was not designed completely in java technology.

Type 3 Driver: 
    • It is also called as middleware database access server driver.
    • This driver could be used to interact with multiple databases from the multiple clients.
    • This driver could be used in collaboration with application server.
    • This driver is suggestable for network applications.
Advantages:
  • It is a fastest driver among all the drivers available in the market.
  • To use Type 3 driver in our jdbc applications it is not required to install odbc native library and database native library.
  • It is very much suitable for network applications.
Dis advantages:
  • This driver is not suitable for simple jdbc applications.
  • This driver requires minimum 3-Tier Architecture.
  • When compared to Type1 and Type2 drivers.. Type3 driver is efficient and portable. But when compared to Type4 driver, Type3 driver is not portable.
Type 4 Driver:
    • This driver is also called as pure java driver i.e, this driver was completely implemented by using java technology.
    • When compared to Type1, Type2 and Type3 drivers.. Type4 driver is portable driver.
    • Type4 driver can be used for any kind of applications.
    • Type4 driver is a cheapest driver when compared to all the drivers that’s why it is frequently used driver.

What is JDBC and What are the steps to write a JDBC application?
           
The process of interacting with the database from a java application is called as JDBC(Java Database Connectivity)
To interact with the database from a java application we will use the following five   steps.
  1. load and register the driver.
  2. Establish a connection between java application and the database.
  3. prepare either statement object or PreparedStatement object or CallebleStatement object as per the application requirements.
  4. write and executer the sql queries.
  5. terminate the connection which we have established.

How to load a JDBC driver?
    • In general sun Microsystems  has provided Driver interface for this all the database vendors has provided their own implementation.
    • If we want to use the database vendor provided Driver implementation to our jdbc application, first we need to make the availability of the respective Driver’s  .class file to JVM, for this we need to set class path environment variable to the location where we have the driver implementation.
    • Sun Microsystems is also provided an implementation to the Driver interface in the form of JdbcOdbcDriver class as part of the java software.
    • If we want to use JdbcOdbcDriver in our jdbc applications no need to set class path environment variable. Why because it was already available in the java software’s pre-defined library.
    • JdbcOdbcDriver internally depends on the mocrosoft product Odbc driver. If we want to use the JdbcOdbcDriver in our jdbc applications first we must configure Odbc driver, for this we will use the following path.
Start/ conrlol panel / performance and maintenance / administrative tools / data source(Odbc)/ user dsn / click on Add / select microsofr Odbc for oracle / finish / provide data source name only / click on ok / ok.
  • To load the driver’s class byte code to the memory we will use the following method.
public void forName(String class name)
Eg:   
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
      Where forName() is a static method, which can be used to load the respective driver class byte code to the memory.
  • Each and every driver class has already a static block at the time of loading the respective driver class byte code to the memory automatically the available static block could be executed, by this 
    DriverManager.registerDriver(….)
    
    method will be executed as part of the static block.
  • By the execution of the
    registerDriver(….)
    
    method automatically the specified driver will be register to the jdbc application.
  • If you want to design any jdbc application, we need to use some pre-defined library, which was provided by the Jdbc API in the form of java.sql package, that’s why we need to import java.sql package in our jdbc application.
Note:-   The best alternative for
Class.forName(..)

is 

DriverManagre.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
 To register the driver.



How to establish a Database connection between java application and Database?
If we want to establish a connection between java application and the database we will the following piece of code.

Connection con= DriverManager.getConnection(“jdbc:odbc:abc”,”abc”,”system”,”manager”);
Where getConnectin() is a static method from DriverManager class, which can be used to return connection object.



Basically Connection is an interface, how getConnection() will create an object for
Connection interface?
Connection is an interface from java.sql package, for which
getConnection(_)
  was return an anonymous inner class object of the Connection interface.
Note:-  Anonymous inner class is a nameless inner class, which can be sued to provide an implementation either for the interfaces or for abstract classes.
Eg:  
interface I
         {
                void ai();
          }
         Class Outer
         {
                     I  i = new I(){
                      public void a1()
                       {
                                             
                       }
                       public void a2()
                       {

                       }
            }            
     Outer o = new Outer();             
     o.i.a1();  // à  correct            
     o.i.a2();  // à  wrong


 getConnection(_) is a static method from DriverManager class, which will call internally  connect() method, this connect() will establish a virtual socket connection in between the java application and the database.



What is the requirement to use Statement object?
  • After establishing a connection between java application and the database we need to write the sql queries and we need to execute them.
  • To execute the sql queries we will use some pre-defined library, which was defined in the form of Statement object,  PreparedStattement object and CallableStatement object.
  • As per the application requirements we need to create either Statement object or CallableStatement object and PreparedStatement object.
  • To create Statement object we will use the following method from connection object.
           
public  Statement createStatement()

Eg:    

Statement st = con.createStatement();





What are the differences between executeQuery(…), executeUpdate(…) and execute(…)  methods?

where executeQuery() can be used to execute selection group sql queries to fetch the data from database.
When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE) will fetch the data from database and send back to the java application.
Java is a purely object oriented technology. That’s why the jdbc application will maintain the fetched data from database, in the form of an object at heap memory, called as ResultSet object.
           
public ResultSet executeQuery(String sqlquery);

            where executeUpdate() can be used to execute updation group sql query to update the database. When we provide updation group sql query as a parameter to executeUpdate(), then JVM will send that sql query to DBE, here DBE will execute it and perform updations on the database, by this DBE will identify the number of records got updated value called as “records updated count” and return back to the java application.
           
public int executeUpdate(String sqlquery)


            where execute() can be used to execute either selection group sql queries or updation group queries.
            When we use selection group sql query with the execute() then we will get ResultSet object at heap memory with the fetched data. But execute() will return “true” as a Boolean value.
            When we use updation group sql query with execute() then we will get “ records updated count value” at jdbc application. But execute() will return “false” as a Boolean value.
            public 
boolean execute(String sqlquery)


What is  ResultSet object and How to Fetch the Data from Database?

ResultSet is an Object which can be used to maintain the fetched data from database in the JDBC applications
           
When we execute a selection group sql query, either with executeQuety()  or with execute() automatically a ResultSet object will be created at heap memory with the fetched data from database.
  • To get the ResultSet object reference directly we will use executeQuery(..).
  • When we create a ResultSet object automatically a cursor will be create called as “ResultSet cursor” to read the data from ResultSet object.
  • When we create the ResultSet object by default ResultSet cursor will be created before the first record.
  • If we want to read the data from ResultSet object every time we need to check whether the next record is available or not. If the next record is available automatically we need to move that ResultSet cursor to next record position.
  • To perform this work we will use the following method from ResultSet interface.  
    public boolean next()
    

  • After getting ResultSet cursor to a record position then we need to get the data from respective fields of the particular record, for this we will use following method,
    public xxx getXxx(int fno)
                //(or)
    public xxx getXxx(String fname)
    //where xxx is byte, shor, int, long, float, //double, char.
    

 Ingeneral execute() method can be used to execute selection group SQl queries for getting the data from Database , but execute() return a boolean value true so here how it possible to fetch the data from database?
  • Execute() can be used to execute both selection group sql query and updation group sql query.
  • If we use execute() to execute a selection group sql query then DBE(Database engine) will execute that sql query and  send back the fetched data from database to java application. Now java application will prepare a ResultSet object with the fetched data but execute() will return “true” as a Boolean value.
  • At this situation to get the reference of the ResultSet object explicitily, we will use the following method from Statement object.
public ResultSet getResultSet();
//eg
       boolean b = st.execute(select * from emp1);
                    System.out.println(b);
                    ResultSet rs = st.getResultSet();

If we use selection group SQL query to executeUpdate() ,what happened?
  • If we use selection group sql query as a parameter to executeUpdate(…) then JVM will send that sql query to the DBE, DBE will fetch the data and send  back to the java application here java application will store the fetched data in the form of ResultSet object. But executeUpdate() is expecting records  updated count value.
 Due to this contradiction JVM will rise an exception like java.lang.SQLException.

If we handle the above exception properly then we will get ResultSet abject and we will get the data from Database.

 What is ResultSet and What are the types of ResultSets are available in JDBC application?

            In jdbc applications ResultSets could be classified in the following two ways.
  • On the basis of ResultSet privilizations - 

There are 2 types of ResultSets.
    • Read only ResultSet
    • Updatable ResultSet
Read only ResultSet:-   It is a ResultSet, which will allow the users to read the        data only. To refer this ResultSet, we will use the following constant from ResultSet interface.
                       
public static final int CONCUR_READ_ONLY;

 Updatable ResultSet:-  If is a ResultSet object, which will allow users to perform some updations on its content. To refer this ResultSet we will use the following constant from ResultSet interface.
                       
public static final int CONCUR_UPDATABLE;

2)On the  basis of  the ResultSet cursor movement:-
There are 2 types of ResultSets.
    • Forward  only ResultSet
    • Scrollable ResultSet

Forward only ResultSet:-  It is a ResultSet object, which will allow the users to iterate the data in any forward direction. To refer this ResultSet object we will use the following  constant from ResultSet interface.
                       
public static final int TYPE_FORWARD_ONLY;

Scrollable ResultSet:-  These are the ResultSet objects, which will allow the users to iterate the data in both forward and backward directions.
            There are 2 types of Scrollable ResultSets.
  • Scroll sensitive ResultSets
  • Scroll in sensitive ResultSets.

What is the difference between ScrollSensitive ResultSet  and ScrollInsensitive  ResultSets?
Scroll sensitive ResultSet is a ResultSet object, which will allow the later updations from database automatically after creating it. To refer this ResultSet we will use the following constant.
           

public static final int TYPE_SCROLL_SENSITIVE;

            Scroll insensitive ResultSet is a ResultSet object, which will not allow later updations from database after creating it. To refer this ResultSet we will use the following constant from ResultSet interface.
  • public static final int TYPE_SCROLL_INSENSITIVE;
    


What is the default ResultSet type in JDBC application and How it is possible to create a specific type of ResultSet object?
  • The default ResultSet type in the jdbc applications is Read only and forward only.
  • In jdbc applications we are able to specify the following types of the ResultSet combination to any particular ResultSet. 
    • read-only, forward only
    • read-only, scroll sensitive
    • read-only, scroll insensitive
    • updatable, forward only
    • updatable, scroll sensitive
    • updatable, scroll insensitive
  • if we want to specity a particular type to the ResultSet object then we should use either of the above constants combination as a parameter to createStatement() method, for this we will use the following method.


public Statement createStatement(int forward / ScrollSensitive / ScrollInsensitive, int&nbsp; readonly / updatable)
Eg:
Statement st = con. createSensitive(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = con.executeQuery(.);



How to iterate the data from Scrollable ResultSet objuect in both forward and backword direction?
  • to iterate the data in forward direction from a ResultSet object we will use the following 2 methods.
         
public Boolean next()
public xxx getXxx(int fieldno.)


         
    Where xxx may be byte, short, char, int, long, float, double.
  • To iterate the data in backward direction from Scrollable ResultSet object we will use the following 2 methods.
           
public Boolean previous()

           
public xxx getXxx(int fieldno)


            Where previous() is a Boolean method, which can be used to check whether the previous record is available or not, if it is available then cursor will be moved to previous record position.


Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...