corejava

"CoreJava "


This Section focuses on basics of java including Access-Modifiers,Exception ,Memory-Management, Threads, Collections,JDBC,IO,Networking.

1 )   Why java is platform independent ?

Ans)

  • null
    Sample Img 1
Java solves the problem of platform-independence by using byte code. The Java compiler does not produce native executable code for a particular machine like a C compiler would. Instead it produces a special format called byte  code.

But still Java programs that have been compiled into byte code need an interpreter to execute them on any given platform. The interpreter reads the byte code and translates it into the native language of the host machine on the fly.



2 )   What is JVM ?

Ans)

  • JVM
    Sample Img 2
A Java virtual machine is software that is implemented on virtual and non-virtual hardware and on standard operating systems such as Windows, Linux, Solaris,Unix. A JVM provides an environment in which Java bytecode can be executed. JVMs are available for many hardware and software platforms. The use of the same bytecode for all JVMs on all platforms allows Java to be described as a write once, run anywhere programming language.



3 )   What is Heap/Stack ?

Ans)

  • Heap/Stack
    Sample Img 3
The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.
The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time;



4 )   Instance Variables will be in Heap Or Stack ?

Ans)
Instance Variables will be in Heap.



5 )   What is Transient Variable ?

Ans)
Transient Variable is a variable which cannot be serialized .
For example if a variable is declared as transient in a Serializable  class and the class is written to an ObjectStream, the value of the variable can't be written to the stream
instead when the class is retrieved from the ObjectStream the value of the variable becomes null
public class userData {
     private transient String password;
}



6 )   What are Finally and Finalize Keywords ?

Ans)

  • Finally and Finalize
    Sample Img 6
final – constant declaration.
public static final String HOST_NAME = "yourhost":
finally – The finally block always executes when the try block exits, except System.exit(0) call.
This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling —
it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally
block is always a good practice, even when no exceptions are anticipated.
try {
finally {
   out.close();
   conn.close();
}


finalize() – method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector,
allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets,
database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection
is going to kick in to release these non-memory resources through the finalize() method.



7 )   What is an Abstract Class ?

Ans)

  •  Abstract Class
    Sample Img 7
An Abstract Class is class which contains Abstract methods, the methods without implementation. Abstract classes could not be instantiated , you need to create a subclass and provide implementation for these unimplemented classes. Please note an Abstract Class can exist without abstract methods, but your application design has to be reviewed and see why you create an Abstract class without an Abstract methods. Please see the example below.
Public abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}

Public class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}





8 )   What is the Difference between Static Inner Class and a Inner class

Ans)
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass 
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass()
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
class OuterClass {
    ...
    class InnerClass {
        ...
    }

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
8) Is an inner class able to access only Final Outer variables ?
Yes, Inner class could access only the “final” outer instance variables.



9 )   What kind of outer class variable could an Inner class would access ?

Ans)
Inner classes could access only the Final Outer Class Variables .



10 )   What is an anonymous Inner Class and a Innter class ?

