Java Interview Questions

Share Embed Donate


Short Description

Download Java Interview Questions...

Description

Junior Java programmer interview questions What is the purpose of finalization? - The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. What is the difference between between the Boolean & operator and the && operator? - If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. 2. How many times may an object’s finalize() method be invoked by the garbage collector? - An object’s finalize() method may only be invoked once by the garbage collector. 3. What is the purpose of the finally clause of a try-catch-finally statement? - The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or  caught. 4. What is the argument type of a program’s main() method? - A program’s main() method takes an argument of the String[] type. 5. Which Java operator is right associative? - The = operator is right associative. 6. Can a double value be cast to a byte? - Yes, a double value can be cast to a byte. 7. What is the difference between a break statement and a continue statement? - A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. 8. What must a class do to implement an interface? - It must provide all of the methods in the interface and identify the interface in its implements clause. 9. What is the advantage of the event-delegation model over the earlier event-inheritance model? - The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their  containers). This allows a clean separation between a component’s design and its use. The other  advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly repeatedly process unhandled unhandled events, as is the case of the event-inheritanc event-inheritancee model. 10.How are commas used in the intialization and iteration parts of a for statement? - Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. abstract method is a method whose implementation implementation is deferred 11.What is an abstract method? - An abstract to a subclass. 12.What value does read() return when it has reached the end of a file? - The read() method returns -1 when it has reached the end of a file. 13.Can a Byte object be cast to a double value? - No, an object cannot be cast to a primitive value. 14.What is the difference between a static and a non-static inner class? - A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner  class does not have any object instances. 15.If a variable is declared as private, where may the variable be accessed? - A private variable may only be accessed within the class in which it is declared. 16.What is an object’s lock and which object’s have locks? - An object’s lock is a mechanism that is used used by multip multiple le thread threadss to obtain obtain synchr synchroni onized zed access access to the object. object. A thread thread may execute execute a 1.

synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object. 17.What is the % operator? - It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 18.When can an object reference be cast to an interface reference? - An object reference be cast to an interface reference when the object implements the referenced interface. 19.Which class is extended by all other classes? - The Object class is extended by all other classes. 20.Can an object be garbage collected while it is still reachable? - A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. 21.Is the ternary operator written x : y ? z or x ? y : z ? - It is written x ? y : z. 22.How is rounding performed under integer division? - The fractional part of the result is truncated. This is known as rounding toward zero. is the difference between the Reader/Writer class hierarchy and the 23.What InputStream/OutputStream class hierarchy? - The Reader/Writer class hierarchy is characteroriented, and the InputStream/OutputStream class hierarchy is byte-oriented. 24.What classes of exceptions may be caught by a catch clause? - A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. 25.If a class is declared without any access modifiers, where may the class be accessed? - A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. 26.Does a class inherit the constructors of its superclass? - A class does not inherit constructors from any of its superclasses. 27.What is the purpose of the System class? - The purpose of the System class is to provide access to system resources. 28.Name the eight primitive Java types. - The eight primitive types are byte, char, short, int, long, float, double, and boolean. 29.Which class should you use to obtain design information about an object? - The Class class is used to obtain information about an object’s design. Core Java interview questions Can there be an abstract class with no abstract methods in it? - Yes Can an Interface be final? - No 2. Can an Interface have an inner class? - Yes. 3. public interface abc 4. { 5. static int i=0; void dd(); 6. class a1 7. { 8. a1() 9. { 10. int j; 11. System.out.println("inside"); 12. }; 13. public static void main(String a1[]) 14. { 15. System.out.println("in interfia"); 1.

16. 17. 18.

} }

} 19.Can we define private and protected modifiers for variables in interfaces? - No 20.What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in) 21.What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces. 22.What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables 23.What are the different identifier states of a Thread? - The different identifiers of a Thread are: R Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock  24.What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass). 25.Why isn’t there operator overloading? - Because C++ has proven by example that operator  overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like   print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte(). 26.What does it mean that a method or field is “static”? - Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class. 27.How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com? 28. String hostname = InetAddress.getByName("192.18.97.39").getHostName(); 29.Difference between JRE/JVM/JDK? 30.Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other  threads may execute while the I/O operation is performed. 31.What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors. 32.Is null a keyword? - The null value is not a keyword. 33.Which characters may be used as the second character of an identifier,but not as the first character of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

