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();
}

}