Friday, June 13, 2014

ORA-01008: not all variables bound

Problem:

    While executing the callable statement or prepared statement, you may get this error.

Solution:

    Just check how many " ? " parameters you are using with your procedure call or prepared statement call.

Saturday, May 24, 2014

Web Driver API commands and UI Elements

Selenium Web Driver API commands

Get your web page

By calling get, you can get your web page.
driver.get("http://www.google.com");

Web Elements

By ID
For locating the UI elements(Web Elements) , you can use WebElement.

See below example,
<div id="languages">
   .........
   .........
   .........
</div>

Now you can get that above element through below command.
WebElement element = driver.findElement(By.id("languages"));

By Class Name
The same concept you can apply to all other UI elements. But it will differ little.

See below example,
<div class="border"><span>RED</span></div>
<div class="border"><span>GREEN</span></div>

List<WebElement> border = driver.findElements(By.className("border"));

Above we are using className method, due to it belongs to class DOM.
and why we are using List, since the class name might be present in multiple places.

By Tag Name
Same concept DOM tag name should mentioned here.

See below example,
<iframe src="..."> </iframe>

WebElement frame = driver.findElement(By.tagName("iframe"));

By Name
You can find the element for an input element.

See below example,
<input name="javahit" type="text"/>

WebElement javaHit = driver.findElement(By.name("javahit"));

By Link Text
You can find the link element with matching visible text.

See below example,
<a href="http://www.google.com/search?q=test">test</a>>

WebElement Test = driver.findElement(By.linkText("test"));

By Partial link text
You can find the link element with partial matching visible text.

See below example,
<a href="http://www.google.com/search?q=color">search for color</a>>

WebElement Color = driver.findElement(By.partialLinkText("color"));

By CSS
It is a locator strategy by CSS. It should be handled with care. since browser version will differ.

<div id="test"><span class="sample">water</span><span class="sample ok">Checking CSS</span></div>

WebElement Checking CSS = driver.findElement(By.cssSelector("#test span.sample.ok"));

By XPATH
Mostly webDriver uses native XPATH, wherever possible cases. Suppose if the browser dont have native XPATH support, you have to give your own implementation.
So you should know the difference various XPATH engines.

Driver
Tag and Attribute Name
Attribute Values
Native XPath Support
HtmlUnit Driver
Lower-cased
As they appear in the HTML
Yes
Internet Explorer Driver
Lower-cased
As they appear in the HTML
No
Firefox Driver
Case insensitive
As they appear in the HTML
Yes

See the below example carefully. So that you can understand this XPATH concept clearly.

<input type="text" name="java" />
<INPUT type="text" name="hit" />

Above I given one input as in Small Letter and another one as Capital Letter.
List<WebElement> inputs = driver.findElements(By.xpath("//input"));

See the below table now.

XPath expression
HtmlUnit Driver
Firefox Driver
Internet Explorer Driver
//input
1 (“java”)
2
2
//INPUT
0
2
0


Sunday, May 18, 2014

Selenium web driver configuration in eclipse


Just right click on your java projects, click Build Path --- > Configure Build Path


After clicking configure build path, the below window will open. Now navigate to Libraies Tab. Click Add External JARs...


Now your browse window will open. Select your selenium jar means, selenium-java-2.41.0 and selenium-java-2.41.0-srcs. 

Again click Add External JARs.... Browse window will open. Now select all jar inside lib folder. 
click Ok. So the final window will look like the below.



Thats all. Now you have successfully configured.



Friday, May 9, 2014

Null pointer deference in find bugs

I have faced null pointer deference, when I checked the code standard with tool. It shows NULL pointer deference in severity 1.

Normally it will come when you are not handling null values. For example,