modifiers may be used with an inner class that is a member of an outer class? - A (nonlocal) inner class may be declared as public, protected, private, static, final, or abstract. 35.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF16 uses 16-bit and larger bit patterns. 36.What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects. 37.What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excluding blank lines and comments). 38.What is the difference between preemptive scheduling and time slicing? - Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher   priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. 39.What is a native method? - A native method is a method that is implemented in a language other  than Java. 40.What are order of precedence and associativity, and how are they used? - Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether  an expression is evaluated left-to-right or right-to-left 41.What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. 42.Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do  both. 43.What is the range of the char type? - The range of the char type is 0 to 2^16 - 1. 34.What

Java interview questions and answers 1.

2. 3.

4. 5.

6.

7.

8.

What is garbage collection? What is the process that is responsible for doing that in java? Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this  process What kind of thread is the Garbage collector thread? - It is a daemon thread. What is a daemon thread? - These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly. How will you invoke any external process in Java? - Runtime.getRuntime().exec(….) What is the finalize method do? - Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected. What is mutable object and immutable object? - If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …) What is the basic difference between string and stringbuffer object? - String is an immutable object. StringBuffer is a mutable object. What is the purpose of Void class? - The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

What is reflection? - Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. 10.What is the base class for Error and Exception? - Throwable 11.What is the byte range? -128 to 127 12.What is the implementation of destroy method in java.. is it native or java code? - This method is not implemented. 13.What is a package? - To group set of classes into a single unit is known as packaging. Packages  provides wide namespace ability. 14.What are the approaches that you will follow for making a program very efficient? - By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for  multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more. 15.What is a DatabaseMetaData? - Comprehensive information about the database as a whole. 16.What is Locale? - A Locale object represents a specific geographical, political, or cultural region 17.How will you load a specific locale? - Using ResourceBundle.getBundle(…); 18.What is JIT and its use? - Really, just a very fast compiler… In this incarnation, pretty much a one  pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem. 19.Is JVM a compiler or an interpreter? - Interpreter  20.When you think about optimization, what is the best way to findout the time/memory consuming process? - Using profiler  21.What is the purpose of assert keyword used in JDK1.4.x? - In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing. 22.How will you get the platform dependent values like line separator, path separator, etc., ? Using Sytem.getProperty(…) (line.separator, path.separator, …) 23.What is skeleton and stub? what is the purpose of those? - Stub is a client side representation of  the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK. 24.What is the final keyword denotes? - final keyword denotes that it is the final implementation for  that method or variable or class. You can’t override that method/variable/class any more. 25.What is the significance of ListIterator? - You can iterate back and forth. 26.What is the major difference between LinkedList and ArrayList? - LinkedList are meant for  sequential accessing. ArrayList are meant for random accessing. 27.What is nested class? - If all the methods of a inner class is static then it is a nested class. 28.What is inner class? - If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class. 29.What is composition? - Holding the reference of the other class within some other class is known as composition. 30.What is aggregation? - It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation. 9.

are the methods in Object? - clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString 32.Can you instantiate the Math class? - You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public. 33.What is singleton? - It is one of the design pattern. This falls in the creational pattern of the design  pattern. There will be only one instance for that entire JVM. You can achieve this by having the  private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … } 34.What is DriverManager? - The basic service to manage set of JDBC drivers. 35.What is Class.forName() does and how it is useful? - It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ). 36.Inq adds a question: Expain the reason for each keyword of  31.What

 public static void main(String args[]) Basic Java interview questions What is a Marker Interface? - An interface with no methods. Example: Serializable, Remote, Cloneable What interface do you implement to do the sorting? - Comparable 2. What is the eligibility for a object to get cloned? - It must implement the Cloneable interface 3. What is the purpose of abstract class? - It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class. 4. What is the difference between interface and abstract class? - Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures. 5. What do you mean by RMI and how it is useful? - RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere. 6. What is the protocol used by RMI? - RMI-IIOP 7. What is a hashCode? - hash code value for this object which is unique for every object. 8. What is a thread? - Thread is a block of code which can execute concurrently with other threads in the JVM. 9. What is the algorithm used in Thread scheduling? - Fixed priority scheduling. 10.What is hash-collision in Hashtable and how it is handled in Java? - Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision. 11.What are the different driver types available in JDBC? - 1. A JDBC-ODBC bridge 2. A nativeAPI partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description 12.Is JDBC-ODBC bridge multi-threaded? - No 13.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?  No 14.What is the use of serializable? - To persist the state of an object into any perminant storage device. 1.

