Core Java & Servlet & JSP &JDBC
Core Java & Servlet & JSP &JDBC
Abstract classes may contain abstract methods. A method declared abstract is not
actually implemented in the current class. It exists only to be overridden in
subclasses. It has no body. For example,
1. What is the Collections API? - The Collections API is a set of classes and
interfaces that support operations on collections of objects
2. What is the List interface? - The List interface provides support for ordered
collections of objects.
3. What is the Vector class? - The Vector class provides the capability to
implement a growable array of objects
4. What is an Iterator interface? - The Iterator interface is used to step through the
elements of a Collection
5. Which java.util classes and interfaces support event handling? - The
EventObject class and the EventListener interface support event processing
6. What is the GregorianCalendar class? - The GregorianCalendar provides
support for traditional Western calendars
7. What is the Locale class? - The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region
8. What is the SimpleTimeZone class? - The SimpleTimeZone class provides
support for a Gregorian calendar
9. What is the Map interface? - The Map interface replaces the JDK 1.1 Dictionary
class and is used associate keys with values
10. What is the highest-level event class of the event-delegation model? - The
java.util.EventObject class is the highest-level class in the event-delegation class
hierarchy
11. What is the Collection interface? - The Collection interface provides support for
the implementation of a mathematical bag - an unordered collection of objects
that may contain duplicates
12. What is the Set interface? - The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements
13. What is the purpose of the enableEvents() method? - The enableEvents()
method is used to enable an event for a particular object. Normally, an event is
enabled when a listener is added to an object for a particular event. The
enableEvents() method is used by objects that handle events by overriding their
event-dispatch methods.
14. What is the ResourceBundle class? - The ResourceBundle class is used to store
locale-specific resources that can be loaded by a program to tailor the program’s
appearance to the particular locale in which it is being run.
15. What is the difference between yielding and sleeping? - When a task invokes
its yield() method, it returns to the ready state. When a task invokes its sleep()
method, it returns to the waiting state.
16. When a thread blocks on I/O, what state does it enter? - A thread enters the
waiting state when it blocks on I/O.
17. When a thread is created and started, what is its initial state? - A thread is in
the ready state after it has been created and started.
18. What invokes a thread’s run() method? - After a thread is started, via its start()
method or that of the Thread class, the JVM invokes the thread’s run() method
when the thread is initially executed.
19. What method is invoked to cause an object to begin executing as a separate
thread? - The start() method of the Thread class is invoked to cause an object to
begin executing as a separate thread.
20. What is the purpose of the wait(), notify(), and notifyAll() methods? - The
wait(),notify(), and notifyAll() methods are used to provide an efficient way for
threads to wait for a shared resource. When a thread executes an object’s wait()
method, it enters the waiting state. It only enters the ready state after another
thread invokes the object’s notify() or notifyAll() methods.
21. What are the high-level thread states? - The high-level thread states are ready,
running, waiting, and dead
22. What happens when a thread cannot acquire a lock on an object? - If a thread
attempts to execute a synchronized method or synchronized statement and is
unable to acquire an object’s lock, it enters the waiting state until the lock
becomes available.
23. How does multithreading take place on a computer with a single CPU? - The
operating system’s task scheduler allocates execution time to multiple tasks. By
quickly switching between executing tasks, it creates the impression that tasks
execute sequentially.
24. What happens when you invoke a thread’s interrupt method while it is
sleeping or waiting? - When a task’s interrupt() method is executed, the task
enters the ready state. The next time the task enters the running state, an
InterruptedException is thrown.
25. What state is a thread in when it is executing? - An executing thread is in the
running state
26. What are three ways in which a thread can enter the waiting state? - A thread
can enter the waiting state by invoking its sleep() method, by blocking on I/O, by
unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s
wait() method. It can also enter the waiting state by invoking its (deprecated)
suspend() method.
27. What method must be implemented by all threads? - All tasks must implement
the run() method, whether they are a subclass of Thread or implement the
Runnable interface.
28. What are the two basic ways in which classes that can be run as threads may
be defined? - A thread class may be declared as a subclass of Thread, or it may
implement the Runnable interface.
29. How can you store international / Unicode characters into a cookie? - One
way is, before storing the cookie URLEncode it. URLEnocder.encoder(str); And
use URLDecoder.decode(str) when you get the stored cookie.
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}
66. What is the Locale class? The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region.
67. 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.
68. What is a class? A class is a blueprint, or prototype, that defines the variables
and the methods common to all objects of a certain kind.
69. What is a object? An object is a software bundle of variables and related
methods.An instance of a class depicting the state and behavior at that particular
time in real world.
70. What is a method? Encapsulation of a functionality which can be called to
perform specific tasks.
71. What is encapsulation? Explain with an example. Encapsulation is the term
given to the process of hiding the implementation details of the object. Once an
object is encapsulated, its implementation details are not immediately accessible
any more. Instead they are packaged and are only indirectly accessible via the
interface of the object
72. What is inheritance? Explain with an example. Inheritance in object oriented
programming means that a class of objects can inherit properties and methods
from another class of objects.
73. What is polymorphism? Explain with an example. In object-oriented
programming, polymorphism refers to a programming language’s ability to
process objects differently depending on their data type or class. More
specifically, it is the ability to redefine methods for derived classes. For example,
given a base class shape, polymorphism enables the programmer to define
different area methods for any number of derived classes, such as circles,
rectangles and triangles. No matter what shape an object is, applying the area
method to it will return the correct results. Polymorphism is considered to be a
requirement of any true object-oriented programming language
74. Is multiple inheritance allowed in Java? No, multiple inheritance is not allowed
in Java.
75. What is interpreter and compiler? Java interpreter converts the high level
language code into a intermediate form in Java called as bytecode, and then
executes it, where as a compiler converts the high level language code to machine
language making it very hardware specific
76. What is JVM? The Java interpreter along with the runtime environment required
to run the Java application in called as Java virtual machine(JVM)
77. What are the different types of modifiers? There are access modifiers and there
are other identifiers. Access modifiers are public, protected and private. Other are
final and static.
78. What are the access modifiers in Java? There are 3 access modifiers. Public,
protected and private, and the default one if no identifier is specified is called
friendly, but programmer cannot specify the friendly identifier explicitly.
79. What is a wrapper class? They are classes that wrap a primitive data type so it
can be used as a object
80. What is a static variable and static method? What’s the difference between
two? The modifier static can be used with a variable and method. When declared
as static variable, there is only one variable no matter how instances are created,
this variable is initialized when the class is loaded. Static method do not need a
class to be instantiated to be called, also a non static method cannot be called from
static method.
81. What is garbage collection? Garbage Collection is a thread that runs to reclaim
the memory by destroying the objects that cannot be referenced anymore.
82. What is abstract class? Abstract class is a class that needs to be extended and its
methods implemented, aclass has to be declared abstract if it has one or more
abstract methods.
83. What is meant by final class, methods and variables? This modifier can be
applied to class method and variable. When declared as final class the class
cannot be extended. When declared as final variable, its value cannot be changed
if is primitive value, if it is a reference to the object it will always refer to the
same object, internal attributes of the object can be changed.
84. What is interface? Interface is a contact that can be implemented by a class, it
has method that need implementation.
85. What is method overloading? Overloading is declaring multiple method with
the same name, but with different argument list.
86. What is method overriding? Overriding has same method name, identical
arguments used in subclass.
87. What is singleton class? Singleton class means that any given time only one
instance of the class is present, in one JVM.
88. What is the difference between an array and a vector? Number of elements in
an array are fixed at the construction time, whereas the number of elements in
vector can grow dynamically.
89. What is a constructor? In Java, the class designer can guarantee initialization of
every object by providing a special method called a constructor. If a class has a
constructor, Java automatically calls that constructor when an object is created,
before users can even get their hands on it. So initialization is guaranteed.
90. What is casting? Conversion of one type of data to another when appropriate.
Casting makes explicitly converting of data.
91. What is the difference between final, finally and finalize? The modifier final is
used on class variable and methods to specify certain behaviour explained above.
And finally is used as one of the loop in the try catch blocks, It is used to hold
code that needs to be executed whether or not the exception occurs in the try catch
block. Java provides a method called finalize( ) that can be defined in the class.
When the garbage collector is ready to release the storage ed for your object, it
will first call finalize( ), and only on the next garbage-collection pass will it
reclaim the objects memory. So finalize( ), gives you the ability to perform some
important cleanup at the time of garbage collection.
92. What is are packages? A package is a collection of related classes and interfaces
providing access protection and namespace management.
93. What is a super class and how can you call a super class? When a class is
extended that is derived from another class there is a relationship is created, the
parent class is referred to as the super class by the derived class that is the child.
The derived class can make a call to the super class using the keyword super. If
used in the constructor of the derived class it has to be the first statement.
94. What is meant by a Thread? Thread is defined as an instantiated parallel
process of a given program.
95. What is multi-threading? Multi-threading as the name suggest is the scenario
where more than one threads are running.
96. What are two ways of creating a thread? Which is the best way and why?
Two ways of creating threads are, one can extend from the Java.lang.Thread and
can implement the rum method or the run method of a different class can be
called which implements the interface Runnable, and the then implement the run()
method. The latter one is mostly used as first due to Java rule of only one class
inheritance, with implementing the Runnable interface that problem is sorted out.
97. What is deadlock? Deadlock is a situation when two threads are waiting on each
other to release a resource. Each thread waiting for a resource which is held by the
other waiting thread. In Java, this resource is usually the object lock obtained by
the synchronized keyword.
98. What are the three types of priority? MAX_PRIORITY which is 10,
MIN_PRIORITY which is 1, NORM_PRIORITY which is 5.
99. What is the use of synchronizations? Every object has a lock, when a
synchronized keyword is used on a piece of code the, lock must be obtained by
the thread first to execute that code, other threads will not be allowed to execute
that piece of code till this lock is released.
The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused. A Java object is
subject to garbage collection when it becomes unreachable to the program in which it is
used.
>
Design patterns helps software developers to reuse successful designs and architectures.
It helps them to choose design alternatives that make a system reusuable and avoid
alternatives that compromise reusability through proven techniques as design patterns.
Ans: Object oriented programming languages directly represent the real life objects. The
features of OOPL as inhreitance, polymorphism, encapsulation makes it powerful.
Ans: Polymorhisum: is a feature of OOPl that at run time depending upon the type of
object the appropriate method is called.
Inheritance: is a feature of OOPL that represents the "is a" relationship between different
objects(classes). Say in real life a manager is a employee. So in OOPL manger class is
inherited from the employee class.
Encapsulation: is a feature of OOPL that is used to hide the information.
Ans: By using the static method there is no need creating an object of that class to use
that method. We can directly call that method on that class. For example, say class A has
static function f(), then we can call f() function as A.f(). There is no need of creating an
object of class A.
Ans: virtual methods are used to use the polymorhism feature in C++. Say class A is
inherited from class B. If we declare say fuction f() as virtual in class B and override the
same function in class A then at runtime appropriate method of the class will be called
depending upon the type of the object.
Q5: Given two tables Student(SID, Name, Course) and Level(SID, level) write the
SQL statement to get the name and SID of the student who are taking course = 3
and at freshman level.
Ans: DeadLock.
Q1: Write the Java code to declare any constant (say gravitational constant) and to
get its value
Ans: Multiple inheritance is a feature in C++ by which one class can be of different
types. Say class teachingAssistant is inherited from two classes say teacher and Student.
Q3: Can you write Java code for declaration of multiple inheritance in Java ?
Q:In Java, what is the difference between an Interface and an Abstract class?
A: An Abstract class declares have at least one instance method that is declared abstract
which will be implemented by the subclasses. An abstract class can have instance
methods that implement a default behavior. An Interface can only declare constants and
instance methods, but cannot implement default behavior.
Q: Can you have virtual functions in Java? Yes or No. If yes, then what are virtual
functions?
A: Yes, Java class functions are virtual by default. Virtual functions are functions of
subclasses that can be invoked from a reference to their superclass. In other words, the
functions of the actual object are called when a function is invoked on the reference to
that object.
A:
Link* reverse_list(Link* p)
{
if (p == NULL)
return NULL;
Link* h = p;
p = p->next;
h->next = NULL;
while (p != null)
{
Link* t = p->next;
p->next = h;
h = p;
p = t;
}
return h;
}
A:Virtual destructors are neccessary to reclaim memory that were allocated for objects in
the class hierarchy. If a pointer to a base class object is deleted, then the compiler
guarantees the various subclass destructors are called in reverse order of the object
construction chain.
Q:What are mutex and semaphore? What is the difference between them?
A:A mutex is a synchronization object that allows only one process or thread to access a
critical code block. A semaphore on the other hand allows one or more processes or
threads to access a critial code block. A semaphore is a multiple mutex
Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an
integrated set of classes to manage user interface components.
4. why a java program can not directly communicate with an ODBC driver?
Answer: Since ODBC API is written in C language and makes use of pointers which Java
can not support.
5. Are servlets platform independent? If so Why? Also what is the most common
application of servlets?
Answer: Yes, Because they are written in Java. The most common application of servlet
is to access database and dynamically construct HTTP response
Servlet
1. What is the servlet?
2. What are the JSP atrributes?
3. What is the need of super.init(config) in servlets?
4. How to know whether we have to use jsp or servlet in our project?
5. Can we call destroy() method on servlets from service method?
6. What is the Servlet Interface?
7. What is the difference between GenericServlet and HttpServlet?
8. How we can check in particular page the session will be alive or not?
9. What is the importance of deployment descriptor in servlet?
10. When we increase the buffer size in our project using page directive attribute
‘buffer’ what changes we observe?
11. What is the difference between ServetConfig and ServletContext..?
12. When a servlet accepts a call from a client, it receives two objects. What are they?
13. What are the differences between GET and POST service methods?
14. In which conditions we have to use the ServletContext?
15. What methods will be called in which order?((i.e)service(),doget(),dopost())
16. Servlet is Java class. Then why there is no constructor in Servlet? Can we write
the constructor in Servlet
17. What is the use of ServletConfig and ServletContext..?
18. What information that the ServletRequest interface allows the servlet access to?
19. What is the difference between ServletContext and ServletConfig?
20. When do you have action=get?
21. What is a Singleton class. How do you write it?
22. What is difference between sendRedirect() and forward()..? Which one is faster
then other and which works on server?
23. What information that the ServletResponse interface gives the servlet methods for
replying to the client?
24. Can I invoke a JSP error page from a servlet?
25. Can a init(ServletConfig config) method be overrided in servlets?
26. How many ServletConfig and servlet context objects are present in one
application?
27. Do we have a constructor in servlet? can we explictly provide a constructor in
servlet programme as in java program?
28. What are the uses of Servlets?
29. Can I just abort processing a JSP?
30. Is servlet is used to create a dynamic webpage or Static webpage or both?
31. If you want a servlet to take the same action for both GET and POST request,
what should you do?
32. What is the difference between JSP and SERVLETS?
33. What are the advantages using servlets than using CGI?
34. What is a better approach for enabling thread-safe servlets and JSPs?
SingleThreadModel Interface or synchronization?
35. We have two applications in that we have two servlets each.How they(servlets)
communicate with each other?
36. How the server will know (i.e) when it can invoke init, service,destroy methods of
servlet life cycle?
37. How to communicate between two servlets?
38. What is the difference between servlets and applets?
39. How will u pass the argument from one servlet to another servlet?
40. What method used to add a jsp to the servlet?
41. How HTTP Servlet handles client requests?
42. How to get one Servlet’s Context Information in another Servlet?
43. Difference between single thread and multi thread model servlet
44. What is the super class of All servlets?
45. How are Servlet Applet communication achieved?
46. What is servlet context and what it takes actually as parameters?
47. What is the servlet life cycle?
48. Types of Servlets?
49. Why is that we deploy servlets in a webserver.What exactly is a webserver?
50. Which code line must be set before any of the lines that use the PrintWriter?
51. What is the difference between CGI and Servlet?
52. What is meant by a servlet?
53. What are the types of servlets? What is the difference between 2 types of
Servlets?
54. What is the type of method for sending request from HTTP server ?
55. What are the exceptions thrown by Servlets? Why?
56. What is the life cycle of a servlet?
57. What is meant by cookies? Why is Cookie used?
58. What is HTTP Session?
59. What is the difference between GET and POST methods?
60. How can you run a Servlet Program?
61. What is the middleware? What is the functionality of Webserver?
62. What webserver is used for running the Servlets?
63. How do you invoke a Servelt? What is the difference in between doPost and
doGet methods?
64. What is the difference in between the HTTPServlet and Generic Servlet? Explain
their methods? Tell me their parameter names also?
65. What are session variable in Servlets?
66. What is meant by Session? Tell me something about HTTPSession Class?
67. What is Session Tracking?
68. Difference between doGet and doPost?
69. What are the methods in HttpServlet?
70. What are the types of SessionTracking? Why do you use Session Tracking in
HttpServlet?
71. 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.
72. 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.
73. 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 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.
74. Which package provides interfaces and classes for writing servlets? javax
75. 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.
76. 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.
77. 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.
78. 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.
79. 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.
80. 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.
81. Can we use the constructor, instead of init(), to initialize servlet? - Yes , of
course you can use the constructor instead of init(). There’s nothing to stop you.
But you shouldn’t. The original reason for init() was that ancient versions of Java
couldn’t dynamically invoke constructors with arguments, so there was no way to
give the constructur a ServletConfig. That no longer applies, but servlet
containers still will only call your no-arg constructor. So you won’t have access to
a ServletConfig or ServletContext.
82. How can a servlet refresh automatically if some new data has entered the
database? - You can use a client-side Refresh or Server Push.
83. The code in a finally clause will never fail to execute, right? - Using
System.exit(1); in try block will not allow finally code to execute.
84. How many messaging models do JMS provide for and what are they? - JMS
provide for two messaging models, publish-and-subscribe and point-to-point
queuing.
85. What information is needed to create a TCP Socket? - The Local System?s IP
Address and Port Number. And the Remote System’s IPAddress and Port
Number.
86. What Class.forName will 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.
87. How to 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
88. SQLWarning warning = stmt.getWarnings();
89. if (warning != null)
90. {
91. while (warning != null)
92. {
93. System.out.println("Message: " +
warning.getMessage());
94. System.out.println("SQLState: " +
warning.getSQLState());
95. System.out.print("Vendor error code: ");
96.
System.out.println(warning.getErrorCode());
97. warning = warning.getNextWarning();
98. }
99. }
100. How many JSP scripting elements are there and what are they? -
There are three scripting language elements: declarations, scriptlets, expressions.
101. In the Servlet 2.4 specification SingleThreadModel has been
deprecated, why? - Because it is not practical to have such model. Whether you
set isThreadSafe to true or false, you should take care of concurrent client
requests to the JSP page by synchronizing access to any shared objects defined at
the page level.
102. What are stored procedures? How is it useful? - A stored procedure is a
set of statements/commands which reside in the database. The stored procedure is
pre-compiled and saves the database the effort of parsing and compiling sql
statements everytime a query is run. Each database has its own stored procedure
language, usually a variant of C with a SQL preproceesor. Newer versions of db’s
support writing stored procedures in Java and Perl too. Before the advent of 3-
tier/n-tier architecture it was pretty common for stored procs to implement the
business logic( A lot of systems still do it). The biggest advantage is of course
speed. Also certain kind of data manipulations are not achieved in SQL. Stored
procs provide a mechanism to do these manipulations. Stored procs are also
useful when you want to do Batch updates/exports/houseKeeping kind of stuff on
the db. The overhead of a JDBC Connection may be significant in these cases.
103. How do I include static files within a JSP page? - Static resources
should always be included using the JSP include directive. This way, the inclusion
is performed just once during the translation phase. Do note that you should
always supply a relative URL for the file attribute. Although you can also include
static resources using the action, this is not advisable as the inclusion is then
performed for each and every request.
104. Why does JComponent have add() and remove() methods but
Component does not? - because JComponent is a subclass of Container, and can
contain other components and jcomponents.
105. How can I implement a thread-safe JSP page? - You can make your
JSPs thread-safe by having them implement the SingleThreadModel interface.
This is done by adding the directive <%@ page isThreadSafe="false" % > within
your JSP page.
JSP
o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
2. What’s the difference between forward and sendRedirect? When you invoke a
forward request, the request is sent to another resource on the server, without the
client being informed that a different resource is going to process the request. This
process occurs completely with in the web container And then returns to the
calling method. When a sendRedirect method is invoked, it causes the web
container to return to the browser indicating that a new URL should be requested.
Because the browser issues a completely new request any object that are stored as
request attributes before the redirect occurs will be lost. This extra round trip a
redirect is slower than forward.
3. What are the different scope values for the <jsp:useBean>? The different
scope values for <jsp:useBean> are:
o page
o request
o session
o application
4. Why are JSP pages the preferred API for creating a web-based client
program? Because no plug-ins or security policy files are needed on the client
systems(applet does). Also, JSP pages enable cleaner and more module
application design because they provide a way to separate applications
programming from web page design. This means personnel involved in web page
design do not need to understand Java programming language syntax to do their
jobs.
5. Is JSP technology extensible? Yes, it is. JSP technology is extensible through
the development of custom actions, or tags, which are encapsulated in tag
libraries.
6. What is difference between custom JSP tags and beans? Custom JSP tag is a
tag you defined. You define how a tag, its attributes and its body are interpreted,
and then group your tags into collections called tag libraries that can be used in
any number of JSP files. Custom tags and beans accomplish the same goals —
encapsulating complex behavior into simple and accessible forms. There are
several differences:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with
custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o Custom tags usually define relatively self-contained behavior, whereas
beans are often defined in one servlet and used in a different servlet or JSP
page.
o Custom tags are available only in JSP 1.1 and later, but beans can be used
in all JSP 1.x versions.
7. What is the query used to display all tables names in SQL Server (Query
analyzer)?
8. select * from information_schema.tables
9. How many types of JDBC Drivers are present and what are they?- There are
4 types of JDBC Drivers
o JDBC-ODBC Bridge Driver
o Native API Partly Java Driver
o Network protocol Driver
o JDBC Net pure Java Driver
10. Can we implement an interface in a JSP?- No
11. What is the difference between ServletContext and PageContext?-
ServletContext: Gives the information about the container. PageContext: Gives
the information about the Request
12. What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()?- request.getRequestDispatcher(path): In order
to create it we need to give the relative path of the resource,
context.getRequestDispatcher(path): In order to create it we need to give the
absolute path of the resource.
13. How to pass information from JSP to included JSP?- Using <
%jsp:param> tag.
14. What is the difference between directive include and jsp include?- <
%@ include>: Used to include static resources during translation time. JSP
include: Used to include dynamic content or static content during runtime.
15. What is the difference between RequestDispatcher and
sendRedirect?- RequestDispatcher: server-side redirect with request and
response objects. sendRedirect : Client-side redirect with new request and
response objects.
16. How does JSP handle runtime exceptions?- Using errorPage attribute of
page directive and also we need to specify isErrorPage=true if the current page is
intended to URL redirecting of a JSP.
17. How do you delete a Cookie within a JSP?
18. Cookie mycook = new Cookie("name","value");
19. response.addCookie(mycook);
20. Cookie killmycook = new Cookie("mycook","value");
21. killmycook.setMaxAge(0);
22. killmycook.setPath("/");
23. killmycook.addCookie(killmycook);
24. How do I mix JSP and SSI #include?- If you’re just including raw
HTML, use the #include directive as usual inside your .jsp file.
25. <!--#include file="data.inc"-->
But it’s a little trickier if you want the server to evaluate any JSP code that’s
inside the included file. If your data.inc file contains jsp code you will have to use
26. I made my class Cloneable but I still get Can’t access protected method
clone. Why?- Some of the Java books imply that all you have to do in order to
have your class support clone() is implement the Cloneable interface. Not so.
Perhaps that was the intent at some point, but that’s not the way it works
currently. As it stands, you have to implement your own public clone() method,
even if it doesn’t do anything special and just calls super.clone().
27. Why is XML such an important development?- It removes two
constraints which were holding back Web developments: dependence on a single,
inflexible document type (HTML) which was being much abused for tasks it was
never designed for; the complexity of full SGML, whose syntax allows many
powerful but hard-to-program options. XML allows the flexible development of
user-defined document types. It provides a robust, non-proprietary, persistent, and
verifiable file format for the storage and transmission of text and data both on and
off the Web; and it removes the more complex options of SGML, making it easier
to program for.
28. What is the fastest type of JDBC driver?- JDBC driver performance
will depend on a number of issues:
o the quality of the driver code,
o the size of the driver code,
o the database server and its load,
o network topology,
o the number of times your request is translated to a different API.
In general, all things being equal, you can assume that the more your request and
response change hands, the slower it will be. This means that Type 1 and Type 3
drivers will be slower than Type 2 drivers (the database calls are make at least
three translations versus two), and Type 4 drivers are the fastest (only one
translation).
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works
in Servlet 2.3+)
32. How can I send user authentication information while
makingURLConnection?- You’ll want to use
HttpURLConnection.setRequestProperty and set all the appropriate headers to
HTTP authorization.
What are the most common techniques for reusing functionality in object-oriented
systems?
A: The two most common techniques for reusing functionality in object-oriented systems
are class inheritance and object composition.
Class inheritance lets you define the implementation of one class in terms of another’s.
Reuse by subclassing is often referred to as white-box reuse.
Object composition is an alternative to class inheritance. Here, new functionality is
obtained by assembling or composing objects to get more complex functionality. This is
known as black-box reuse.
Q: Why would you want to have more than one catch block associated with a single
try block in Java?
A: Since there are many things can go wrong to a single executed statement, we should
have more than one catch(s) to catch any errors that might occur.
Q: What does the JSP engine do when presented with a JavaServer Page to process?
A: The JSP engine builds a servlet. The HTML portions of the JavaServer Page become
Strings transmitted to print methods of a PrintWriter object. The JSP tag portions result in
calls to methods of the appropriate JavaBean class whose output is translated into more
calls to a println method to place the result in the HTML document.
1. 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.
2. Is JSP technology extensible? - Yes. JSP technology is extensible through the
development of custom actions, or tags, which are encapsulated in tag libraries.
3. 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 <%@ page isThreadSafe="false" %> 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 <%! DECLARE %>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
4. 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: <%@ page
errorPage="error.jsp" %>
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.
5. 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.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
6. 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:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>
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:
<%
//some comment
/**
yet another comment
**/
%>
12. Response 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 <HTML
Tag><Some Headers><Body>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
13. 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 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.
14. <jsp:useBean id="foo" class="com.Bar.Foo" >
15. <jsp:setProperty name="foo" property="today"
16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >
17. <%-- scriptlets calling bean setter methods go here --%>
18. </jsp:useBean >
19. 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 encodeRedirectedURL() 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.
20. hello1.jsp
21. <%@ page session="true" %>
22. <%
23. Integer num = new Integer(100);
24. session.putValue("num",num);
25. String url =response.encodeURL("hello2.jsp");
26. %>
27. <a href='<%=url%>'>hello2.jsp</a>
28. hello2.jsp
29. <%@ page session="true" %>
30. <%
31. Integer i= (Integer )session.getValue("num");
32. out.println("Num value in session is "+i.intValue());
33. How can I declare methods within my JSP page? - You can declare methods
for use within your JSP page as declarations. The methods can then be invoked
within any other methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit objects like
request, response, session and so forth from within JSP methods. However, you
should be able to pass any of the implicit JSP variables as parameters to the
methods you declare. For example:
34. <%!
35. public String whereFrom(HttpServletRequest req) {
36. HttpSession ses = req.getSession();
37. ...
38. return req.getRemoteHost();
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from
");
43. %>
44. <%= whereFrom(request) %>
45. Another Example
46. file1.jsp:
47. <%@page contentType="text/html"%>
48. <%!
49. public void test(JspWriter writer) throws IOException{
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
54. <%@include file="file1.jsp"%>
55. <html>
56. <body>
57. <%test(out);% >
58. </body>
59. </html>
60. Is there a way I can set the inactivity lease period on a per-session basis? -
Typically, a default inactivity lease period for all sessions is set within your JSP
engine admin screen or associated properties file. However, if your JSP engine
supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-
session basis. This is done by invoking the HttpSession.setMaxInactiveInterval()
method, right after the session has been created. For example:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>
would reset the inactivity period for this session to 5 minutes. The inactivity
interval is set in seconds.
64. How can I set a cookie and delete a cookie from within a JSP page? - A
cookie, mycookie, can be deleted using the following scriptlet:
65. <%
66. //creating a cookie
67. Cookie mycookie = new Cookie("aName","aValue");
68. response.addCookie(mycookie);
69. //delete a cookie
70. Cookie killMyCookie = new Cookie("mycookie", null);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
75. How does a servlet communicate with a JSP page? - The following code
snippet shows how a servlet instantiates a bean and initializes it with FORM data
posted by a browser. The bean is then placed into the request, and the call is then
forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for
downstream processing.
76. public void doPost (HttpServletRequest request,
HttpServletResponse response) {
77. try {
78. govi.FormBean f = new govi.FormBean();
79. String id = request.getParameter("id");
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
83. //use the id to compute
84. //additional bean properties like info
85. //maybe perform a db query, etc.
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89.
getServletConfig().getServletContext().getRequestDispatcher
90. ("/jsp/Bean1.jsp").forward(request,
response);
91. } catch (Exception ex) {
92. . . .
93. }
94. }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the
default request scope via the useBean action.
If any of the above conditions are not satisfied, the JSP engine may throw a
translation error.
Once the superclass has been developed, you can have your JSP extend it as
follows:
JDBC
1. 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.
2. CallableStatement cs =
3. con.prepareCall("{call SHOW_SUPPLIERS}");
4. ResultSet rs = cs.executeQuery();
5. 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.
6. 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.
7. 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.
8. 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.
9. 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.
10. 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.
11. 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
12. 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.
13. What 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.
14. 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
15. What is the normal procedure followed by a java client to access the db.? -
The database connection is created in 3 steps:
4. 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
8. What are the steps involved in establishing a JDBC connection? This action
involves two steps: loading the JDBC driver and making the connection.
9. 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”);
12. 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
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.
con.setAutoCommit(false);
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);
19. 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.
20. CallableStatement cs = con.prepareCall("{call
SHOW_SUPPLIERS}");
21. ResultSet rs = cs.executeQuery();
22. 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:
23. SQLWarning warning = stmt.getWarnings();
24. if (warning != null)
25. {
26. System.out.println("n---Warning---n");
27. while (warning != null)
28. {
29. System.out.println("Message: " +
warning.getMessage());
30. System.out.println("SQLState: " +
warning.getSQLState());
31. System.out.print("Vendor error code: ");
32. System.out.println(warning.getErrorCode());
33. System.out.println("");
34. warning = warning.getNextWarning();
35. }
36. }
37. 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.
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.
1. IN
2. OUT
3. RETURN
4. IN OUT
21. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;
The trigger code should only execute when the column, COST_PER_TICKET, is
greater than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)
27. What is the maximum number of handlers processed before the PL/SQL
block is exited when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None
28. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row
2. Statement only
3. Row only
4. Oracle Forms trigger
29. Read the following code:
30. CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
31. RETURN number IS
32.
33. v_yearly_budget NUMBER;
34.
35. BEGIN
36. SELECT yearly_budget
37. INTO v_yearly_budget
38. FROM studio
39. WHERE id = v_studio_id;
40.
41. RETURN v_yearly_budget;
42. END;
1. An user defined exception must be declared and associated with the error
code and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code
directly.
3. Handle the error in the EXCEPTION section by referencing the
UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately
after the UPDATE statement.
51. Read the following code:
52. CREATE OR REPLACE PROCEDURE calculate_budget IS
53. v_budget studio.yearly_budget%TYPE;
54. BEGIN
55. v_budget := get_budget(11);
56. IF v_budget < 30000
57. THEN
58. set_budget(11,30000000);
59. END IF;
60. END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table.
It should fire only once for the entire DELETE statement. What additional
information must you add?
PLAY_TABLE
————————————-
“Midsummer Night’s Dream”, SHAKESPEARE
“Waiting For Godot”, BECKETT
“The Glass Menagerie”, WILLIAMS
1.
60494
2.
LOA
3.
Terminated
4.
ACTIVE
103. SELECT (TO_CHAR(NVL(SQRT(59483), “INVALID”)) FROM
DUAL is a valid SQL statement.
1. TRUE
2. FALSE
104. The appropriate table to use when performing arithmetic calculations
on values defined within the SELECT statement (not pulled from a table
column) is
1. EMP
2. The table containing the column values
3. DUAL
4. An Oracle-defined table
105. Which of the following is not a group function?
1. avg( )
2. sqrt( )
3. sum( )
4. max( )
106. Once defined, how long will a variable remain so in SQL*Plus?
1. Until the database is shut down
2. Until the instance is shut down
3. Until the statement completes
4. Until the session completes
107. The default character for specifying runtime variables in SELECT
statements is
1. Ampersand
2. Ellipses
3. Quotation marks
4. Asterisk
108. A user is setting up a join operation between tables EMP and DEPT.
There are some employees in the EMP table that the user wants returned by
the query, but the employees are not assigned to departments yet. Which
SELECT statement is most appropriate for this user?
1. select e.empid, d.head from emp e, dept d;
2. select e.empid, d.head from emp e, dept d where e.dept# = d.dept#;
3. select e.empid, d.head from emp e, dept d where e.dept# = d.dept# (+);
4. select e.empid, d.head from emp e, dept d where e.dept# (+) = d.dept#;
109. Developer ANJU executes the following statement: CREATE TABLE
animals AS SELECT * from MASTER.ANIMALS; What is the effect of this
statement?
1. A table named ANIMALS will be created in the MASTER schema with
the same data as the ANIMALS table owned by ANJU.
2. A table named ANJU will be created in the ANIMALS schema with the
same data as the ANIMALS table owned by MASTER.
3. A table named ANIMALS will be created in the ANJU schema with the
same data as the ANIMALS table owned by MASTER.
4. A table named MASTER will be created in the ANIMALS schema with
the same data as the ANJU table owned by ANIMALS.
110. User JANKO would like to insert a row into the EMPLOYEE table,
which has three columns: EMPID, LASTNAME, and SALARY. The user
would like to enter data for EMPID 59694, LASTNAME Harris, but no
salary. Which statement would work best?
1. INSERT INTO employee VALUES (59694,’HARRIS’, NULL);
2. INSERT INTO employee VALUES (59694,’HARRIS’);
3. INSERT INTO employee (EMPID, LASTNAME, SALARY) VALUES
(59694,’HARRIS’);
4. INSERT INTO employee (SELECT 59694 FROM ‘HARRIS’);
111. Which three of the following are valid database datatypes in Oracle?
(Choose three.)
1. CHAR
2. VARCHAR2
3. BOOLEAN
4. NUMBER
112. Omitting the WHERE clause from a DELETE statement has which of
the following effects?
1. The delete statement will fail because there are no records to delete.
2. The delete statement will prompt the user to enter criteria for the deletion
3. The delete statement will fail because of syntax error.
4. The delete statement will remove all records from the table.
113. Creating a foreign-key constraint between columns of two tables
defined with two different datatypes will produce an error.
1. TRUE
2. FALSE
114. Dropping a table has which of the following effects on a nonunique
index created for the table?
1. No effect.
2. The index will be dropped.
3. The index will be rendered invalid.
4. The index will contain NULL values.
115. To increase the number of nullable columns for a table,
1. Use the alter table statement.
2. Ensure that all column values are NULL for all rows.
3. First increase the size of adjacent column datatypes, then add the column.
4. Add the column, populate the column, then add the NOT NULL
constraint.
116. Which line of the following statement will produce an error?
1. CREATE TABLE goods
2. (good_no NUMBER,
3. good_name VARCHAR2 check(good_name in (SELECT name FROM
avail_goods)),
4. CONSTRAINT pk_goods_01
5. PRIMARY KEY (goodno));
6. There are no errors in this statement.
117. MAXVALUE is a valid parameter for sequence creation.
1. TRUE
2. FALSE
118. Which of the following lines in the SELECT statement below contain
an error?
1.SELECT DECODE(empid, 58385, “INACTIVE”, “ACTIVE”) empid
2.FROM emp
3.WHERE SUBSTR(lastname,1,1) > TO_NUMBER(’S')
4.AND empid > 02000
5.ORDER BY empid DESC, lastname ASC;
6.There are no errors in this statement.
119. Which function below can best be categorized as similar in function to
an IF-THEN-ELSE statement?
1. SQRT
2. DECODE
3. NEW_TIME
4. ROWIDTOCHAR
120. Which two of the following orders are used in ORDER BY clauses?
(choose two)
1. ABS
2. ASC
3. DESC
4. DISC
121. You query the database with this command
SELECT name
FROM employee
WHERE name LIKE ‘_a%’;
UML
DataBase Management
Expected answer:
A Cartesian product is the result of an unrestricted join of two or more tables. The result
set of a three table Cartesian product will have x * y * z number of rows where x, y, z
correspond to the number of rows in each table involved in the join. It is causes by
specifying a table in the FROM clause without joining it to another table.
Expected answer:
A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS
control of permissions for security purposes. It also eliminates the need to recompile
components when minor changes occur to the database.
Expected answer:
A LEFT JOIN will take ALL values from the first declared table and matching values
from the second declared table based on the column the join has been declared on. An
INNER JOIN will take only matching values from both tables
4. When a query is sent to the database and an index is not being used, what type of
execution is taking place?
Expected answer:
A table scan.
Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data
modification in a table to which the trigger belongs.
6. What are the pros and cons of using stored procedures. When would you use
them?
7. What are the pros and cons of using cursors? When would you use them?