Ans)
"An anonymous class is essentially a local class without a name."
    As you will see from the sample program in this lesson, anonymous class definitions are often included as arguments to method calls.
    Button buttonC = new Button("C");

    buttonC.addMouseListener(new MouseListener()
    {//begin class definition
    //Instance initialize
    {System.out.println(
    "Anonymous class C name: " +
    getClass().getName());}

    As is the case for an object of a member class or a local class(an inner class) (discussed in previous lessons), an object of an anonymous class must be internally linked to an object of the enclosing class.
    Thus, an anonymous class is truly an inner class, because an object of the anonymous class cannot exist in the absence of an object of the enclosing class.



    11 )   What you could when you get "OutOFMemoryError"

    Ans)

    • OutofmemoryError ?
      Sample Img 11
    "OutofmemoryError" error occurs when JVM is unable to allocate Memory for creating any
    new variables while performing some task.
    This could be solved in by following steps:
    i) First and foremost, check the memory settings of your application (JVM), if there is
    any scope to increase the Memory settings, please change those, if not you may need to
    tune the application. So first please review the Memory Parameters i.e. "-Xmx. -Xmx" values,
    usually you could find these in SetEnv bat (or .sh) file or you could also  provide these as
    System (-D) parameters to JVM.
    -Xmn512M -Xms1024M
    ii) Tune the application by using some Profilers such as JProfilier or Optimize it and make sure
    all Unused objects are reachable to Garbage Collectors by setting the NULL value to
    garbage-collect them.
    iii) Use soft Or Weak references to avoid this as shown below.
         private  SoftReference<byte[]> bufferRef;
    iv) Close all Database Connections and File IO streams properly in Finally block as
    shown below and avoid connection leaks.
         try{
            } finally {
              con.close();
         }
    v) Close all IO streams which are used for performing File operations such as filinputsteam
     or filinputsteam.
              FileInputStream fin = null;
         try{
             fin = new FileInputStream(file)
            } finally {
              fin.close();
         }
    vi) See if you could use Object Pool instead of creating unlimited new Objects.




    12 )   What is the Differance between Exception and Error ?

    Ans)
    An Error "indicates serious problems that a reasonable application should not try to catch."
    An Exception "indicates conditions that a reasonable application might want to catch."
    In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.



    13 )   What is the differance between Checked and Unchecked Exceptions ?

    Ans)
    Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller
    On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything goes well, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. These should be resolved by following good Coding standards and having code reviews ect.,



    14 )   What is a Thread?

    Ans)
    A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.



    15 )   What is the differance between Thread and Process ?

    Ans)

    • Thread VS Process
      Sample Img 15
    • Threads are lightweight compared to processes
    • Threads share the same address space and therefore can share both data and code
    • Context switching between threads is usually less expensive than between processes
    • Cost of thread intercommunication is relatively low that that of process intercommunication
    • Threads allow different tasks to be performed concurrently.



    16 )   How many way you create Thread in Java ?, what are those?

    Ans)
    There are two ways to create thread in java;
      • Implement the Runnable interface (java.lang.Runnable)
      • By Extending the Thread class (java.lang.Thread)
    class RunnableThread implements Runnable {
            Thread runner;
            public RunnableThread(String threadName) {
                    runner = new Thread(this, threadName);
                    runner.start();
            }
            public void run() {
            }
    }
    class MyThread extends Thread {
            MyThread() {
            }
            MyThread(String threadName) {
                    super(threadName); // Initialize thread.
                    start();
            }
            public void run() {
            }
    }



    17 )   Thread LifeCycle ?

    Ans)

    • Thread LifeCycle
      Sample Img 17
    • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
    • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
    • Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
    • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
    • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.



    18 )   What is the Synchronizied Keyword ?, what is Thread Racing ?

    Ans)

    • Thread Racing and Synchronizied
      Sample Img 18
    A race condition occurs when the order of execution of two or more threads may affect
    some variable or outcome in the program.
     It may turn out that all the different possible
    thread orderings have the same final effect on the application: the effect caused by the race
    condition may be insignificant, and may not even be relevant.
    Synchronized keyword can be applied to static/non-static methods or a block of code to make
    your code Thread Safe.
     Only one thread at a time can access synchronized methods and if
    there are multiple threads trying to access the same method then other threads have to
    wait for the execution of method by one thread. Synchronized keywordprovides a lock
    on the object and thus prevents race condition.
    public void synchronized method(){}
    public void synchronized staticmethod(){}
    public void myMethod(){
                synchronized (this){         
                }
    }



    19 )   What are Read/Write Locks ?

    Ans)

    public class DataReader  {
     private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
     private static final Lock read = readWriteLock.readLock();
     private static final Lock write = readWriteLock.writeLock();

     public static void loadData() {
      try {
       write.lock();
       loadDataFromTheDB());
      } finally {
       write.unlock();
      }
     }

     public static boolean readData() {
      try {
       read.lock();
       readData();
      } finally {
       read.unlock();
      }
     }
     public static List loadDataFromTheDB() {
         List list = new ArrayList();
      return list;
     }
        public static void readData() throws DataServicesException {
         //Write reading logic
        }
    }





    20 )   What is the Java Thread Executor Framework ?

    Ans)

    • Java Thread Executor Framework
      Sample Img 20

    Java Thread Executor is simple Java Framework which is based on "Master-Slave
    architectural design pattern" allows us to perform multiple tasks asynchronously
    for better performance. In general Tasks are logical units of work, and threads
    are a mechanism by which tasks can run asynchronously. Also this Framework
    takes the Overhead of managing the Threads and its priorities and frees you from them.
    By decoupling the task submission from execution, we can easily change or specify
    execution policies, such as
    • execution order, how many tasks are allowed to run concurrently
     and how many are queued, etc.
    Here is the Simple Example :
    Step 1 : Create an "ExecutorService" with Number of Thread you would like to have.
      //Let us start the Worked Threads
                    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
                 
    Step 2 : Create a Worker Thread, which actually perform the given task, your Worker Thread perform different tasks,
    public class EmailSender  implements Runnable {
            String message;
            EmailSender  (String message) {
                    this.message = message;
            }
            public void run() {
                    try {
                            sendEmail(message);
                    } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
            }
         
        private static void sendEmail(String message2)  {
              System.out.println("Sending Email" + message);
        }
    }
    Step 3 : Assign these Tasks to Executor
            //Let us start the Worked Threads
                    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
                    for (int i = 0; i < 6; i++) {
                            DateRange dateRange = new DateRange();
                            Runnable worker = new BatchRunnable(dateRange);
                            executor.execute(worker);
                    }
                 
    Step 4: Terminate the Executor by invoking the LifeCycle methods
                    // This will make the executor accept no new threads
                    // and finish all existing threads in the queue
                    executor.shutdown();
                    // Wait until all threads are finish
                    while (!executor.isTerminated()) {
                    } 



    21 )   What are Thread Sleep and Join ?

    Ans)
    There is a difference between join() and sleep(). join() will wait until the timeout expires or the thread finishes. sleep() will just wait for the specified amount of time unless interrupted. So it is perfectly possible for join() to return much faster than the specified time.



    22 )   What is the Use of ThreadLocal ?

    Ans)
    A thread-local variable effectively provides a separate copy of its value for each thread
    that uses it.
     Each thread can see only the value associated with that thread, and is unaware
    that other threads may be using or modifying their own copies.
    Because thread-local variables are implemented through a class, rather than as part of the
    Java language itself, the syntax for using thread-local variables is a bit more clumsy than for
    language dialects where thread-local variables are built in.
    To create a thread-local variable, you instantiate an object of class ThreadLocal. In following
    Example "userName" is stored in a ThreadLocal.
    Please note this really useful to Cache Some Data per a Request.
    public class YourDataHolder {
       private static ThreadLocal dataVariable = new ThreadLocal();
       private static YourDataHolder dataHolderVar ;
       private YourDataHolder() {
       }
       public void storeDataToThreadLocal (String userName) {
        dataVariable.set(userName);
       }
       public String readDataFromThreadLocal ()  {
        if (dataVariable.get() != null) {
            return (String) dataVariable.get();
        }
       }
       public static ServiceVersionHolder getInstance () {
        if (dataHolderVar == null) {
         dataHolderVar = new YourDataHolder();
        }
        return dataHolderVar;
       }
    }



    23 )   What is the Difference between ArrayList/Vector?

    Ans)

    • null
      Sample Img 23
    Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList
    A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later.



    24 )   How to read both "Key" and "Value" from the Map ?

    Ans)
    You could use "Map.Entry", which is key-value pair of the Map.
    Below is the e.g.
      Map<String,String> empmapNew = new HashMap<String,String>();
      empmapNewput("68688","Jones");
      empmapNew.put("777777","Smith");

      Set s = empmapNew.entrySet();
      for(Iterator i = s.iterator();i.hasNext();){
       Map.Entry me = (Map.Entry)i.next();
       System.out.println(me.getKey() + " : " + me.getValue());

      }



    25 )   What is the Differance between Hashtable/HashMap? What is HashSet ?

    Ans)

    • Hashtable/HashMap/HashSet
      Sample Img 25
    Hashtable is one implementation of that interface, for the "old" days when it was thought that having everything synchronized is a good idea (ref. Vector). It offers "kind of" thread-safety, if you know what you are doing. If you are serious about a map which can be used from multiple threads you should absolutely check out the ConcurrentHashMap and ConcurrentSkipListMap.
    HashMap is almost the same as a Hashtable, but with the synchronization removed. It's the preferred general-purpose Map implementation.
    HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.



    26 )   What is the use of collections framework ? How do you Sort the ArrayList

    Ans)
    "Collections" could be used to perfome some operations like "sort()" , "synchronizedList()" etc., this uses "Command Design Pattern".
    Collections.sort(questionVOList.getQuestionList(), new QuestionVOComparator());
     public static class QuestionVOComparator implements Comparator {
      @Override
         public int compare(Object o1, Object o2) {
             return ((QuestionVO)o1).getQuestionIdAsInt() - ((QuestionVO)o2).getQuestionIdAsInt();
         }
     }



    27 )   What are different types of JDBC Drivers ?

    Ans)

    • Types of JDBC Drivers
      Sample Img 27
     There are Four types of JDBC Drivers
    Type1 - JDBC-ODBC bridge plus ODBC driver(Bridge):
    The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver
    implementation that employs the ODBC driver to connect to the database. The driver
    converts JDBC method calls into ODBC function calls. As a result, this kind of driver
     is most appropriate on a corporate network where client installations are not a major
     problem, or for application server code written in Java in a three-tier architecture.
    Type 2 - Native-API partly-Java driver(Native):
    The JDBC type 2 driver, also known as the Native-API driver, is a database driver
    implementation that uses the client-side libraries of the database. The driver converts
    JDBC method calls into native calls of the database API.This kind of driver converts
    JDBC calls into calls on the client API for Oracle, Sybase, Informix, IBM DB2, or other DBMSs.
    Type 3 - JDBC-Net pure Java driver(Middleware):
    The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is a
    database driver implementation which makes use of a middle tier between the calling
    program and the database. The middle-tier (application server) converts JDBC calls
    directly or indirectly into the vendor-specific database protocol. This driver translates
    JDBC calls into a DBMS-independent net protocol, which is then translated to
    a DBMS protocol by a server.
    Type 4 - Native-protocol pure Java driver(Pure):
    The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database
    driver implementation that converts JDBC calls directly into a vendor-specific database protocol.
    This kind of driver converts JDBC calls directly into the network protocol used by DBMSs.
    This allows a direct call from the client machine to the DBMS server and is an excellent
    solution for intranet access.
    So Driver categories 3 and 4 are the preferred way to access databases using the JDBC API.



    28 )   What is the Prepared Statement ?, what is the advantage we get with this ?

    Ans)
    For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.
    Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.

        PreparedStatement updateTotal = null;
        String updateStatement = "update " + dbName + ".COFFEES " +
            "set TOTAL = TOTAL + ? " +
            "where COF_NAME = ?";
        try {
            con.setAutoCommit(false);
            updateTotal = con.prepareStatement(updateStatement);
            for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
                updateTotal.setInt(1, e.getValue().intValue());
                updateTotal.setString(2, e.getKey());
                updateTotal.executeUpdate();
                con.commit();
            }
        } catch (SQLException e ) {}




    29 )   How you invoke DB StoredProcedure with JDBC ?

    Ans)
    By using callable statements , we could invoke Stored Procedures by using JDBC.

    CallableStatement cs = null;
    cs = this.con.prepareCall("{call SHOW_SUPPLIERS}");
    ResultSet rs = cs.executeQuery();
    // Read the out parameter like this
    while (rs.next()) {
        String supplier = rs.getString("SUP_NAME");
        String coffee = rs.getString("COF_NAME");
        System.out.println(supplier + ": " + coffee);
    }



    30 )   How do you query a huge table which has 1 million records in it?

    Ans)
    Consider a scenario where we have a huge database table with (say 1 million records),
    and the requirement is to display those records in your application UI, how could we
    do this.
    The challenge in this is that Querying DB tables with huge set of records it will take more
    time to iterate the records from DB and more over we get OutOfMemory error if we load
    such a huge ResultSet into JVM memory.
    To avoid these kind of issues, better set the ResultSet FetchSize to appropriate number
    so that your JDBC Statement would fetch only that number of records.
     rs.setFetchSize(fetchSize);



    31 )   What are connection Leaks?

    Ans)
    An application(basically application server) is said to be leaking connection, if it acquires a connection and does not close it within specified time period. If this feature is enabled, the application server detects these potential connection leaks and dumps the leak tracing logs to server logs (you have to enable JDBC logs by using Admin console). Looking at the logs the user can figure out which application is leaking connection and fix the issues with application, if exists.
    We can avoid these connection leaks by reviewing code with the help of logs and close all the connections properly as shown below.
    try{ }catch (Exception e){
                                             e.printStackTrace();
                                      } finally {
                                            if (rs != null) {
                                                    rs.close();
                                            }
                                            if (con != null) {
                                                    con.close();
                                            }
                                   }



    32 )   Two Phase commit ?

    Ans)

    • Two Phase commit
      Sample Img 32
    Two-phase commit is a transaction protocol designed for the complications that arise with distributed resource managers. With a two-phase commit protocol, the distributed transaction manager employs a coordinator to manage the individual resource managers.
    The commit process proceeds as follows:
    Phase 1
    Each participating resource manager coordinates local operations and forces all log records out: 
    If successful, respond "OK" 
    If unsuccessful, either allow a time-out or respond "OOPS" 
    Phase 2
    If all participants respond "OK": 
    Coordinator instructs participating resource managers to "COMMIT" 
    Participants complete operation writing the log record for the commit 
    Otherwise:
    Coordinator instructs participating resource managers to "ROLLBACK" 
    Participants complete their respective local undos.



    33 )   JDBC Tuning ?

    Ans)
     1) Turn off auto-commit for better performance, especially when you use callable statements
        or just querying database.
        conn.setAutoCommit(false);
     2) Use the PreparedStatement object for overall database efficiency.
         When you use a PreparedStatement object to execute a SQL statement, the statement is
         parsed and compiled by the database, and then placed in a statement cache.
     3) Use PreparedStatements for batching repetitive inserts or updates.
         With Oracle, you can choose standard JDBC batching using the addBatch() and executeBatch()
         methods, or you can choose Oracle's proprietary method, which is faster, by utilizing the
        OraclePreparedStatement's setExecuteBatch() method along with the standard executeUpdate()
        method.
      To use Oracle's proprietary batching mechanism, call setExecuteBatch() as follows:  
           PreparedStatement pstmt3D null;
              try {
                  ((OraclePreparedStatement)pstmt).setExecuteBatch(30);
                  pstmt.executeUpdate();
           }

    4) Create Indexes on your Database Bases.
     5) Use DataBase Views instead of using tables for quering.
     6)Set the dataBase PageSize properly to appropriately value.
     7) The higher the level of transaction protection, the higher the performance penalty.
     Transaction levels in order of increasing level are:
     TRANSACTION_NONE,
     TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITTED, TRANSACTION_REPEATABLE_READ,
     TRANSACTION_SERIALIZABLE. Use Connection.setTransactionIsolation() to set the desired
     tansaction level.
    8)  The default autocommit mode imposes a performance penalty by making every database
        command a separate transaction. Turn off autocommit (Connection.setAutoCommit(false)),
            and explicitly specify transactions.
        Use Connection.setReadOnly(true) to optimize read-only database interactions.



    34 )   JDBC Batch Updates ?

    Ans)
    JDBC batch update is a collectively called when a group of SQL statements are executed simultaneously to a database as a single unit.
     The batch is sent to the database in a single request using connection object. The advantage of batch is to reduce the network calls between the
     front end application and its database rather  than executing single SQL statement.  Please take a look at the example below.
      con = DriverManager.getConnection(url + db, user, pass);
      con.setAutoCommit(false);// Disables auto-commit.
      st = con.createStatement();
      st.addBatch("update person set cname='Smith' where id='1'");
      st.addBatch("update person set cname='Dave' where id='2'");
      st.addBatch("update person set cname='Chris' where id='3'");
      st.executeBatch();

      String sql = "select * from person";
      rs = st.executeQuery(sql);
      System.out.println("No Name");
      while (rs.next()) {
      System.out.print(rs.getString(1) + " \t");
      System.out.println(rs.getString(2));
      }
      rs.close();




    35 )   What is Blob and How do you read it ?

    Ans)
    Ans)
    A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:
        Call the getBlob method of the PreparedStatement class to retrieve a java.sql.Blob object
        Call either getBinaryStream or getBytes in the extracted Blob object to retrieve the java byte[] which is the Blob object.

             PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");
             // Execute
             ResultSet rs = stmnt.executeQuery();
             while(rs.next())
             {
                try
                {
                   // Get as a BLOB
                   Blob aBlob = rs.getBlob(1);
                   byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());
                }
                catch(Exception ex)
                {
                }
             }
           rs.close();
           stmnt.close();



    36 )   Copy Properties from one Bean to another Bean ?

    Ans)
     You got to use "BeanUtils" for this purpose , this is really helpful when you want generalize some solution.  
    FromBean fromBean = new FromBean("fromBean", "fromBeanAProp");
      ToBean toBean = new ToBean("toBean", "toBeanBProp");
      try {
          BeanUtils.copyProperties(toBean, fromBean);
      
    } catch (IllegalAccessException e) {
       e.printStackTrace();
      } catch (InvocationTargetException e) {
       e.printStackTrace();
      }



    37 )   What is Serialization ?

    Ans)

    • Serialization
      Sample Img 37
    Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes,
    which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by
    Objects would be passed between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation.
    The object which is to be serialzed should implement "Serializable" interface.
     class PersonDetails implements Serializable

    We use ObjectOutputStream to Serialize the Objects,  please take a look at colored code snippet below.
       FileOutputStream fos = null;
      ObjectOutputStream out = null;
      try {
       fos = new FileOutputStream(filename);
       out = new ObjectOutputStream(fos);
       out.writeObject(list);
       out.close();
       System.out.println("Object Persisted");
      } catch (IOException ex) {
       ex.printStackTrace();
      }



    38 )   How you know that you Object has been added to JNDI properly ?

    Ans)
    You have log in into your App server console and take a look at the JNDI tree and see if this Object is being added to JNDI tree .



    39 )   Socket accept() ?

    Ans)
    A ServerSocket generally operates in a loop that repeatedly accepts connections. Each pass through the loop invokes the accept( ) method,
    This returns a Socket object representing the connection between the remote client and the local server.
    Sample :
     ServerSocket server = new ServerSocket(5776);
     
    while (true) {
       Socket connection = server.accept(  );
       OutputStreamWriter out
        = new OutputStreamWriter(connection.getOutputStream(  ));
       out.write("You've connected to this server. Bye-bye now.\r\n");     
       connection.close(  );
     }





    40 )   What is a Socket ?

    Ans)
    Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits,
    listening to the socket for a client to make a connection request.



    41 )   What is ServerSocket ?

    Ans)
    The ServerSocket class contains everything you need to write servers in Java. It has constructors that create new ServerSocket
    objects, methods that listen for connections on a specified port, and methods that return a Socket object when a connection is made
    so that you can send and receive data.
    Example :
    ServerSocket httpd = new ServerSocket(80);



    42 )   How a ServerSocket Accept the Client Requests ?

    Ans)

    • TCP Client  Server
      Sample Img 42
    A ServerSocket generally operates in a loop that repeatedly accepts connections. Each pass through the loop invokes the accept( ) method.
    This returns a Socket object representing the connection between the remote client and the local server.
    ServerSocket server = new ServerSocket(5776);
     whi
    le (true) {
       Socket connection = server.accept(  );
       OutputStreamWriter out
        = new OutputStreamWriter(connection.getOutputStream(  ));
       out.write("You've connected to this server. Bye-bye now.\r\n");     
       connection.close(  );
     }




    43 )   What is TCP/IP ? and What are the layers in that ?

    Ans)

    • TCP/IP Layers
      Sample Img 43
    TCP/IP model is a suite of protocol named after its most significant pair of protocols the Transmission Control
    Protocol and Internet Protocol. It is made of five layers, each layer is responsible for a set of computer network
    related tasks. Every layer provides service to the the layer above it.
    It has the following Layers
    application
    transport
    network /internet
    data link
    physical



    44 )   What is UDP ?

    Ans)
    The UDP protocol provides a mode of network communication whereby applications send packets of data, called datagrams,
    to one another.
    A datagram is an independent, self-contained message sent over the network whose arrival, arrival time,
    and content are not guaranteed. The DatagramPacket and DatagramSocket classes in the java.net package implement system-independent
    datagram communication using UDP.
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
              serverSocket.receive(receivePacket);