is the use of transient? - It is an indicator to the JVM that those variables should not be  persisted. It is the users responsibility to initialize the value when read back from the storage. 16.What are the different level lockings using the synchronization keyword? - Class level lock  Object level lock Method level lock Block level lock  17.What is the use of preparedstatement? - Preparedstatements are precompiled statements. It is mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk   processing. 18.What is callable statement? Tell me the way to get the callable statement? - Callablestatements are used to invoke the stored procedures. You can obtain the callablestatement from Connection using the following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency) 19.In a statement, I am executing a batch. What is the result of the execution? - It returns the int array. The array contains the affected row count in the corresponding index of the SQL. 20.Can a abstract method have the static qualifier? - No 21.What are the different types of qualifier and what is the default qualifier? - public, protected,  private, package (default) 22.What is the super class of Hashtable? - Dictionary 23.What is a lightweight component? - Lightweight components are the one which doesn’t go with the native call to obtain the graphical units. They share their parent component graphical units to render  them. Example, Swing components 24.What is a heavyweight component? - For every paint call, there will be a native call to get the graphical units. Example, AWT. 25.What is an applet? - Applet is a program which can get downloaded into a client environment and start executing there. 26.What do you mean by a Classloader? - Classloader is the one which loads the classes into the JVM. 27.What are the implicit packages that need not get imported into a class file? - java.lang 28.What is the difference between lightweight and heavyweight component? - Lightweight components reuses its parents graphical units. Heavyweight components goes with the native graphical unit for every component. Lightweight components are faster than the heavyweight components. 29.What are the ways in which you can instantiate a thread? - Using Thread class By implementing the Runnable interface and giving that handle to the Thread class. 30.What are the states of a thread? - 1. New 2. Runnable 3. Not Runnable 4. Dead 31.What is a socket? - A socket is an endpoint for communication between two machines. 32.How will you establish the connection between the servlet and an applet? - Using the URL, I will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data. 33.What are the threads will start, when you start the java program? - Finalizer, Main, Reference Handler, Signal Dispatcher  15.What

Interview questions for Java junior developer position What gives Java its “write once and run anywhere” nature? - Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platorm specific and hence can be fed to any platform. After being fed to the JVM, which is specific to a particular operating system, the code platform specific machine code is generated thus making java platform independent.

What are the four corner stones of OOP? - Abstraction, Encapsulation, Polymorphism and Inheritance. 2. Difference between a Class and an Object? - A class is a definition or prototype whereas an object is an instance or living representation of the prototype. 3. What is the difference between method overriding and overloading? - Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments. 4. What is a “stateless” protocol? - Without getting into lengthy debates, it is generally accepted that  protocols like HTTP are stateless i.e. there is no retention of state between a transaction which is a single request response combination. 5. What is constructor chaining and how is it achieved in Java? - A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement. 6. What is passed by ref and what by value? - All Java method arguments are passed by value. However, Java does manipulate objects by reference, and all object variables themselves are references 7. Can RMI and Corba based applications interact? - Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP. 8. You can create a String object as String str = “abc”; Why cant a button object be created as Button bt = “abc”;? Explain - The main reason you cannot create a button by Button bt1= “abc”; is  because “abc” is a literal string (something slightly different than a String object, by the way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String. Important to note that you are NOT calling a java.lang.String constuctor when you type String s = “abc”; 9. What does the “abstract” keyword mean in front of a method? A class? - Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of it,it is called abstract method.Abstract method hs no body.It has only arguments and return type.Abstract methods act as placeholder methods that are implemented in the subclasses. Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be created.If a class contains any abstract method it must be declared as abstract. 10.How many methods do u implement if implement the Serializable Interface? - The Serializable interface is just a “marker” interface, with no methods of its own to implement. Other ‘marker’ interfaces are 11. java.rmi.Remote 12. java.util.EventListener  13.What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? - It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more)   packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for  example. If I import java.util.* and javax.swing.* and then try to use “Timer”, I get an error while compiling (the class name is ambiguous between both packages). Let’s say what you really wanted was the  javax.swing.Timer  class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import   java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in. 14.What is the difference between logical data independence and physical data independence? Logical Data Independence - meaning immunity of external schemas to changeds in conceptual 1.