if ( URL != null) {System.out.println( "URL is NOT NULL + URL );}

ok fine. You are checking URL is not null. But in case , URL come as null, what will happen? Null pointer Exception error will thrown.

So this error called Null Pointer Dereference error. ok, How to handle this. See below for solution.

if ( URL != null) {System.out.println( "URL is NOT NULL + URL );}
        else {
        System.out.println( "URL is NULL " );
         throw new IllegalArgumentException();
}

Thats all.

Thursday, May 8, 2014

Appears to call the same method on the same object redundantly in FindBugs

Issue Here below:

try {
----------
----------
}
catch (final SQLException e) {
LOG.error("Error Message Test: " + e.getMessage());
            throw new YourException(e.getMessage(), e);
}


Solution for that:

try {
--------------
--------------
 } catch (final SQLException e) {
        String errorMessage = e.getMessage();
            LOG.error("Error Message Test: " + errorMessage);
            throw new YourException(errorMessage, e);

Wednesday, May 7, 2014

Why toString() method in bean class?

Why toString() method in bean class?

We can use it to print object values directly, if overriding toString() method. If you will try to print object without overriding toString() method, it will print some hexadecimal values.

Generally we will use toString() in bean class, to check the bean property values.

For example,

public class TestBean implements Serializable {

private string name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name= name;
}

public int getAge() {
return age;
}

public void setAge(String age) {
this.age= age;
}

@Override
public String toString() {

return "TestBean [name=" +  name  + ", age=" + age + "]";
}
}


Now you should set values to this bean property. Now somewhere you can create object for this bean class like below.

TestBean test = new TestBean();

try to print the test object ,
System.out.println(test);

It will display the value like below.

=TestBean[name=test, age=19 ]

So you can use this to debug or log etc.,



Saturday, May 3, 2014

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

You may get this error while doing build with Maven. Here the solution,

Just follow the images and provide the information based on that,



After that, follow the next screen , remember select execution environments inside Installed JREs.



Wednesday, April 9, 2014

ActiveMQ

What is ActiveMQ?
            It is an open source, Message Oriented Middleware (MOM) from the apache software foundation. It provides standard based, with MOM concept across many languages and platforms.

It provides,
·         High – availability
·         Performance
·         Scalability
·         Reliability
·         Security

Features:

·         It’s implementing JMS, compliant to MOM.
·         JMS provides synchronous and asynchronous message delivery.
·         Its supports the connectivity protocols are http/s, TCP, UDP, SSL etc.
·         It’s possible to integrate with containers like Tomcat, Jboss, Weblogic etc.

Message Oriented Middleware (MOM):

·         It’s loosely coupled, so application will not affect much.
·         It will allow application to application communication.
·         It will act as a message mediator between message senders and message    receivers.
·         Its supports the connectivity protocols are http/s, TCP, UDP, SSL etc.

           
Message Queue:

Messages stored in First In First Out order and when the message has been consumed, it can be deleted from the store.

Tuesday, March 11, 2014

Number to Word Converter in Java


import java.io.IOException;
import java.util.*;

public class NumberToword

{
  private static int n = 0;
  private static NumberToword obj = null;
  private static Scanner s = null;

 //This method is used for getting the result
  public void result(int n,String ch)

     {

   String one[]={

     " "," one"," two"," three"," four"," five"," six"," seven"," eight"," Nine"," ten"," eleven"," twelve"," thirteen"," fourteen","fifteen"," sixteen"," seventeen"," eighteen"," nineteen"};

   String ten[]={" "," "," twenty"," thirty"," forty"," fifty"," sixty","seventy"," eighty"," ninety"};

   if(n>19) {
    System.out.print(ten[n/10]+" "+one[n%10]) ;
    }
  
   else {
    System.out.print(one[n]);
        }  
  
       if(n>0)
         System.out.print(ch);
       }
 //This method is used for processing the input

    public void processInput(){
               
     obj.result((n/1000000000)," Hundred");
     obj.result((n/10000000)%100," crore");
     obj.result(((n/100000)%100)," lakh");
     obj.result(((n/1000)%100)," thousand");
     obj.result(((n/100)%10)," hundred");
     obj.result((n%100)," ");
  
    }
  
 //This method Used for getting input
    public int getInput(){
      int i = 0;
      s =new Scanner(System.in);
      System.out.println("Enter an integer number: ");
      i = s.nextInt();
      return i;
    }
  
      public static void main(String[] args) throws IOException
      {
      
        String emptyArg[] = null;
        int startLimit = 0;
        int endLimit = 999999999;
      
       try {
        obj =new NumberToword();
        n = obj.getInput();
       if( n <= startLimit && n < endLimit ){
       
        System.out.println("Enter numbers between 0 to 999999999");
        NumberToword.main(emptyArg);
       }
       else
          {
        obj =new NumberToword();
        System.out.println("After conversion number in words is :");
        obj.processInput();
            
          }
       }
       catch(InputMismatchException e) {
        //e.printStackTrace();
        System.out.println("Enter numbers between 0 to 999999999");
        NumberToword.main(emptyArg);
       
       }
            
      }
}

Thursday, February 27, 2014

Array List Tutorial

What is Array list?

Array list is a class that extends abstract list and implements the List interface. It will allow duplicates values.

Normal java array you have to set a size. But array list will support dynamic grow, that means it will be created with an initial size. After that if the size is exceeded, it will automatically increase the size. So Array Index out of bounds exception will not come.


The default value of array list size is 10. Now if you will add the 11th element half size will be increased half of its original size.

Remember, Array list is not synchronized. If you array list should be synchronized, use the below.

Collections.synchronizedList( new ArrayList());

It supports three constructors.

1.ArrayList()
2.ArrayList(Collection c)
3.ArrayList(int capacity)


Create Array List

You ca create an array list like below.


ArrayList<String> list = new ArrayList<String>(); //This Array List will Store only String objects

Adding values into array list


You can add the values into array list with the help of add method. 

list.add("java");
list.add("check");

Getting index of values


If you want to know the index of particular value, you have to pass that into the indexOf method. It will give the index. 

int index = list.indexOf("check");


Getting size of Array list values


If you want to know the size of the array list, you can use the size method.

int size = list.size();

Checking the array list is empty or not


If you want to check whether an array list is empty or not, use isEmpty method.
 
boolean result = list.isEmpty();

If the result value is true means, that's empty.Otherwise not.

Checking array list have an item


The conatains method will helpful to check array list have specified item or not.

boolean check = list.contains("java");

If the check value have true means, it have "java" value. Otherwise not.

Getting array list values through loop

With for loop you can get all values of array list.


for (String data: list) {
    System.out.println("The values are " + data);  
}

Removing an element from array list

To remove the specified object from list, you can use remove method.


list.remove("java");


Copying the data with ArrayList


addAll method will helpful for adding all list into another list.

ArrayList<String> listNew = new ArrayList<String>();
listNew.addAll(list);

Iterator and List Iterator with array list


Already we have seen, we can use enhanced for loop to get list values. Now you can use iterator and list Iterator to get values. See the below,

Iterator it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

//Iterate with List Iterator

ListIterator listItr = list.listIterator();
while(listItr.hasNext()){
System.out.println(itr.next());
}

Simple array list example

package com.javahit.example;

import java.util.ArrayList;

public class JavaHitArrayList {

    public static void main(String[] args){

    //Creating arraylist... See I didn't mention any size
       
        ArrayList<String> al = new ArrayList<String>();
        //adding elements to the ArrayList
        al.add("one");
        al.add("two");
        al.add("three");
        al.add("four");
        System.out.println(al);

        //getting elements by index
        System.out.println("Index one value:"+al.get(1));


        //Checking the elements exist or not
        System.out.println("Checking existing value:"+al.contains("two"));

        //to add elements at index
        al.add(2,"PLAY");
       

        System.out.println("Checking array list empty "+al.isEmpty());
        System.out.println("Getting index value of two "+al.indexOf("two"));
        System.out.println("Arraylist size is: "+al.size());

        System.out.println(al);    
     }
}

Monday, February 24, 2014

Interface Interview Questions

1.What is Interface? 

You can only declare the method here, You can not implement here.

2.Why do we want to use Interface?

Java does not support multiple inheritance. Instead of that, we can use interface. Next thing is, it will               allow the third party to implement its methods.

3.Simple interface example

interface JavaHit {
void test(); //you can only do method declare here.
}

Important Note: After compilation, that method declaration will changed like
public abstract void test();
Because of, that interface should allow thaird party to implement that. So its giving access like public.

4.Can you write one interface example?

interface JavaHit {
void connect(); //it will change to public access after compilation.
oid disconnect();
}

class SqlDb implements JavaHit {
public void connect() {
System.out.println("SQL Database Connected");
}
public void disconnect() {
System.out.println("SQL Database Disconnected");
}
}
class OracleDb implements JavaHit {
public void connect() {
System.out.println("Oracle Database Connected");
}
public void disconnect() {
System.out.println("Oracle Database Disconnected");
}
}

5.Can I create methods inside interface with private or protected access?

No. public only allowed. Refer: Question 3

6.How do I create an object to interface?

You can not create object to interface class.

7.An interface can extend another interface?

Yes. Possible.

8.An interface can implement another interface?

No.

9.Can I write a class inside an interface?

Yes.

Friday, February 21, 2014

Interview Question about Static in java

1.What is static method?

Static method is a method , it should be declared with keyword static.

2.How will you call static method?

static method should be called by className.static method name.

e.g   A.test();
Here A is a class ad test is a static method.

3.Can I call static method with the help of object?

No. Before creating object static method should be called. I mean, static mehtod is not part of the object.

4.Can I use instance variable inside the static method?

No. JVM will create the object and instance variables after executing static method.So you can not use instance variable inside the static method.

5.What is static block?

static block is a block of statements declared as static.

e.g
static {
System.out.println("You are insdie static block");
}

6.Can I override static method in java?

No.

7.Can I overload static method?

Yes.

public class Test {
    public static void test() {
        System.out.println("Test for static overload I");
    }
    public static void test(int a) {
        System.out.println("Test for static overload II");
    }
    public static void main(String args[])
    {
        Test.test();
        Test.test(2);
    }
}

Output:

Test for static overload I
Test for static overload II

8.I have static block, static method and static variable. what is the order of execution?

static variable, static block, static method.

Saturday, February 15, 2014

Exception Handling Interview Questions

1.What are the 3 types of error?

1. Compile Time Error
2. Runtime Error
3. Error

2.What is Throwable?

Throwable is a class, for all errors and Exceptions.

3.What is the super class for all exceptions?

Exception class.

4.How will you create own exception in java?

You have to extends Exception class to create your own exception.

5.What are checked exception or Compile time Error?

The java compiler will check the exception at compile time is called checked exception.

6.What is unchecked exception or Runtime exception?

JVM will check the exception at runtime called unchecked exception.

7.What is Error?

Error is an error and it can not be handled by programmer. For example Memory error.

8.What is try catch in java?

try is the block , you can write your code logic here. Suppose if any exception will come in try block, you have to catch it.
For that you will write catch block to catch the exception.

For example,
try {
// DB connection coding
   }
catch(SQLException e){
e.printStackTrace();
}

9.What is throws and throw ?

If the programmer dont want to handle the exception, at the same time, programmer want to throw exception out of a method, throws will be helpful.

If the programmer want to throw the exception explicitly , then should handle it in catch block. 

So please remember throws and throw both are very different.

10.What is finally block?

whether the exception will occur or not, finally block will be executed. 

For example,

try {
// DB connection coding
   }
catch(SQLException e){
e.printStackTrace();
}
finally {
        // DB connection close code
}

So here, the exception will occur or not, finally bloack will be executed. DB connection will also close for security purpose.

11.Can I write the try block without catch block?

Yes. you can write try block without catch block.

12.Can I write the multiple catch block?

Yes.

13.What is nested try?

If you will write a try block within aother try, is called nested try.

14.Can I write the code between try and catch?

No.

Friday, February 14, 2014

String Interview Questions

1.Shall we consider String is a class or DataType or both?

You can consider string as a both class and datatype.

2.What is String constant pool?

It is a separate block of memory for strig objects and it will be assigned by JVM.
If you will use assignment operator, that wil be stored in constant pool only.

e.g String test="javahit";

3.Can you tell me the example for  ==  and equals()?

== does not compare the contet of the objects.
equals() - compare the contents.

e.g   Strig test = "java";
String check = "java";
if(test == check) {
System.out.println("Same");
else
System.out.pritln("Not same");
}

String t1 = new String("Test");
String t2 = new String("Test");

if(t1.equals(t2)) {
System.out.println("Same");
else
System.out.pritln("Not same");
}

4.Can you tell me some important methods in String class?

String concat(String t);
int length();
char charAt(int i);
int index(String s);
boolean equals(String s);
String substring(int i1, int i2);

Friday, February 7, 2014

Abstract Class

An abstract class can contain zero or more abstract methods. The abstract keyword must be used here.

For Example,

abstract class JavaHit
{
//abstract method
abstract void test(int n, int m);
}
class First extends JavaHit
{
//Add two values
void test(int j, int k)
{
          int p = j+k;
          System.out.println(“Added value is ” +  p  );
}
}
class Second extends JavaHit
{
          //Subtract two values
void test(int j, int k)
{
          int p = j-k;
          System.out.println(“Added value is ” +  p  );
}
}
class LastOne
{
          public static void main(String args[])
 {
          First first = new First();
          Second second = new Second();
          first.test(1,3);
          second.test(2,4);
}
}

Points to Remember:

1.You can have instance variables and concrete methods.
2.You cannot create object to abstract class.
3.While you are extending the abstract class, all the abstract methods should be implemented in its sub class.
4.If the abstract method is not implemented in its sub class, then that sub class should also use abstract keyword.

Monday, February 3, 2014

JDBC Database Connections

What is JDBC ad Why do we need it?
·        It is an API Java DataBase Connectivity
·        Connect to the DataBase.
·        Retrieve Data from DataBase
·        Insert data into DataBase.
Steps for JDBC Program
o   Register a Driver
o   Connect to the DataBase
o   SQL Statements
o   Executing SQL Statements
o   Retrieving Results
o   Closing Connection
How to Register a Driver?
Option 1:
You can register a driver with the help of registerDriver() method.
For example,
DriverManger.registerDriver( new sun.jdbc.odbc.jdbcodbcDriver());
Option 2:
You can register a driver with the help of forName() method.
For example,
Class.forName(sun.jdbc.odbc.jdbcodbcDriver);

How To Connect To DataBase?
1.You should pass the URL of the DataBase.
2.You should give DataBase UserName.
3. You should give DataBase Password.
Please see the below code.
DriverManager.getConection(“jdbc:odbc:oradsn”, “scott”, “sa”);

How To Prepare SQL Statements?
Here you can use two ways.
1.Statement
2.Prepared Statement
For executing query we can use both, But the difference is Perpared Statement is Fast and It is Pre Compile.
Please look the below code.
Statement stmt = con.createStatement();
Now we have to execute the query with the help of executeQuery()  method.
ResultSet rs = stmt.executeQuery(“select * from vendor”);
Now the query will be executed and result will be stored into ResultSet.
ResultSet have some methods. You can use this for retrieving datas.
The methods are,
String getString()
int getInt()
float getFloat() etc.,.
How to use these methods, can see later in example.
Example Program for JDBC Connection:
import java.sql.*;
class TestJdbc {
          public static void main(String args[]) {
                   //Driver Register
          DriverManger.registerDriver( new sun.jdbc.odbc.jdbcodbcDriver());
          //Connection with database
Connection con =     DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:     xe”, “test” , “sa”);
                   // for creating sql statement
                   Statemet stmt = con.createStatement();
                   //Executing statement
                   ResultSet rs = stmt.executeQuery(“Select * form vendor”);
                   // Retreiving results
                   While(rs.next()) {
                   System.out.pritln(“The vendor ID is ” + rs.getInt(1));
                   System.out.pritln(“Vendor Name ” + rs.getString());
                   System.out.pritln(“Vendor Fund Percent” + rs.getFloat());
                   }
con.close();
}

}

Thursday, January 30, 2014

Finding the Number of Words in a String

Write a program to find he Number of Words in a String


import java.util.Scanner;


public class NoOfWordsInAString {


    public static void main(String[] args) {


        Scanner sc=new Scanner(System.in);
        System.out.println("Enter your string:-");
        String str=sc.nextLine();
        int strLen=str.length();
        int word=1;
        for(int i=0;i<strLen-1;i++)
        {
            if((str.charAt(i))==' ')
            {
                word++;
            } 
        }
        System.out.print("The Number of words in the Given String are :" +word);
    }

}

OUTPUT:-

Enter your string:-
java test


The Number of words in the Given String are :2




To find length of the String

Write a program to find length of the String


import java.util.Scanner;


public class StringLength {

    public static void main(String[] args) {

            Scanner sc=new Scanner(System.in);
            System.out.println("Please Enter your String:-");
            String str=sc.nextLine();
            char c[]=new char[10];
            c= str.toCharArray();
            int count=0;
               try{
                    for( count=0;c[count] !='\0'; count++);
               }
              catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println(count);
         }
    
    }
}

OUTPUT:-

Please Enter your String:-
javainchennai
The Length of the Given String is: 13