schema. Physical Data Independence - meaning immunity of conceptual schema to changes in the internal schema. 15.What is a user-defined exception? - Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. 16.Describe the visitor design pattern? - Represents an operation to be performed on the elements of  an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The root of a class hierarchy defines an abstract method to accept a visitor. Subclasses implement this method with visitor.visit(this). The Visitor interface has visit methods for all subclasses of the baseclass in the hierarchy.

Java database interview questions and answers How do you call a Stored Procedure from JDBC? - The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.

1. 2. 3. 4.

5.

6.

7.

8.

9.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); Is the JDBC-ODBC Bridge multi-threaded? - No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge,  but they won’t get the advantages of multi-threading. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?  No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge. What is cold backup, hot backup, warm backup recovery? - Cold backup (All these files must be  backed up at the same time, before the databaseis restarted). Hot backup (official name is ‘online  backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users. When we will Denormalize data? - Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data. What is the advantage of using PreparedStatement? - If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first. What is a “dirty read”? - Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is

always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency. 10.What is Metadata and why should I use it? - Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your  database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns 11.Different types of Transaction Isolation Levels? - The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of  inconsistencies can occur: o Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database. o  Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data. o Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent. TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR. TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-REPEATABLE READ AND PHANTOMS CAN OCCUR. TRANSACTION_REPEATABLE_READ : DIRTY READS , NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR. TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ AND PHANTOMS ARE PREVENTED.

is 2 phase commit? - A 2-phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources. 13.How do you handle your own transaction ? - Connection Object has a method called setAutocommit(Boolean istrue) - Default is true. Set the Parameter to false , and begin your transaction 14.What is the normal procedure followed by a java client to access the db.? - The database connection is created in 3 steps: 12.What

1. 2. 3.

Find a proper database URL Load the database driver  Ask the Java DriverManager class to open a connection to your database

In java code, the steps are realized in code as follows:

Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form  jdbc:someSubProtocol://myDatabaseServer/theDatabaseName 5. Class.forName(”my.database.driver”); 6. Connection conn = DriverManager.getConnection(”a.JDBC.URL”, “databaseLogin”,”databasePassword”); 2. What is a data source? - A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc. 3. What are collection pools? What are the advantages? - A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused 4. How do you get Column names only for a table (SQL Server)? Write the Query. 5. select name from syscolumns 6. where id=(select id from sysobjects where name='user_hdr') 7. order by colid --user_hdr is the table name 4.

Common JSP interview questions What are the implicit objects? - Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response,  pageContext, session, application, out, config, page, exception. 1.

2.

3.

4.

Is JSP technology extensible? - Yes. JSP technology is extensible through the development of  custom actions, or tags, which are encapsulated in tag libraries. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of  using it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive within your JSP  page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of  each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your  JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that   page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use . You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe How does JSP handle run-time exceptions? - You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request  processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: < %@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute. How do I prevent the output of my JSP or Servlet pages from being cached by the browser? You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by

the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. How do I use comments within a JSP page? - You can use “JSP-style” comments to selectively  block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example: 6. 5.

You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example: Of course, you can also use comments supported by your JSP scripting language within your  scriptlets. For example, assuming Java is the scripting language, you can have: has already been commited error. What does it mean? - This error show only when you try to redirect a page after you already have written something in your page. This happens  because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type=”text/html” or “text/xml” or “plain-text” or “image/jpg”, etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server  expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with some output (like testing your variables.) Before you indicate that the file is over  (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1 12.How do I use a scriptlet to initialize a newly instantiated bean? - A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to 11.Response

initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. 13. 14. 16. 17. 18.How can I enable session tracking for JSP pages if the browser has disabled cookies? - We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself  as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and e ncodeRedirectedURL() first determine whether  cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier    placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. 19. hello1.jsp 20. 21. 26. hello2.jsp 27. hello2.jsp 28. 29. How can I get to print the stacktrace for an exception occuring within my JSP page? 103. By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page: 104. 105. How do you pass an InitParameter to a JSP? - The JspPage interface defines the jspInit() 111. and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console. 112. 113. 124. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean: 125. 126. 136.

Java GUI designer interview questions What advantage do Java’s layout managers provide over traditional windowing systems? - Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. 1.

2.

3.

4.

What is the difference between the paint() and repaint() methods? - The paint() method supports  painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. How can the Checkbox class be used to create a radio button? - By associating Checkbox objects with a CheckboxGroup What is the difference between a Choice and a List? - A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. What interface is extended by AWT event listeners? - All AWT event listeners extend the  java.util.EventListener interface.

What is a layout manager? - A layout manager is an object that is used to organize components in a container  6. Which Component subclass is used for drawing and painting? - Canvas 7. What are the problems faced by Java programmers who dont use layout managers? - Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work  within the constraints imposed by each windowing system 8. What is the difference between a Scrollbar and a ScrollPane? (Swing) - A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. 5.

J2EE interview questions and answers What makes J2EE suitable for distributed multitiered Applications? - The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:

Client-tier components run on the client machine. Web-tier components run on the J2EE server. o Business-tier components run on the J2EE server. o o Enterprise information system (EIS)-tier software runs on the EIS server. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. What are the components of J2EE application? - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: o

2.

3.

Application clients and applets are client components. 2. Java Servlet and JavaServer Pages technology components are web components. 3. Enterprise JavaBeans components (enterprise beans) ar e business components. 4. Resource adapter components provided by EIS and tool vendors. What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage,  processes it (if necessary), and sends it back to the client program. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user  interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier. 1.

2.

3.

Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server  components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. 5. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either. 6. What can be considered as a web component? - J2EE Web components can be either servlets or  JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. 7. What is the container? - Containers are the interface between a component and the low-level  platform specific functionality that supports the component. Before a Web, enterprise bean, or  application client component can be executed, it must be assembled into a J2EE application and deployed into its container. 8. What are container services? - A container is a runtime support of a system-level entity. Containers   provide components with services such as lifecycle management, security, deployment, and threading. 9. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. 10.What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for  J2EE applications. Enterprise beans and their container run on the J2EE server. 11.What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 12.How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings. 13.What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. 14.What are types of J2EE clients? - Following are the types of J2EE clients: 4.

o o o o

Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology. Wireless clients, based on Mobile Information Device Profile (MIDP) technology.

What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. 5. What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. 6. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA. 7. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. 8. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can  be plugged into any J2EE product. Each type of database or EIS has a different resource adapter.  Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or  enterprise information system. 9. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 10.What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. 11.What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server  Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic  platform, suitable for development teams, independent developers, and everyone between. 12.How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or  4.

state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or  configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied  by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans. Basic Java servlet interview questions

What is the difference between CGI and Servlet? 1. What is meant by a servlet? 2. What are the types of servlets? What is the difference between 2 types of Servlets? 3. What is the type of method for sending request from HTTP server ? 4. What are the exceptions thrown by Servlets? Why? 5. What is the life cycle of a servlet? 6. What is meant by cookies? Why is Cookie used? 7. What is HTTP Session? 8. What is the difference between GET and POST methods? 9. How can you run a Servlet Program? 10. What is the middleware? What is the functionality of Webserver? 11. What webserver is used for running the Servlets? 12. How do you invoke a Servelt? What is the difference in between doPost and doGet methods? 13. What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also? 14. What are session variable in Servlets? 15. What is meant by Session? Tell me something about HTTPSession Class? 16. What is Session Tracking? 17. Difference between doGet and doPost? 18. What are the methods in HttpServlet? 19. What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet? Servlet interview questions What is a servlet? Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For  example, a servlet might be responsible for taking data in an HTML order-entry form and applying the  business logic used to update a company’s order database. Servlets are to servers what applets are to  browsers. Unlike applets, however, servlets have no graphical user interface. 1.

2.

Whats the advantages using servlets over using CGI? Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension. What are the general advantages and selling points of Servlets? A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can

3. 4.

5.

6.

7.

8.

9.

 be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. Which package provides interfaces and classes for writing servlets? javax What’s the Servlet Interface? The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet. When a servlet accepts a call from a client, it receives two objects. What are they? ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package. What information does ServletRequest allow access to? Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application  protocols such as the HTTP POST and GET methods. What type of constraints can ServletResponse interface set on the client? It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data. Explain servlet lifecycle? Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down. How does HTTP Servlet handle client requests? An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. JDBC interview questions and answers

What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection. 1.

How can you load the drivers? Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for  example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); Your driver documentation will give you the class name to use. For instance, if the class name is  jdbc.DriverXYZ, you would load the driver with the following line of code: Class.forName(”jdbc.DriverXYZ”);

2.

3.

What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

String url = “jdbc:odbc:Fred”; Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?); 4.

How can you create JDBC statements and what are they? A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

Statement stmt = con.createStatement(); 5.

How can you retrieve data from the ResultSet? JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”); String s = rs.getString(”COF_NAME”); The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs. What are the different types of Statements? Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall) 7. How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not  just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first. 8. PreparedStatement updateSales = 9. con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); 10.What does setAutoCommit do? When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode: 6.

con.setAutoCommit(false); Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true); 11.How

do you call a stored procedure from JDBC? The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure. 12. CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); 13. ResultSet rs = cs.executeQuery(); 14.How do I retrieve warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object: 15. SQLWarning warning = stmt.getWarnings(); 16. if (warning != null) 17. { 18. System.out.println("n---Warning---n"); 19. while (warning != null) 20. { 21. System.out.println("Message: " + warning.getMessage()); 22. System.out.println("SQLState: " + warning.getSQLState()); 23. System.out.print("Vendor error code: "); 24. System.out.println(warning.getErrorCode()); 25. System.out.println(""); 26. warning = warning.getNextWarning(); 27. }

28. } 29.How can you move the cursor in scrollable result sets? One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check  the position of the cursor. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for  specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both  parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY. 30.What’s

the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE? You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened: 31. Statement stmt = 32. con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); 33. ResultSet srs = 34. stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); 35. srs.afterLast(); 36. while (srs.previous()) 37. { 38. String name = srs.getString("COF_NAME"); 39. float price = srs.getFloat("PRICE"); 40. System.out.println(name + " " + price); 41. } 42.How to Make Updates to Updatable Result Sets? Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the crea teStatement method. 43. Connection con =

44. DriverManager.getConnection("jdbc:mySubprotocol:mySubName"); 45. Statement stmt = 46. con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); 47. ResultSet uprs = 48. stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Oracle interview questions

 No answers, but these are useful questions for conducting Oracle interview. The readers are welcome to contribute their answers. 1. What is an oracle instance? 2. What is a view? 3. What is referential integrity? 4. Name the data dictionary that stores user-defined constraints? 5. What is a collection of privileges? 6. What is a snapshot? 7. What is a synonym? 8. What is a cursor? 9. What is a sequence? 10. What is a trigger? 11. What is an exception? 12. What is a partition of table? 13. What are pseudo-columns in SQL? Provide examples. 14. What are the Data Control statements? 15. What is a schema? 16. What is a type? 17. What is a data model? 18. What is a relation? 19. Advantages of redo log files? 20. What is an Archiver? 21. What is a database buffer cache? 22. What are the background processes in Oracle? 23. %type and %rowtype are attributes for…? 24. What are the steps in a two-phase commit? 25. What is a union, intersect, minus? 26. What is a join, explain the types of joins? 27. What is a co-related sub-query? 28. ODBC stands for…? 29. Data-type used to work with integers is? 30. Describe data models? 31. Describe the Normalization principles? 32. What are the types of Normalization? 33. What is de-normalization?

JavaScript interview questions and answers What’s relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for  JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined. 2. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); 3. What does isNaN function do? - Return true if the argument is not a number. 4. What is negative infinity? - It’s a number in JavaScript, derived by dividing negative number by zero. 5. What boolean operators does JavaScript support? - &&, || and ! 6. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124. 7. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result. 8. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach. 9. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {}; 10.How do you assign object properties? - obj["age"] = 17 or obj.age = 17. 11.What’s a way to append a value to an array? - arr[arr.length] = value; 12.What is this keyword? - It refers to the current object. 1.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF