You are on page 1of 157

Question 5) What is the Proxy Server? ANSWER : A proxy server speaks the client side of a protocol to another server.

This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular web site, a proxy server can get the contents of the web server's popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Struts Basic questions and answers Q1.Describe Jakarta Struts Framework? Ans: Jakarta Struts Framework is implements Model-View-Controller design pattern , it is an open source code sponsored by Apache Jakarta Struts.It is server side implementation of MVC model-II. It saves time in design and implementation of a web based application due to this framework and pattern as I is highly robust, scalable and reliable. Q2.What are the components of Struts? Ans: Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller. Model: Model is used to impalement business object. Components like business logic / business processes and data are the part of Model. View: JSP, HTML etc. are part of View Controller: ActionServlet of Struts is part of Controller components which works as front controller to handle all the requests. Struts Objective Questions And Answers
Struts Objective Questions And Answers

Struts Subjective Questions And Answers


Struts Subjective Questions And Answers

Struts Interview Questions And Answers


Struts Interview Questions And Answers

Q3:What is ActionServlet ? Ans:ActionServlet provides the "controller" in the Model-View-Controller (MVC) design pattern for web applications that is commonly known as "Model 2".

It is backbone of struts application.It is used as controller to control .There can be only one ActionServlet defined for a context. ActionServlet is defined in web.xml file of a context e.g. WEB-INF/web.xml Q4:What is an Action Class used for? Ans:An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The controller (ActionServlet) will select an appropriate Action for each request, create an instance (if necessary), and call the perform method. Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. In this means you should design with the following items in mind: Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action. Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary. When an Action instance is first created, the controller servlet will call setServlet() with a non-null argument to identify the controller servlet instance to which this Action is attached. When the controller servlet is to be shut down (or restarted), the setServlet() method will be called with a null argument, which can be used to clean up any allocated resources in use by this Action. Q5:What is ActionForm? Ans:An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresonding action's perform() method is called. When the properties of this bean have been populated, but before the perform() method of the action is called, this bean'svalidate() method will be called, which gives the bean a chance to verify that the properties submitted by the user are correct and valid. If this method finds problems, it returns an error messages object that encapsulates those problems, and the controller servlet will return control to the corresponding input form. Otherwise, the validate() method returns null(), indicating that everything is acceptable and the corresponding Action's perform() method should be called. This class must be subclassed in order to be instantiated. Subclasses should provide property getter and setter methods for all of the bean properties they wish to expose, plus override any of the public or protected methods for which they wish to provide modified functionality. Q6:What is Struts Validator Framework? Ans:Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts

Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. Q7.What are the core classes of the Struts Framework? Ans:Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServletetc.

Q8.What are Tag Libraries provided with Struts? Ans: Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are: 1) Bean Tags: Bean Tags are used to access the beans and their properties. 2) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc.. 3) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets. 4) Nested Tags: Nested Tags helps to work with the nested context. Q9:What are difference between ActionErrors and ActionMessage? Ans: ActionMessage: A class that encapsulates messages is called ActionMessage. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key , and up to four placeholder arguments used for parametric substitution in the resulting message. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property. Q10:How you will handle exceptions in Struts? Ans: In Struts you can handle the exceptions in two ways: 1) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within .. tag. Example: key="database.error.duplicate" path="/UserExists.jsp" type="mybank.account.DuplicateUserException"/> 2) Programmatic Exception Handling: Here you can use try{}catch{} block to

handle the exception.

Q11:Give the Details of XML files used in Validator Framework? Ans:The Validator Framework uses two XML configuration files validatorrules.xml and validation.xml. Thevalidator-rules.xml is provided with the Validator Framework. The validator-rules.xml is used to declares and assigns the logical names to the validation routines. It also contains the client-side java-script code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations. The Validator plug-in is supplied with a predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. This basic set of rules can also be extended with custom validators if required. The validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together. Example of form in the validation.xml file: <!-- An example form --> <form name="logonForm"> <field property="username" depends="required"> <arg key="logonForm.username"/> </field> <field property="password" depends="required,mask"> <arg key="logonForm.password"/> <var> <var-name>mask</var-name> <var-value>^[0-9a-zA-Z]*$</var-value> </var> </field> </form> Q12:How you will display validation fail errors on jsp page? Ans:Following tag displays all the errors:

Q13:How you will enable front-end validation based on the xml in validation.xml? Ans:The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form "logonForm" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

Q14:Can I setup Apache Struts to use multiple configuration files? Ans:Yes.Struts can use multiple configuration files. Here is the configuration example: <servlet> <servlet-name>banking</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml, /WEB-INF/struts-authentication.xml, /WEB-INF/struts-help.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Q15:How you will make available any Message Resources Definitions file to the Struts Framework Environment? Ans: Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag. Q16:What is Struts Flow? Ans: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuationscapable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. Q17:What is LookupDispatchAction? Ans: LookupDispatchAction is an abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. Q18:What do you understand by DispatchAction?

Ans:DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class. Q19:Is struts threadsafe?Give an example? Ans:Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action

Q20:What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file? Ans:tiles-def.xml is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View.

Q21:What is the difference between perform() and execute() methods? Ans:Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available. Q22:How Struts relates to J2EE? Ans:Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard. Q23:What is Struts actions and action mappings? Ans:A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and password. An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is

visible only to this action. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller. Page 1
Ques: 1 What is struts? Ans: The Jakarta struts project, an open source project supported by the Apache software Foundation, is a server side java implementation of the modetl view controller (MVC) design pattern. The struts framework designed to create Web application that easily separate the presentation layer and allow it to be abstracted from the transaction and data layers. Ques: 2 What are the various steps involved in the implementaion of struts? Ans: The struts framwork models its server side implementation of the MVC using a combination of JSPs, custom JSP tags, and a Java Servlet. It involves the following steps : * The incoming request is received by the ActionServlet, which acts as the controller, and the ActionServlet looks up the requested URI in an XML file. * The ActionClass performs its logic on the Model components associated with the application. * Once the Action has completed its processing, it returns control to the ActionServlet with a key that indicates the result of its processing. ActionServlet uses this key to determine where this result should be forwarded for presentation. * The request is complete when the ActionServlet response by forwarding the request ot the view that was linked to the returned key, and this view presents the result of the Action. Ques: 3 What is MVC design pattern? Ans: MVC stands for Model-View-Controller. The MVC design pattern is originated from Smalltalk, consists of three components : a Model, a View, and a Controller. MODEL : Represents the data objects. The Model is what is being manipulated and persented to the user. Model contains the business logic of the application. VIEW : Serves as screen representation of the Model. It is the object that represents the current state of the objects. CONTROLLER : Defines the way the user interface reacts to the user's input. The Controller component is the object that manipulates the Model, or data object. Ques: 4 How will you install struts framework in your web application? Ans: The follwing steps are involved to install struts framework in your web application : * Uncompress the Struts Archive to your local disk.

* Create a new web Application say, MyStrutsApp inside the webapps directory under the tomcat directory. * Copy all the jar files, extracted from the lib directory into the /webapps/MyStrutsApp/WEB-INF/lib directory. * Create an empty web.xml file and copy it to the /webapps/MyStrutsApp/WEB-INF/ directory. * Create an empty struts-config.xml file and copy it to the /webapps/MyStrutsApp/WEB-INF/ directory. The struts-config.xml file is the diployment descriptor for all Struts applicattion. It is the file that glues all of the MVCcomponents together. Ques: 5 Describe the struts specific form tag? Ans: Instead of using the standard HTML Form tag, like most HTML pages, the struts specific Form tag is : <html:form action="" name="" type=""> .......... </html:form> This tag with its subordinate input tags, encapsulates Struts form processing. The Form tag attributes are : * action : Represents the URL to which this form will be submitted. This is also used to find the appropriate ActionMapping in the Struts configuration file. * name : Identifies the key that is used to lookup the appropriate ActionForm that will represent the submitted form data. * type : Names the fully qualified classname of the form bean you want to use in this request. To use the struts specific <html:form> tag you have to use the taglib directive: <%@ taglib uri="WEB-INF/struts-html.tld" prefix="html" %> Ques: 6 What is ActionForm in the struts? Ans: When an <html:form/> is submitted, the Struts framework populates the matching data members of the ActionForm with the values entered in the <html:form/> tag. The Struts framework does this by using JavaBean introspection. This is all done by the class specified in the type attribute of the <html:form/> tag. This class will extends the org.apache.struts.action.ActionForm, as must all ActionForm objects with a get and set accessor that match its data members. Ques: 7 What are the parameters used in the Action.execute() method in the Struts. Ans: The following parameters are used in the Action.execute(...) method : * ActionMapping : The ActionMapping class contains all of the deployment information for a particular Action object. This class is used to determine where the result of the class (that extends the Action class) will be sent once its processing is complete. * ActionForm : Represents the form inputs cntaining the request parameters from the view referencing this Action bean. * HttpServletRequest : Reference to the current Http request object. * HttpServletResponse : Reference to the current Http response object. Ques: 8 Which mathod is use to forward the result to the appropriate view in the Action class in Struts? Ans: The findForward() method is use to forward the result to the appropriate view in the Action class. This method takes the paremeter name for the view file to which the result is being forwarded. Ans: ActionMapping Class's findForward(String) method...

in ActionClass ActionMapping is Passed as Parameter so we do not need to create Seprate instance for that ...... Ques: 9 How will you tell the web application and container about your ActionServlet? Ans: This can be accomplished by adding the following servlet definition to the web.xml file : <servelt> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Once you told the container about the ActionServlet you need to tell it when it should be executed by adding <servelt-mapping> element in web.xml file : <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> This mapping tells the web application that whenever a request is received with .do appended to the URL then the servlet named action should service the request. Ques: 10 What are the various struts controller components? Ans: Four distinct Struts Controller components: * The ActionServlet class * The Action class * Plugins * RequestProcesser Ques: 11 What is ActionServlet class in the struts controller? Ans: The org.apache.struts.action.ActionServlet is the backbone of all Struts application. It is the main controller component that handles the client request and determines which org.apache.struts.action.Action will process each received request. It serves as an Action factory - creating specific Action classes based on the user's request. Ques: 12 What is the entry point to ActionServlet when a request comes in. Ans: The two main entry point into the ActionServlet are the same as any other servelt : doGet() and doPost(). They call single method named process(). The struts specific behaviour begin with this mehtod. Ques: 13 What is the process() method doing in the ActionServlet class? Ans: The process() method gets the current RequestProcessor and invokes the RequestProcessor.process() method.The RequestProcessor.process() method is where the current request is actually serviced. This method retrieves from the struts-config.xml file, the <action> element that matches the path submitted on the request. It does this by matching the path passed in the <html:form/> tag's action element to the <action> element with the same path value. Ques: 14 Who calls the ActionForm.validate() method inside the ActionServlet.

Ans: The RequestProcessor.process() method calls the ActionForm.validate() method, which checks the validity of the of the submitted values. Ques: 15 What is for Action.execute() method? Ans: The execute method is where your application logic begins. It is the method that you need to override when defining your own Actions. The execute() method has two functions: * It performs the user-defined business logic associated with your application. * It tells the Framework where it should next route the request. The Struts framework defines two execute() methods. The first execute() implementation is used when you are defining custom Actions that are not HTTP specific, i.e. anlogous to the javax.servlet.GenericServlet class. The second, HTTP specific, You need to override the Action.execute() method and is anlogous to the javax.servlet.HttpServlet class. Its signature is: public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpResponse response) throws IOException, ServletException{// some code here} Ques: 16 Describe the purpose of the Action class? Ans: The org.apache.struts.action.Action class is a most common component of the Struts Controller. This class must be extended for each specialized Struts function in your application. The collection of these Action classes is what defines your web application. To develop your own Action class, you must complete the following steps: * Create a class that extends the org.apache.struts.action.Action class. * Implement the appropriate execute() method and add your specific business logic. * Compile the new Action and move it to the Web application's classpath, i.e. /WEBINF/classes directory. * Add an <action> element to the application's struts-config.xml file describing the new Action. Ques: 17 What are Struts Plugins? Ans: Struts Plugins are modular extensions to the Struts COntroller. They are defined by the org.apache.struts.action.Plugin interface. Struts Plugins are useful are useful when you are allocating resources or preparing connections to the databases or even JNDI resources. This interface defines two lifecycle mathods: init() and desstroy(). Ques: 18 What are the steps involved in Struts Plugins? Ans: All Plugins must implement the two Plugin methods init() and destroy(). To develop your own Plugin You must complete the following steps: * Create a class that implements the org.apache.struts.action.Plugin interface. * Add a default empty contructor to the Plugin implementation. You must have a default constructor to ensure that the ActionServlet property creates your Plugin. * Implement both the init() and destroy() methods and your implementation. * Compare the new Plugin and move it into the web applocation's classpath. * Add a <plug-in> element to the application's struts-config.xml file describing the new Plugin. Ques: 19 What is RequestProcessor? How will you create your own RequestProcessor? Ans: The RequestProcessor is the class that you need to override when you want to customize

the processing of the ActionServlet. It contains a predefined entry point that is invoked by the Struts controller with each request. The entry point is the processPreprocess() method. Steps involved in creation your own RequestProcessor: * Create a class that extends the org.apache.struts.action.RequestProcessor class. * Add a default empty constructor to the RequestProcessor implementation. * Implement your processPreprocess() method. Ques: 20 How will you configure the Plugin in your web application. Ans: To deploy and configure your Plugin class, you must: * Compile and move the Plugin class file into your application's WEB-INF/classes/ directory. * Add a <plug-in> element to your struts-config.xml file. For example: <plug-in className="MyPlugin"/> The <plug-in> element should be the last element in the struts-config.xml file. * Restart the Web application

155 Java Interview Questions OOPS 1. What is an Object? 2. What is a Class? 3. What is OOAD? 4. What is Data Abstraction ? 5. What is Data Encapsulation? 6. What is the difference between Data Abstraction and Information Hiding? 7. What is Inheritance and what are different types of it? 8. Why Java uses Singly rooted hierarchy? 9. Why does Java not support Multiple Inheritance? 10. Why is Java not 100% pure OOP language? 11. What is Early Binding?

12. What is Polymorphism/Late Binding? 13. What is method overloading? 14. What is method overriding? 15. How is Java different from C++? 16. What is UML and how is it useful in designing large systems? 17. Is UML useful for procedural programming ? 18. What are different notations used in UML ? 19. What is a Use case and an Actor? 20. How to identify an Actor? 21. What is Generalization? 22. What is Association and how it maps into a Java class? 23. What is Aggregation and how it maps into a Java class? 24. What is Composition and how it maps into a Java class? 25. What is Dependency and how it maps into a Java class? 26. What is the purpose of State machine diagrams? 27. What are different kinds of Structure diagrams? 28. What are different kinds of Interaction diagrams? 29. What are different kinds of Behavior diagrams?

Java Fundamentals 30. What is a Java Virtual Machine (JVM)? 31. What is a JVM consisted of? 32. What is a class loader and what is its responsibilities? 33. What is heap and stack? 34. How is your Java program executed inside JVM? 35. What is Java class file's magic number? 36. How JVM performs Thread Synchronization? 37. How JVM performs Garbage Collection? 38. How to profile heap usage? 39. What will you do if VM exits while printing "OutOfMemoryError" and increasing max heap size doesn't help? 40. Should one pool objects to help Garbage Collector?Should one call System.gc() periodically? 41. An application has a lot of threads and is running out of memory, why? 42. If your program is I/O bound or running in native methods, do these activities engage JVM? 43. What is the difference between interpreted code and compiled code? 44. Why Java based GUI intensive program has performance issues? 45. What is 64 bit Java ?

46. What is the difference between JVM and JRE? 47. What are different primitive datatypes in Java? 48. What are expressions,statements and blocks in Java? 49. What is a transient variable? 50. What is the difference between the '&' operator and the '&&' operator? 51. Why main method of Java has public static void? 52. If you have static block, constructor and main method in Java file then what will be the sequence of method calls? 53. What are the command line arguments? 54. Does Java support multi dimensional arrays? 55. What are the restrictions for static method? 56. Why a abstract method cannot be static? 57. Is 'sizeof' a keyword? 58. What is the precedence of operators in Java? 59. How is an argument passed in Java methods? 60. What is the difference between class variable, member variable and automatic(local) variable? 61. When are static and non static variables of a class initialized? 62. Can shift operators be applied to float types?

63. What are different Java declarations and their associated rules? 64. What are Java Modifiers? 65. Explain final modifier. 66. Can you change the reference of the final object? 67. Can abstract class be instantiated? 68. When does the compiler insist that the class must be abstract? 69. Where can static modifiers be used? 70. What is static initializer code? 71. Can an anonymous class implement an interface and extend a class at the same time? 72. What are volatile variables? 73. Can protected or friendly features be accessed from different packages? 74. How many ways can one write an infinite loop? 75. When do you use 'continue' and 'break' statements? 76. What is the difference between 'while' and 'do while' loop? 77. What is an Assertion and why using assertion in your program is a good idea ? 78. Explain Assertions with a code exmaple. 79. How many forms of assertions we have?

80. When assertions should be avoided? 81. What situations are best suitable for implementing assertions? 82. What is Exception ? 83. What is a user-defined exception? 84. What do you know about the garbage collector? 85. Why Java does not support pointers? 86. Does garbage collection guarantee that a program will not run out of memory? 87. What is finally in Exception handling? 88. What can prevent the execution of the code in finally block? 89. Explain 'try','catch' and 'finally' blocks? 90. Define Checked and Unchecked exception. 91. What is the difference between an abstract class and an interface? 92. What is the use of interface? 93. What is serializable interface? 94. Does a class inherit constructors from its superclass? 95. What's the difference between constructors and other methods? 96. If the method to be overridden has access type 'protected', can subclass have the access type as 'private'?

97. If you use super() or this() in a constructor where should it appear in the constructor? 98. What modifiers may be used with an inner class that is a member of an outer class? 99. Can an inner class be defined inside a method? 100. What is an anonymous class? 101. What is a thread? 102. What is the difference between process and threads? 103. What are two types of multitasking? 104. What are two ways of creating threads in Java and why so? 105. How does multithreading take place on a computer with a single CPU? 106. How a Java object be locked for exclusive use by a given thread? 107. What is Synchronization? 108. Explain wait(),notify(), and notifyAll() methods? 109. What is a Daemon thread? 110. How a dead thread can be started? 111. What is the difference between String and StringBuffer? 112. How is '==' different from .equals() method in case of String objects? 113. Explain StreamTokenizer?

114. What is Collection? 115. Explain List,Set and Map. 116. What is the serialization? 117. What is the difference between Serializable and Externalizable interface? 118. What is memory leak? 119. Difference between ArrayList and Vector class? 120. What is the difference between Hashtable and HashMap? 121. What is JFC? 122. What is the difference between JFC Swing and AWT? 123. What is the base class for all swing components? 124. What are lightweight and heavyweight components ? 125. How can a GUI component handle its own events? 126. What is a Layout Manager and what are its different types and their advantages? 127. How are the elements of a GridBagLayout organized? 128. What are the problems faced by Java programmers in absence of layout managers? 129. Where the CardLayout is used? 130. What is the difference between GridLayout and GridBagLayout?

131. How will you add a panel to a frame? 132. What is the difference between Application and Applet? 133. Explain Lifecycle of the Applet and what is the order of method invocation in an applet? 134. What is the difference between Java class and bean? 135. What is difference between trusted and untrusted applet? 136. How do you set Java Library path programmatically?(new)

137. Explain the usage of java.util.Date and more classes and APIs for date handling in Java?(new) JDBC 138. What is JDBC ? 139. What are four drivers available in JDBC? 140. How do you establish database connection using JDBC? 141. What are the different types of Statements? 142. What is PreparedStatement and how is different from Statement? 143. What is the difference between executeQuery () and execute() ? 144. What is the difference between executeQuery () and executeUpdate()? 145. How do you call a stored procedure in Java? 146. What are new features from JDBC2.0 onwards?

147. How can a cursor move in scrollable result sets? 148. Differentiate TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE? 149. How will you differentiate the following two ways of loading a database driver? 150. How can you display a particular web page from an applet?(new) 151. How can you get the hostname on the basis of IP addres ?(new) 152. How can you get an IP address of a machine from its hostname?(new) 153. How do you know who is accessing your server?(new) 154. What are different socket options?(new) 155. What should I use a ServerSocket or DatagramSocket in my applications?(new) Core java interview questions with answers 1. Can a main() method of class be invoked in another class? Ans-- Yes it is possible only when main() class should be declared as public and static. here the example package r4r.co.in; class Newclass { //this is main class called as Newclass public static void main(String args[]) { System.out.println("this is mainclass"); } } public class Invokedclass { public static void main(String args[]) { System.out.println("this is invokedclass which invoked Newclass"); //this is subclass called as Invokedclass

Newclass.main(args); } } //save and compile the program by name of Invokedclass.java Result: this is invokedclass which invoked Newclass this is mainclass

2. What is the difference between java command line arguments and C command line arguments? Ans-3. What is the difference between == & .equals(). Ans-- The equals( ) method compares the characters inside a String object while the == operator compares two object references which refer to the same instance. Example //Comparison of two Strings package r4r.co.in; class CompareStrings { public static void main(String args[]) { String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 + " equals " + s2 + " : " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " : " + (s1 == s2)); } } //save and compile the program by name of CompareStrings.java Result: Hello equals Hello : true Hello == Hello : false 4. What is the difference between abstract class & Interface. Ans-- Any class that contains one or more abstract methods must be declared abstract by putting the abstract keyword in front of the class and at the beginning of the class declaration, remember there is no objects of an abstract class. Abstract class method can't be overriding in a another class because an abstract

class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Through the use of the interface keyword, Java allows to fully abstract the interface from its implementation. Interface is a concept work on sharing the data in superclass ( or Parent class) to subclass( or child class) ,but non of class define protected and abstract. The interface, itself, does not actually define any implementation. 5. What is singleton class & how you can implementation it?. 6. What is use of static, final variable? Ans-- Any class which is declare to be static as use a keyword static. The example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist, while instance variables declared as static are used as global variables. Methods declared as static have several restrictions:

They can only call other static methods. They must only access static data not dynamic data. They can't refer to this or super in any way. As the program is compile static member ,variable or class is loaded first than dynamic class.

A variable can be declared as final, class can't declare final means a final variable must be initialize a final when it is declared.Final Variables don't occupy memory on per-instance basis. Hence, a final variable is must be constant. 7. Examples of final class. Ans-- Final class is only use for prevent a class from being inherited. By declaring a class as final as use final keyword in front of class implicitly declares all of its methods as final too. But, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and depend upon its subclasses to provide complete implementations. //Following example consider for final class package r4r.co.in; final class A { //following class should be declare to final can't be inheritance int a = 5; //value which declare into int should be constant Float b = (float) 3.45; }

class B extends A { public static void main(String[] args) { } } 8. What is difference between Event propagation & Event delegation? 9. What is difference between Unicast & Multicast model? 10. What is a java bean? Ans--A Java Bean is a software component that is designed for the reusable in a variety of different environments and itsarchitecture is totally based on a component which enables programmers to create software. Components are selfcontained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. Also, a bean is use to perform a function like checking the spelling of a document, a complex function such as forecasting the performance of a stock portfolio. Beans expose properties so they can be customized at design time.Customization is supported in two ways: -- by using property editors. -- by using more sophisticated bean customizers. 11. What is use of synchronized keyword? Ans--The synchronized keyword can be used for locking in program or utilize for lock/ free the resource for any thread/program.When two or more threads/program want to access a shared resource, they need someway to ensure that the resource will be use by only one thread at a time. The process by which this is achieved is called synchronization. // Create multiple threads using synchronization method. package r4r.co.in; class MYThread implements Runnable { String name; Thread t; MYThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("My thread: " + t); t.start(); // name of thread

// Thread Start for execution

} synchronized public void run() { try { for (int i = 0; i < 10; i++) { System.out.println(name + ": " + i); Thread.sleep(100); } } catch (Exception e) { System.out.println(name + e); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new MYThread("One"); new MYThread("Two"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("My thread exiting."); } } 12. What are the restrictions of an applet & how to make the applet access the local machines resources? Ans-13. What is reflect package used for & the methods of it? Ans-- The java.lang.reflect.* package provides the ability to obtain information about the fields, constructors, methods, and modifiers of a class, also includes a class that access arrays dynamically.
//simple example consider for how reflection works, package r4r.co.in; import java.lang.reflect.*;

// Initialization of thread.

//thread sleep

// Thread sleep

public class Reflection { public static void main(String args[]) { try { Class c = Class.forName("java.lang.String");

// Here String is loaded

class.
Method m[] = c.getDeclaredMethods(); implemented System.out.println(m[0].toString()); // Here get method

for (int i = 0; i < m.length; i++) { System.out.println(m[i].toString()); } } catch (Exception e) { System.out.println(e); } }

14. What is use of serialization? Ans--The process of writing the state of an object to a byte stream is called serialization, also, it is used to save the program to persistent storage area, like a file and easily restore using Deserialization process. 15. Can methods be overloaded based on the return types ? Ans-- Java does not support return-type-based method overloading. Method can be overload either same name and samesignatures( argument/parameter). 16. Why do we need a finalize() method when Garbage Collection is there ? Ans-- Some time an object( which is lost there object reference) is holding some java resource like file handle ,character font, need to free from the resource before that object is collecting by JVM( Java Virtual machine) or say garbage collection. Then to finalize the class, simply define the keyword protected finalize( ) method( protected prevent access of final method) in front of class, Java at the runtime call this object's resource and JVM easily recycle that class. 17. Difference between AWT and Swing components ? Ans--AWT are heavy weight components while Swing are light weight components because AWT is platform dependent while Swing is not dependent any of the platform. Alternate, AWT( heavyweight component ) is one that is associated with its own native screen resource (commonly known as a peer) while Swing( lightweight component )

is one that "borrows" the screen resource of an ancestor ( means it has no native resource of its own). 18. Is there any heavy weight component in Swings ? Ans--Yes, since all AWT components are heavyweight and all Swing components are lightweight (except for the top-level ones: JWindow, JFrame, JDialog, and JApplet), these differences apparent when start mixing Swing components with AWT components. 19. Can the Swing application if you upload in net, be compatible with your browser? Ans-- Yes. because Swing are platform independent independent 20. What should you do get your browser compatible with swing components? 21. What are the methods in Applet ? Ans-- Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. Some Applet method which frequently used-

22. When is init(), start() called ? Ans-- Int() method is called by applet viewer or browser at the time of load applet application into system while Start() method is called by the applet viewer or browser at the time of when applet is complete loaded into system and start its execution. 23. When you navigate from one applet to another what are the methods called? Ans--Applet can be navigate with other by appletcontext() method. 24. What is the difference between Trusted and Untrusted Applet ? Ans-- Java applets are typically executed by Web browsers with embedded Java Virtual Machines (VMs) and runtime class libraries. Applets are downloaded by the browser and then executed by the built-in VM on the machine running the browser. The security of the system depends upon the Java language itself, the runtime class libraries, and the Security Manager of the browser. Applets are of two types-

Trusted Applet:-Java virtual machines( JVM ) run applets under a different security regime( refers to a set of conditions) than applications. By default, applications are implicitly trusted. The designers of the JVM specification assumed that users start applications at their own initiative and can therefore take responsibility for the application's behavior on their machine. Such code is considered to be trusted. Untrusted Applet-The applet which started automatically by the browser after it downloads and displays a page. Users can't be expected to know what applets a page might contain before they download it, and therefore cannot take responsibility for the applet's behavior on their machine. Applets, therefore, are considered by default to be untrusted.

25. What is Exception ? Ans-- An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error must be checked and handled manually. Exceptions can be generated by the Java run-time system (or java virtual machine, JVM ), or they can be manually generated by your code. Exception is of two type1. Check Exception or Compiletime Exception. An exception which generate by programming error like user written program or code and must be handle at time of compilation of program. 2. Uncheck Exception or Runtime Exception. An exception which can generate at the runtime of program, the compiler doesnt force the programmers to catch the exception. 26. What are the ways you can handle exception ? Ans-- When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Try block is used to monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner. To manually throw an exception, use the keyword throw. Any code that must be executed before a method returns is put in a finally block. The following syntax represent exception handling try { // block of code to monitor for errors } catch (Exception exObject) { // exception handler for ExceptionType1 }

finally { // block of code to be executed before try block ends } 27. When is try, catch block used ? Ans--Try block is used to monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner. The following syntax represent exception handling try { // block of code to monitor for errors } catch (Exception exObject) { // exception handler for ExceptionType1 }

28. What is finally method in Exceptions ? Ans-- The finally method will be executed after a try or catch execution, and mainly used to free up resources. Any code that must be execute before a method returns is put in a finally block. 29. What are the types of access modifiers ? Ans-- In java four access modifier is used describe belowAccess Modifiers* public protected private package( default) Class Yes Yes Yes Yes Nested class Yes Yes No Yes Subclass Other packages Yes Yes No Yes Yes No No No

* The following access modifiers apply to script and instance member like instance functions, script functions, instance variables, and script variables.

32. Is synchronized modifier ? Ans-- Yes, If more than one of your threads running at the same time and access shared objects, then a synchronized keyword is placed in front of Run method, so synchronized should be modify according to the object that call run method. 33. What is meant by polymorphism ? Ans-- Generally, polymorphism is a concept in which a subclass( or child class) can be easily inherited the member (like method, parameter and signature) of superclass (or parent class) but not vice-versa. Polymorphism may be of two kind

Method overloading Method overriding

34. What is inheritance ? 35. What is method Overloading ? What is this in OOPS ? Ans-- when two methods and operator (within different class) have the same name and same arguments , but different signature, it is known as overloading in Object oriented concepts. Two types of are:1. Operator overloading is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments. 2. Function overloading or method overloading is allows to creation the several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the function. Method overloading is usually associated with statically-typed programming languages which enforce type checking in function calls. 36. What is method Overriding ? What is it in OOPS ? Ans-- In overriding, a method in a super class is overridden in the subclass. The method in the subclass will have the same signature as that of the superclass. Since the method in the subclass has the same signature & name as the method of its super class, it is termed as overriding. // example for method overriding package r4r.co.in; class number { int i, j;

number(int a, int b) { i = a; j = b; System.out.println("i and j: " + i + " " + j); } } class numbertest extends number { A. int k; numbertest(int a, int b, int c) { super(a, b); k = a + b + c; //airthmetic sum System.out.println("value of k:" + k); } } class Override { public static void main(String args[]) { numbertest b = new numbertest(1, 2, 3); } } 37. Does java support multi dimensional arrays ? Ans-- Yes, java supported multi dimension array. Example//Syntax for defining multidimensional array var array = new Array(3); for (var i = 0; i < 3; i++) { array[i] = [' ', ' ', ' ']; } //initialization of an array // Create a subclass by extending class

//initilization numbertest

Result array[0][2] = 'x'; array[1][1] = 'x'; array[2][0] = 'x';

38. Is multiple inheritance used in Java ? Ans-- Java doesn't support multiple inheritance is direct form due to arise the problem of ambiguity( Doubtfulness or uncertainty as regards interpretation), but it support it in term of interface. 40. Does JavaScript support multidimensional arrays ? Ans-- Yes , JavaScript is support multidimensional array. Example--//Syntax for defining multidimensional array var array = new Array(3); for (var i = 0; i < 3; i++) { array[i] = [' ', ' ', ' ']; } //initialization of an array

Result array[0][2] = 'x'; array[1][1] = 'x'; array[2][0] = 'x';

41. Is there any tool in java that can create reports ? Ans--Jesperreport. 43. What is meant by a class ? Ans-- A class is a specification (think of it as a blueprint or pattern and a set of instructions) of how to construct something. 44. What is meant by a method ? Ans-- A method declaration is the heading of a method containing the name of the method, its parameters, and its access level. 45. What are the OOPS concepts in Java ? Ans-- OOPs use three basic concepts as the fundamentals for the programming language: classes, objects and methods. Additionally, Inheritance, Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within object-oriented programming languages. 46. What is meant by encapsulation ? Explain with an example. Ans-- Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. 47. What is meant by inheritance ? Explain with an example. Ans--Inheritance means to take something that is already made. It is one of the most important features of Object Oriented Programming. It is the concept that is used for reusability purpose. Inheritance is the mechanism through which we can

derive classes from other classes. The derived class is called as childclass or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used.

50. What is meant by Java interpreter ? Ans-- A small program with interpret java byte code to machine languages Core java interview questions And Answer Q1.What is the difference between procedural and object-oriented programs? Ans: The difference between procedural and object-oriented programs are a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code. Q2.What are Encapsulation, Inheritance and Polymorphism? Ans: Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used more than one calss.In other world we can say polymorphism is a reusability of object in more than one class. Q3.What is the difference between Assignment and Initialization? Ans:Assignment can be many times as desired whereas initialization can be only once. Q4.What is OOPs? Ans: Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. Q5.What are Class, Constructor and Primitive data types? Ans: Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created. The name of constructor is same as class name. Primitive data types are 8 types and they are: byte, short, int, long, float, double, Boolean, char. Q6.What is an Object and how do you allocate memory to it? Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. The object is created by using new keyword. When an object is created using new operator, memory is allocated to it. Q7.What is the difference between constructor and method? Ans: Constructor will be automatically invoked when an object is created whereas method has to be called explicitly by using dot(.) operator . Q8:What are methods and how are they defined? Ans: Methods are functions that operate on instances of classes in which they are defined. By use of the method objects can communicate with each other and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A methods signature is a combination of the first three parts mentioned above. Q9:What is the use of bin and lib in JDK? Ans: Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages. Q10: What is casting? Ans: Casting is process of convert the value of one type to another. Q11: How many ways can an argument be passed to a subroutine and explain them? Ans: An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Q12:What is the difference between an argument and a parameter? Ans: At time of defining method, variables passed in the method are called parameters At time of using those methods, values passed to those variables are called arguments

Core Java Interview Questions and Answers Q13:What are different types of access modifiers? Ans:There are following four types of access modifiers public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private cant be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. Q14 : When we can declare a method as abstract method ? Ans: When we have to want child class to implement the behavior of the method.

Q15: Can We call a abstract method from a non abstract method ? Ans : Yes, We can call a abstract method from a Non abstract method in a Java abstract class Q16: What is the difference between an Abstract class and Interface ? And can you explain when you are using an Abstract classes ? Ans: Abstract classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic functionality of your application, child class which inherited this class will provide the functionality of the abstract methods in abstract class. When base class calls this method, Java calls the method defined by the child class. An Interface can only declare constants and instance methods, but cannot implement default behavior. Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast. Q17: What is user-defined exception in java ? Ans: User-defined expectations are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherited the Exception class as shown below. Using this class we can throw new exceptions for this we have use throw keyword .

Example of user define exception Java Example : 1.Create an class which extends Exception:public class greaterVlaueException extends Exception { } 2.Throw an exception using a throw statement: public class Fund { /java/. public Object getFunds() throws greaterVlaueException { if (id>2000) throw new greaterVlaueException(); /java/. } } User-defined exceptions should usually be checked. Q18 : What is the difference between checked and Unchecked Exceptions in Java ? Ans: All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try /java/ catch() block or we should throw the exception using throws clause. If you don't, compilation of program will fail. All exceptions in RuntimeExcetption and Error class are unchecked exception. Q19: Explain garbage collection ? Ans: Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and this object will destroy by garbage collector. A more accurate and up-to-date metaphor might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being freed. Q20 : How you can force the garbage collection ? Ans: Garbage collection automatic process and can't be forced. We can call garbage collector in Java by callingSystem.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Q21 : What are the static fields & static Methods ? Ans: If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot access nonstatic field or call non-static method Q22:What are the Final fields & Final Methods ? Ans: Fields and methods can also be declared final. Final method: A final method cannot be overridden in a subclass. Final field: A final field is like a constant: once it has been given a value, it cannot be assigned to again

1. Can a main() method of class be invoked in another class? Ans-- Yes it is possible only when main() class should be declared as public and static. here the example package r4r.co.in; class Newclass { //this is main class called as Newclass public static void main(String args[]) { System.out.println("this is mainclass"); } } public class Invokedclass { public static void main(String args[]) { System.out.println("this is invokedclass which invoked Newclass"); Newclass.main(args); } } //save and compile the program by name of Invokedclass.java Result: this is invokedclass which invoked Newclass this is mainclass //this is subclass called as Invokedclass

2. What is the difference between java command line arguments and C command line arguments? Ans--

3. What is the difference between == & .equals(). Ans-- The equals( ) method compares the characters inside a String object while the == operator compares two object references which refer to the same instance. Example //Comparison of two Strings package r4r.co.in; class CompareStrings { public static void main(String args[]) { String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 + " equals " + s2 + " : " + s1.equals(s2)); System.out.println(s1 + " == " + s2 + " : " + (s1 == s2)); } } //save and compile the program by name of CompareStrings.java Result: Hello equals Hello : true Hello == Hello : false 4. What is the difference between abstract class & Interface. Ans-- Any class that contains one or more abstract methods must be declared abstract by putting the abstract keyword in front of the class and at the beginning of the class declaration, remember there is no objects of an abstract class. Abstract class method can't be overriding in a another class because an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Through the use of the interface keyword, Java allows to fully abstract the interface from its implementation. Interface is a concept work on sharing the data in superclass ( or Parent class) to subclass( or child class) ,but non of class define protected and abstract. The interface, itself, does not actually define any implementation. 5. What is singleton class & how you can implementation it?. 6. What is use of static, final variable? Ans-- Any class which is declare to be static as use a keyword static. The example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist, while instance variables declared as static are used as global variables. Methods declared as static have several restrictions:

They can only call other static methods. They must only access static data not dynamic data. They can't refer to this or super in any way. As the program is compile static member ,variable or class is loaded first than dynamic class.

A variable can be declared as final, class can't declare final means a final variable must be initialize a final when it is declared.Final Variables don't occupy memory on per-instance basis. Hence, a final variable is must be constant. 7. Examples of final class. Ans-- Final class is only use for prevent a class from being inherited. By declaring a class as final as use final keyword in front of class implicitly declares all of its methods as final too. But, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and depend upon its subclasses to provide complete implementations. //Following example consider for final class package r4r.co.in; final class A { //following class should be declare to final can't be inheritance int a = 5; //value which declare into int should be constant Float b = (float) 3.45; } class B extends A { public static void main(String[] args) { } } 8. What is difference between Event propagation & Event delegation? 9. What is difference between Unicast & Multicast model? 10. What is a java bean? Ans--A Java Bean is a software component that is designed for the reusable in a variety of different environments and itsarchitecture is totally based on a component which enables programmers to create software. Components are selfcontained, reusable software units that can be visually assembled into composite components, applets, applications, and servlets using visual application builder tools. Also, a bean is use to perform a function like checking the spelling of a

document, a complex function such as forecasting the performance of a stock portfolio. Beans expose properties so they can be customized at design time.Customization is supported in two ways: -- by using property editors. -- by using more sophisticated bean customizers. 11. What is use of synchronized keyword? Ans--The synchronized keyword can be used for locking in program or utilize for lock/ free the resource for any thread/program.When two or more threads/program want to access a shared resource, they need someway to ensure that the resource will be use by only one thread at a time. The process by which this is achieved is called synchronization. // Create multiple threads using synchronization method. package r4r.co.in; class MYThread implements Runnable { String name; Thread t; MYThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("My thread: " + t); t.start(); } synchronized public void run() { try { for (int i = 0; i < 10; i++) { System.out.println(name + ": " + i); Thread.sleep(100); } } catch (Exception e) { System.out.println(name + e); } System.out.println(name + " exiting."); } } class MultiThreadDemo { // name of thread

// Thread Start for execution

// Initialization of thread.

//thread sleep

public static void main(String args[]) { new MYThread("One"); new MYThread("Two"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("My thread exiting."); } } 12. What are the restrictions of an applet & how to make the applet access the local machines resources? Ans-13. What is reflect package used for & the methods of it? Ans-- The java.lang.reflect.* package provides the ability to obtain information about the fields, constructors, methods, and modifiers of a class, also includes a class that access arrays dynamically.
//simple example consider for how reflection works, package r4r.co.in; import java.lang.reflect.*; public class Reflection { public static void main(String args[]) { try { Class c = Class.forName("java.lang.String");

// Thread sleep

// Here String is loaded

class.
Method m[] = c.getDeclaredMethods(); implemented System.out.println(m[0].toString()); // Here get method

for (int i = 0; i < m.length; i++) { System.out.println(m[i].toString()); } } catch (Exception e) {

System.out.println(e); } }

14. What is use of serialization? Ans--The process of writing the state of an object to a byte stream is called serialization, also, it is used to save the program to persistent storage area, like a file and easily restore using Deserialization process. 15. Can methods be overloaded based on the return types ? Ans-- Java does not support return-type-based method overloading. Method can be overload either same name and samesignatures( argument/parameter). 16. Why do we need a finalize() method when Garbage Collection is there ? Ans-- Some time an object( which is lost there object reference) is holding some java resource like file handle ,character font, need to free from the resource before that object is collecting by JVM( Java Virtual machine) or say garbage collection. Then to finalize the class, simply define the keyword protected finalize( ) method( protected prevent access of final method) in front of class, Java at the runtime call this object's resource and JVM easily recycle that class. 17. Difference between AWT and Swing components ? Ans--AWT are heavy weight components while Swing are light weight components because AWT is platform dependent while Swing is not dependent any of the platform. Alternate, AWT( heavyweight component ) is one that is associated with its own native screen resource (commonly known as a peer) while Swing( lightweight component ) is one that "borrows" the screen resource of an ancestor ( means it has no native resource of its own). 18. Is there any heavy weight component in Swings ? Ans--Yes, since all AWT components are heavyweight and all Swing components are lightweight (except for the top-level ones: JWindow, JFrame, JDialog, and JApplet), these differences apparent when start mixing Swing components with AWT components. 19. Can the Swing application if you upload in net, be compatible with your browser? Ans-- Yes. because Swing are platform independent independent 20. What should you do get your browser compatible with swing components? 21. What are the methods in Applet ? Ans-- Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web

document. Some Applet method which frequently used-

22. When is init(), start() called ? Ans-- Int() method is called by applet viewer or browser at the time of load applet application into system while Start() method is called by the applet viewer or browser at the time of when applet is complete loaded into system and start its execution. 23. When you navigate from one applet to another what are the methods called? Ans--Applet can be navigate with other by appletcontext() method. 24. What is the difference between Trusted and Untrusted Applet ? Ans-- Java applets are typically executed by Web browsers with embedded Java Virtual Machines (VMs) and runtime class libraries. Applets are downloaded by the browser and then executed by the built-in VM on the machine running the browser. The security of the system depends upon the Java language itself, the

runtime class libraries, and the Security Manager of the browser. Applets are of two types

Trusted Applet:-Java virtual machines( JVM ) run applets under a different security regime( refers to a set of conditions) than applications. By default, applications are implicitly trusted. The designers of the JVM specification assumed that users start applications at their own initiative and can therefore take responsibility for the application's behavior on their machine. Such code is considered to be trusted. Untrusted Applet-The applet which started automatically by the browser after it downloads and displays a page. Users can't be expected to know what applets a page might contain before they download it, and therefore cannot take responsibility for the applet's behavior on their machine. Applets, therefore, are considered by default to be untrusted.

25. What is Exception ? Ans-- An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error must be checked and handled manually. Exceptions can be generated by the Java run-time system (or java virtual machine, JVM ), or they can be manually generated by your code. Exception is of two type1. Check Exception or Compiletime Exception. An exception which generate by programming error like user written program or code and must be handle at time of compilation of program. 2. Uncheck Exception or Runtime Exception. An exception which can generate at the runtime of program, the compiler doesnt force the programmers to catch the exception. 26. What are the ways you can handle exception ? Ans-- When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Try block is used to monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner. To manually throw an exception, use the keyword throw. Any code that must be executed before a method returns is put in a finally block. The following syntax represent exception handling try { // block of code to monitor for errors }

catch (Exception exObject) { // exception handler for ExceptionType1 } finally { // block of code to be executed before try block ends } 27. When is try, catch block used ? Ans--Try block is used to monitor for exceptions, Catch block is used to catch this exception and handle it in some rational manner. The following syntax represent exception handling try { // block of code to monitor for errors } catch (Exception exObject) { // exception handler for ExceptionType1 }

28. What is finally method in Exceptions ? Ans-- The finally method will be executed after a try or catch execution, and mainly used to free up resources. Any code that must be execute before a method returns is put in a finally block. 29. What are the types of access modifiers ? Ans-- In java four access modifier is used describe belowAccess Modifiers* public protected private package( default) Class Yes Yes Yes Yes Nested class Yes Yes No Yes Subclass Other packages Yes Yes No Yes Yes No No No

* The following access modifiers apply to script and instance member like instance functions, script functions, instance variables, and script variables. 32. Is synchronized modifier ? Ans-- Yes, If more than one of your threads running at the same time and access shared objects, then a synchronized keyword is placed in front of Run method, so synchronized should be modify according to the object that call run method. 33. What is meant by polymorphism ? Ans-- Generally, polymorphism is a concept in which a subclass( or child class) can be easily inherited the member (like method, parameter and signature) of superclass (or parent class) but not vice-versa. Polymorphism may be of two kind

Method overloading Method overriding

34. What is inheritance ? 35. What is method Overloading ? What is this in OOPS ? Ans-- when two methods and operator (within different class) have the same name and same arguments , but different signature, it is known as overloading in Object oriented concepts. Two types of are:1. Operator overloading is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments. 2. Function overloading or method overloading is allows to creation the several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the function. Method overloading is usually associated with statically-typed programming languages which enforce type checking in function calls. 36. What is method Overriding ? What is it in OOPS ? Ans-- In overriding, a method in a super class is overridden in the subclass. The method in the subclass will have the same signature as that of the superclass. Since the method in the subclass has the same signature & name as the method of its super class, it is termed as overriding. // example for method overriding package r4r.co.in; class number {

int i, j; number(int a, int b) { i = a; j = b; System.out.println("i and j: " + i + " " + j); } } class numbertest extends number { A. int k; numbertest(int a, int b, int c) { super(a, b); k = a + b + c; //airthmetic sum System.out.println("value of k:" + k); } } class Override { public static void main(String args[]) { numbertest b = new numbertest(1, 2, 3); } } 37. Does java support multi dimensional arrays ? Ans-- Yes, java supported multi dimension array. Example//Syntax for defining multidimensional array var array = new Array(3); for (var i = 0; i < 3; i++) { array[i] = [' ', ' ', ' ']; } //initialization of an array // Create a subclass by extending class

//initilization numbertest

Result array[0][2] = 'x';

array[1][1] = 'x'; array[2][0] = 'x'; 38. Is multiple inheritance used in Java ? Ans-- Java doesn't support multiple inheritance is direct form due to arise the problem of ambiguity( Doubtfulness or uncertainty as regards interpretation), but it support it in term of interface. 40. Does JavaScript support multidimensional arrays ? Ans-- Yes , JavaScript is support multidimensional array. Example--//Syntax for defining multidimensional array var array = new Array(3); for (var i = 0; i < 3; i++) { array[i] = [' ', ' ', ' ']; } //initialization of an array

Result array[0][2] = 'x'; array[1][1] = 'x'; array[2][0] = 'x';

41. Is there any tool in java that can create reports ? Ans--Jesperreport. 43. What is meant by a class ? Ans-- A class is a specification (think of it as a blueprint or pattern and a set of instructions) of how to construct something. 44. What is meant by a method ? Ans-- A method declaration is the heading of a method containing the name of the method, its parameters, and its access level. 45. What are the OOPS concepts in Java ? Ans-- OOPs use three basic concepts as the fundamentals for the programming language: classes, objects and methods. Additionally, Inheritance, Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within object-oriented programming languages. 46. What is meant by encapsulation ? Explain with an example. Ans-- Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.

47. What is meant by inheritance ? Explain with an example. Ans--Inheritance means to take something that is already made. It is one of the most important features of Object Oriented Programming. It is the concept that is used for reusability purpose. Inheritance is the mechanism through which we can derive classes from other classes. The derived class is called as childclass or the subclass or we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used.

50. What is meant by Java interpreter ? Ans-- A small program with interpret java byte code to machine languages. Applets Question 1) What is an Applet? Should applets have constructors? Ans : Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We dont have the concept of Constructors in Applets. Question2) How do we read number information from my applets parameters, given that Applets getParameter() method returns a string? Ans : Use the parseInt() method in the Integer Class, the Float(String) constructor in the Class Float, or the Double(String) constructor in the class Double. Question3) How can I arrange for different applets on a web page to communicate with each other? Ans : Name your applets inside the Applet tag and invoke AppletContexts getApplet() method in your applet code to obtain references to the other applets on the page. Question 4) How do I select a URL from my Applet and send the browser to that page? Ans : Ask the applet for its applet context and invoke showDocument() on that context object. Eg. URL targetURL; String URLString AppletContext context = getAppletContext();

try{ targetUR L = new URL(URLString); } catch (Malformed URLException e){ // Code for recover from the exception } context. showDocument (targetURL); Question 5) Can applets on different pages communicate with each other? Ans : No. Not Directly. The applets will exchange the information at one meeting place either on the local file system or at remote system. Question 6) How do Applets differ from Applications? Ans : Appln: Stand Alone Applet: Needs no explicit installation on local m/c. Appln: Execution starts with main() method. Applet: Execution starts with init() method. Appln: May or may not be a GUI Applet: Must run within a GUI (Using AWT) Question 7) How do I determine the width and height of my application? Ans : Use the getSize() method, which the Applet class inherits from the Component class in the Java.awt package. The getSize() method returns the size of the applet as a Dimension object, from which you extract separate width, height fields.

Eg. Dimension dim = getSize (); int appletwidth = dim.width (); Question 8) What is AppletStub Interface? Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface. Question 9) It is essential to have both the .java file and the .shtmll file of an applet in the same directory. True. False. Ans : 2. Question 10) The <PARAM> tag contains two attributes namely _________ and _______. Ans : Name , value. Question 11) Passing values to parameters is done in the _________ file of an applet. Ans : .shtml. Question 12) What tags are mandatory when creating HTML to display an applet 1. name, height, width 2. code, name 3. codebase, height, width 4. code, height, width Ans : 4. Question 13) Applets getParameter( ) method can be used to get parameter values. a. True. b.False. Ans : a. Question 14) What are the Applets Life Cycle methods? Explain them?

Ans : init( ) method - Can be called when an applet is first loaded. start( ) method - Can be called each time an applet is started. paint( ) method - Can be called when the applet is minimized or refreshed. stop( ) method - Can be called when the browser moves off the applets page. destroy( ) method - Can be called when the browser is finished with the applet. Question 15) What are the Applets information methods? Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy right information, etc. getParameterInfo( ) method : Returns an array of string describing the applets parameters. Question 16) All Applets are subclasses of Applet. a. True. b. False. Ans : a. Question 17) All Applets must import java.applet and java.awt. a. True. b. False. Ans : a. Question 18) What are the steps involved in Applet development? Ans : a) Edit a Java source file, b) Compile your program and c) Execute the appletviewer, specifying the name of your applets source file. Question 19) Applets are executed by the console based Java run-time interpreter. a. True.

b.False. Ans : b. Question 20) Which classes and interfaces does Applet class consist? Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext, AppletStub and AudioClip. Question 21) What is the sequence for calling the methods by AWT for applets? Ans : When an applet begins, the AWT calls the following methods, in this sequence. init( ) start( ) paint( ) Question 22) When an applet is terminated, the following sequence of method cals takes place : stop( ) destroy( ) Question 23) Which method is used to output a string to an applet? Ans : drawString ( ) method. Question 24) Every color is created from an RGB value. a. True. b. False Ans : a.
Ques: 1 I want to learn java connectivity with oracla.How? Ans: You should have Driver for connectivity and 1) Load that driver in your class By help of Class.forNamr(Driver) 2) Than get the connection Connection con = null; con = DriverManger.getDataBaseConnection(url,user,password). 3) Create statement help of connection Statement st = con.createStatement("Select * From tbl......");

4) Execute Statement ResultSet rs = null; rs= st.execute(); 5) Get you result from resultset Enjoy :) .... Vishvesh Richhariya

Ans: By using oracle drivers. in oracle 4 types of drivers are there. U can select any driver.

Java Interview Questions With Answers

AWT: Controls, Layout Managers and Menus Question 1) What is meant by Controls and what are different types of controls? Ans : Controls are componenets that allow a user to interact with your application. The AWT supports the following types of controls: Labels Push buttons Check boxes Choice lists Lists Scroll bars Text components These controls are subclasses of Component. Question 2) You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use? new TextArea(80, 10) new TextArea(10, 80) Ans: b. Question 3) A text field has a variable-width font. It is constructed by calling new TextField("iiiii"). What happens if you change the contents of the text field to "wwwww"? (Bear in mind that is one of the narrowest characters, and w is one of the widest.) a. The text field becomes wider.

b. The text field becomes narrower. c.The text field stays the same width; to see the entire contents you will have to scroll by using the and keys. d.The text field stays the same width; to see the entire contents you will have to scroll by using the text fields horizontal scroll bar. Ans : c. Question 4) The CheckboxGroup class is a subclass of the Component class. a. True b. False Ans : b. Question 5) What are the immediate super classes of the following classes? a) Container class b) MenuComponent class c) Dialog class d) Applet class e) Menu class Ans : a) Container - Component b) MenuComponent - Object c) Dialog - Window d) Applet - Panel e) Menu - MenuItem Question 6) What are the SubClass of Textcomponent Class? Ans : TextField and TextArea Question 7) Which method of the component class is used to set the position and the size of a component? Ans : setBounds() Question 8) Which TextComponent method is used to set a TextComponent to the read-only state? Ans : setEditable()

Question 9) How can the Checkbox class be used to create a radio button? Ans : By associating Checkbox objects with a CheckboxGroup. Question 10) What Checkbox method allows you to tell if a Checkbox is checked? Ans : getState() Question 11) Which Component method is used to access a component's immediate Container? a. getVisible() b getImmediate c.getParent() d.getContainer Ans : c. Question 12) What methods are used to get and set the text label displayed by a Button object? Ans : getLabel( ) and setLabel( ) Question 13) What is the difference between a Choice and a List? Ans : 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. Question 14) Which Container method is used to cause a container to be laid out and redisplayed? Ans : validate( ) Question 15) What is the difference between a Scollbar and a Scrollpane? Ans : A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 16) Which Component subclass is used for drawing and painting? Ans : Canvas. Question 17) Which of the following are direct or indirect subclasses of Component? a. Button b. Label c. CheckboxMenuItem d. Toolbar e. Frame Ans : a, b and e. Question 18) Which of the following are direct or indirect subclasses of Container? a. Frame b.TextArea c MenuBar d.FileDialog e Applet Ans : a,d and e. Question 19) Which method is used to set the text of a Label object? a. setText( ) b. setLabel( ) c. setTextLabel( ) d.setLabelText( ) Ans : a. Question 20) Which constructor creates a TextArea with 10 rows and 20 columns? a. new TextArea(10, 20) b. new TextArea(20, 10) c. new TextArea(new Rows(10), new columns(20)) d. new TextArea(200) Ans : a. Question 21) Which of the following creates a List with 5 visible items and multiple selection enabled?

a. new List(5, true) b. new List(true, 5) c. new List(5, false) d. new List(false,5) Ans : a.

Question 22) Which are true about the Container class? a. The validate( ) method is used to cause a Container to be laid out and redisplayed. b. The add( ) method is used to add a Component to a Container. c. The getBorder( ) method returns information about a Containers insets. d. The getComponent( ) method is used to access a Component that is contained in a Container. Ans : a, b and d. Question 23) Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frames font is set to 12-point TimesRoman, the Panels font is set to 10-point TimesRoman, and the Buttons font is not set, what font will be used to dispaly the Buttons label? a. 12-point TimesRoman b. 11-point TimesRoman c. 10-point TimesRoman d. 9-point TimesRoman Ans : c. Question 24) A Frames background color is set to Color.Yellow, and a Buttons background color is to Color.Blue. Suppose the Button is added to a Panel, which is added to the Frame. What background color will be used with the Panel? a. Colr.Yellow b. Color.Blue c. Color.Green d. Color.White Ans : a. Question 25) Which method will cause a Frame to be displayed? a. show( ) b. setVisible( ) c display( )

d. displayFrame( ) Ans : a and b. Question 26) All the componenet classes and container classes are derived from _________ class. Ans : Object. Question 27) Which method of the container class can be used to add components to a Panel. Ans : add ( ) method. Question 28) What are the subclasses of the Container class? Ans : The Container class has three major subclasses. They are : Window Panel ScrollPane Question 29) The Choice component allows multiple selection. a. True. b. False. Ans : b. Question 30) The List component does not generate any events. a. True. b. False. Ans : b. Question 31) Which components are used to get text input from the user. Ans : TextField and TextArea. Question 32) Which object is needed to group Checkboxes to make them exclusive? Ans : CheckboxGroup. Question 33) Which of the following components allow multiple selections? a. Non-exclusive Checkboxes.

b. Radio buttons. c. Choice. d. List. Ans : a and d. Question 34) What are the types of Checkboxes and what is the difference between them? Ans : Java supports two types of Checkboxes. They are : Exclusive and Nonexclusive. In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other. Question 35) What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panal and the panal subclasses? Ans: A layout Manager is an object that is used to organize components in a container. The different layouts available in java.awt are : FlowLayout, BorderLayout, CardLayout, GridLayout and GridBag Layout. The default Layout Manager of Panal and Panal sub classes is FlowLayout". Question 36) Can I exert control over the size and placement of components in my interface? Ans : Yes. myPanal.setLayout(null); myPanal.setbounds(20,20,200,200); Question 37) Can I add the same component to more than one container? Ans : No. Adding a component to a container automatically removes it from any

previous parent(container). Question 38) How do I specify where a window is to be placed? Ans : Use setBounds, setSize, or setLocation methods to implement this. setBounds(int x, int y, int width, int height) setBounds(Rectangle r) setSize(int width, int height) setSize(Dimension d) setLocation(int x, int y) setLocation(Point p)

Question 39) How can we create a borderless window? Ans : Create an instance of the Window class, give it a size, and show it on the screen. eg. Frame aFrame = ...... Window aWindow = new Window(aFrame); aWindow.setLayout(new FlowLayout()); aWindow.add(new Button("Press Me")); aWindow.getBounds(50,50,200,200); aWindow.show(); Question 40) Can I create a non-resizable windows? If so, how? Ans: Yes. By using setResizable() method in class Frame. Question 41) What is the default Layout Manager for the Window and Window subclasses (Frame,Dialog)?

Ans : BorderLayout(). Question 42) How are the elements of different layouts organized? Ans : FlowLayout : The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout : The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout : The elements of a CardLayout are stacked, one on top of the other, like a deck of cards. GridLayout : The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout : The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Question 43) Which containers use a BorderLayout as their default layout? Ans : The Window, Frame and Dialog classes use a BorderLayout as their default layout. Question 44) Which containers use a FlowLayout as their default layout? Ans : The Panel and the Applet classes use the FlowLayout as their default layout. Question 45) What is the preferred size of a component? Ans : The preferred size of a component size that will allow the component to display normally. Question 46) Which method is method to set the layout of a container? startLayout( ) initLayout( ) layoutContainer( )

setLayout( ) Ans : d. Question 47) Which method returns the preferred size of a component? getPreferredSize( ) getPreferred( ) getRequiredSize( ) getLayout( ) Ans : a. Question 48) Which layout should you use to organize the components of a container in a tabular form? a. CardLayout b. BorederLayout c. FlowLayout d.GridLayout Ans : d. Question 49) An application has a frame that uses a Border layout manager. Why is it probably not a good idea to put a vertical scroll bar at North in the frame? a. The scroll bars height would be its preferred height, which is not likely to be enough. b. The scroll bars width would be the entire width of the frame, which would be much wider than necessary. c. Both a and b. d. Neither a nor b. There is no problem with the layout as described. Ans : c. Question 50) What is the default layouts for a applet, a frame and a panel? Ans : For an applet and a panel, Flow layout is the default layout, whereas Border layout is default layout for a frame. Question 51) If a frame uses a Grid layout manager and does not contain any panels, then all the components within the frame are the same width and height. a. True b. False. Ans : a.

Question 52) If a frame uses its default layout manager and does not contain any panels, then all the components within the frame are the same width and height. a. True b. False. Ans : b. Question 53) With a Border layout manager, the component at Center gets all the space that is left over, after the components at North and South have been considered. a. True b False Ans : b. Question 54) An Applet has its Layout Manager set to the default of FlowLayout. What code would be the correct to change to another Layout Manager? a. setLayoutManager(new GridLayout()); b. setLayout(new GridLayout(2,2)); c. setGridLayout(2,2,)) d. setBorderLayout(); Ans : b. Question 55) How do you indicate where a component will be positioned using Flowlayout? a) North, South,East,West b) Assign a row/column grid reference c) Pass a X/Y percentage parameter to the add method d) Do nothing, the FlowLayout will position the component Ans :d. Question 56) How do you change the current layout manager for a container? a) Use the setLayout method b) Once created you cannot change the current layout manager of a component c) Use the setLayoutManager method d) Use the updateLayout method

Ans :a. Question 57)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement true or false? a) true b) false Ans : b. Question 58) Which of the following statements are true? a)The default layout manager for an Applet is FlowLayout b) The default layout manager for an application is FlowLayout c) A layout manager must be assigned to an Applet before the setSize method is called d) The FlowLayout manager attempts to honor the preferred size of any components Ans : a and d. Question 59) Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu? Ans : itemStateChanged method. Question 60) Which is a dual state menu item? Ans : CheckboxMenuItem. Question 61) Which method can be used to enable/diable a checkbox menu item? Ans : setState(boolean). Question 62) Which of the following may a menu contain? a. A separator b. A check box c. A menu d. A button e. A panel Ans : a and c.

Question 63) Which of the following may contain a menu bar? a. A panel b. A frame c. An applet d. A menu bar e. A menu Ans : b Question 64) What is the difference between a MenuItem and a CheckboxMenuItem? Ans : The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

Question 65) Which of the following are true? a. A Dialog can have a MenuBar. b. MenuItem extends Menu. c. A MenuItem can be added to a Menu. d. A Menu can be added to a Menu. Ans : c and d. Java Networking Interview Questions With Answers

Networking: Question 1) What is the difference between URL instance and URLConnection instance? ANSWER : A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location. Question 2) How do I make a connection to URL? ANSWER : You obtain a URL instance and then invoke openConnection on it.

URLConnection is an abstract class, which means you can't directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL. Eg. URL url; URLConnection connection; try{ url = new URL("..."); conection = url.openConnection(); }catch (MalFormedURLException e) { } Question 3) What Is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--which implement the client side of the connection and the server side of the connection, respectively. Question 4) What information is needed to create a TCP Socket? ANSWER : The Local Systems IP Address and Port Number. And the Remote System's IPAddress and Port Number. Question 5) What are the two important TCP Socket classes? ANSWER : Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class. Question 6) When MalformedURLException and UnknownHostException throws? ANSWER : When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress methods getByName and getLocalHost are unabletoresolve the host name they throwan UnknownHostException

PHP Interview Questions And Answers Page 1


Ques: 1 What are the differences between Get and post methods in form submitting, give the case where we can use get and we can use post methods? Ans: GET Method: Using get method we can able to pass 2K data from HTML.All data we are passing to Server will be displayed on the Browser. This is used to sent small size data. POST Method: 1n this method we does not have any size limitation. All data passed to server will be hidden, User cannot able to see this info on the browser.The data is send into a small packets. This used to sent large amount of data. Ques: 2 What is PHP? Ans: PHP(PHP:Hypertext Preprocessor) is a server-side programing languages.It is use to made the web pages dynamically. PHP is introduce by Rasmus Lerdorf in 1995.It is a free released and open source softwareWe introduce PHP under the HTML tags.In this scripts are executed on server side.It supports many database like that MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc. Ques: 3 Tell more about PHP file? Ans: In PHP file we may contain text, HTML tags and scripts.It returned to the browser in form of plain HTML code.We can save PHP file using these three extension .php,.php3 or .phtml. An Example of PHP file are given below: <html> <head><title>PHPExample</title></head> <body> <h1><?php echo "Welcome in PHP world"; ?></h1> <?php $txt = "This is my first PHP script"; /* statement */ echo $txt; ?> </body> </html> Ques: 4 How PHP is more secure than JavaScript? Ans: We use PHP in a HTML with in some specific tags.It is much secure than JavaScript because of when client process the PHP page than PHP code only send the output of given request without PHP source code.So, the PHP code Can not steal by nonauthorized person.Where in the case of JavaScript It also send the source of JavaScript to the client with output. Ques: 5 What do you understand about MySQL? Ans: MySQL is an open source Relational Database Management System(RDMS).It sound as /ma&#618;&#716;&#603;skju&#720;&#712;&#603;l/ ("My ess cue el").It is introduce in 23May,1995 by MySQLAB,its an Swedish company.Now,is a subsidiary of Sun Microsystems,.MySQL is designed in C and C++.We can download is codes as per rules of GNU(General Public Licence). It fast,reliable and flexible.It works on many platforms like:Uinux,Linux and Windows. Ques: 6 Why we used PHP? Ans: Because of several main reason we have to use PHP. These are:

1.PHP runs on many different platforms like that Unix,Linux and Windows etc. 2.It codes and software are free and easy to download. 3.It is secure because user can only aware about output doesn't know how that comes. 4.It is fast,flexible and reliable. 5.It supports many servers like: Apache,IIS etc. Ques: 7 How to install PHP in our system? Ans: First you have download PHP software from: http://www.php.net/downloads.php than you have to install Database Which you want to use:Like MySQL download from: http://www.mysql.com/downloads/index.html than download server on which you want to work.from: http://httpd.apache.org/download.cgi After install them you will ready to work on PHP. Ques: 8 What is the Syntax of PHP? Ans: Below I will given you how PHP work with HTML codes.Always keep that in mind PHP starts with <?php and close with ?>Their in not a specific place of this block in the HTML code.Like that,<?php/*Enter your code*/?>Now, I have given you a example on PHP. Like that you can create your first PHP file.<html><body><?phpecho \"Welcome in world of PHP.\";?></body></html> Keep one thing in mind when we write PHP code each PHP line should ends with semicolon(;). Ques: 9 Tell me about basic statements that we used in PHP? Ans: PHP has two basic statements.These are echo and print.I have given you a example say how to use echo and print in PHP. Example: <html> <title>This is my first PHP page</title> <body> <?php echo "Welcome!"; ?> </body> </html> //// <html> </body> <?php $decimal_number = 109.09; printf("%.2f", $decimal_number); ?> </body> </html>

Ques: 10 What are the PHP variables? Ans: We use Variables to store the values,Like: Strings, Numbers or Array.In PHP their s no limit to create number of variables.All variable in PHP starts with dollar("$")sign and we assign value to the variable using "=" operator. Syntax: $variable_name = vale; Example: <?php $Name = "Abhi"; $Age = 23;

Ques: 11 What are the Limitations of Variable Naming? Ans: Some main limitations of Variable Naming in PHP are given below: 1.In PHP their is not a fixed limit for Variable Name as compare to other programing language. 2.First letter of PHP Variable must start with a letters,numbers or underscore "_". 3.Variable Name should be a combination of Alpha-Numeric Characters or underscores(a-z,A-Z,0-9or_) 4.Variable name must be one word.If their is more than one word in our Variable Name.Than we can distinguish them with underscore("_").Like $first_name. Ques: 12 How to declare data types in PHP? Ans: Data type that we used in PHP are given below: 1.Numeric data type 2.Array data type 3.String data type 1.Numeric data type: We introduce numeric data type when we use numbers in PHP.Two different types of numeric data types are integer and double. integer data type use to introduce the whole number.Where as double data type use to introduce float values. Example: $intnum = 50; $doublepercentage = 67.9; 2.Array data type: In this we store many values in a single variable.In this we show all values of variable with their variable and index. Example: $arrayMarks[0] = 70; $arrayMarks[1] = 75; $arrayMarks[2] = 65; $intTotalMark = $arrayMarks[0] + $arrayMarks[1] + $arrayMarks[2]; echo $intTotalMark; Output: 210 3.String data type:In this values of variables may be of combination of characters and numbers or words. Examle: $stringName = "Abhi"; $stringId = "Abhi007"; String Concatenation:In thois we can add two strings using "."operator.When we add two strings second string add at the end of first string. Example: $stringFirst_Name = "vivek"; $stringSpace = " "; $stringLast_Name = "agarwal"; $stringName = $stringFirst_Name.$stringSpace.$stringLast_Name; echo $stringName; Output: vivek agarwal

Ques: 13 What is the use of strlen() and strpos() functions? Ans: strlen() function is used to find out the length of the given string.

Example: <?php echo strlen("R4R Welcomes you!"); ?> output: 17 strpos() function is used to match a character or word from the given string.And return the position of the character or word. Example:This program return the position of 'you'. <?php echo strpos("R4R Welcomes you","you"); ?> output: 13 Correct answer is 13 not 14.Because in strpos() function counting starts with 0 not 1. Ques: 14 Tell me about PHP operator? Ans: PHP provide us many operator. These are: 1.Arithmetic Operator 2.Assignment Operator 3.Comparison Operator 4.logical Operator 1.Arithmetic Operator:Some arithmetic operators are given below, Addition('+') m+4 , 8(given m=4) Subtraction('-') m-4, 4(given m=8) Multiplication('*') m*4, 8(given m=2) Division('/') m/4, 2(given m=8) Modulus (division remainder)('%') m%2, 1(given m=3) Increment('++') m++, m=5(given m=4) Decrement('--') m--, m=6(given m=5) 2.Assignment Operator: Some assignment operations are given below, = m=n -= m-=n or m=m-n *= m*=n or m=m*n /= m/=n or m=m/n .= m.=n or m=m.n %= m%=n or m=m%n += m+=n or m=m+n 3.Comparison Operator:Some comparison operators are given below, ==(is equal to) 2==5returns false !=(is not equal to) 2==5returns true >(is greater than) 2==5returns false <(is less than) 2==5returns true >=(greater than or equal to) 2==5returns false <=(is less than or equal to) 2==5returns true 4.Logical Operators:Some logic operators are given below: &&(and) (m<4 && n>2)returns true(given m=3,n=5) ||(or) (m=4 && n=4)returns false(given m=5,n=6) !(not) !(m==n)returns true(given m=2,n=3) Ques: 15 How we use if..else and elseif statement in PHP? Ans: If..else statement is used where we want to execute some code if condition is true otherwise execute some other code. Syntax:

if (condition) code to be executed;//when condition is true else code to be executed;//When condition is false Example: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Weekend!"; else echo "Today!"; ?> </body> </html> Elseif statement is used where we want to execute some code if multiple conditions are true. Syntax: if (condition) code to be executed;//condition is true elseif (condition) code to be executed;//condition is true else code to be executed;//condition is false Example: <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Weekend!"; elseif ($d=="Sun") echo "Sunday!"; else echo "Today!"; ?> </body> </html> Ques: 16 How to use Switch statement in PHP? Ans: If you want to execute more than one code than we use Switch statement. Syntax: switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; }

In this One expression is execute one time.We match a particular value.If it is matched than its correspondent case will executed.When break comes executed case will stopped and command go on next case.If none of the case are executed than default case will executed. Example: <html> <body> <?php switch ($m) { case 1: echo "Number One"; break; case 2: echo "Number Two"; break; case 3: echo "Number Three"; break; default: echo "No number between One and Three"; } ?> </body> </html> Ques: 17 What do you understand array in PHP? Ans: We create array in PHP to solved out the problem of writing same variable name many time.In this we create a array of variable name and enter the similar variables in terms of element.Each element in array has a unique key.Using that key we can easily access the wanted element.Arrays are essential for storing, managing and operating on sets of variables effectively. Array are of three types: 1.Numeric array 2.Associative array 3.Multidimensional array Numeric array is used to create an array with a unique key.Associative array is used to create an array where each unique key is associated with their value.Multidimensional array is used when we declare multiple arrays in an array. Ques: 18 What do you understand about Numeric array, Associative array and Multidimensional array? Ans: Here, I explain Numeric array, Associative array and Multidimensional array in detail: 1. Numeric array:In this array we entered each array element with a unique key.Below I have given you examples how to use Numeric Arrays in PHP. Example: <?php $p_names = array("vivek","abhi","ankit","nik"); echo $p_names[0] . " ," . $p_names[1] . " . $p_names[2] . " and " . $p_names[3] . " are friends"; ?> 'OR' <?php $names[0] = "vivek"; $names[1] = "abhi"; $names[2] = "ankit";

$names[3] = "nik"; echo $p_names[0] . " ," . $p_names[1] . " . $p_names[2] . " and " . $p_names[3] . " are friends"; ?> 2.Associative array:In this array we assign array elements with unique key and their respected values.Below I have given you examples how to use Associative Arrays in PHP. Example: <?php $marks['vivek'] = "90"; $marks['abhi'] = "80"; $marks['ankit'] = "85"; echo "vivek scored" . $marks['vivek'] . " percent in CAT exam."; ?> Output: vivek scored 90 percent in CAT exam. 3.Multidimensional array:In this array we can declare array with in an array. In this multiple arrays has a automatically assign unique key.Below I have given you examples how to use Multidimensional Arrays in PHP. Example: <?php $families = array ( "Agarwal"=>array ( "vivek", "vineet", "abhi" ), "Patel"=>array ( "hariom" ), "Singh"=>array ( "saurabh", "ram", "rohan" ) ); echo "Is " . $families['Agarwal'][0] . " belongs to the Agarwal family?"; ?> Output: Is vivek belongs to the Agarwal family?

Ques: 19 What do you understand about looping in PHP? Ans: Looping uses, when we want to execute some block of code for a specific time.In PHP Looping are of Four types: 1.while 2.do..while 3.for 4.foreach We uses 'while', when we want to execute a block of code till given condition is true.

We uses 'do..while', when we want to execute a block of code at least one.After that it checks the condition if it is true than block of code is execute till condition is true,Other wise stopped the execution. We uses 'for', when we want to execute a block of code many times. We uses 'foreach', when we want to execute a block of code for each element in an array. Ques: 20 How to use while,do..while,for and foreach loop in PHP? Ans: Below I have given u how to use while, do.while, for and foreach loop in PHP. 1.while:Uses, we want to execute a line of code many times till specific condition is true. Syntax: while (condition) code will be executed;//When condition is true Example: <html> <body> <?php $m=3; while($3<=6) { echo "Number is " . $m . "<br />"; $m++; } ?> </body> </html> 2.do..while:Uses, we want to execute a block of code at least one time. After that it checks the condition, till its correct the block of code will executed.Otherwise stopped the execution. Syntax: do { code will be executed; } while (condition);//loop execute atleast one time whenever condition is true or false Example: <html> <body> <?php $m=2; do { $m++; echo "Number is " . $m . "<br />"; } while ($m<7); ?> </body> </html> 3.for:Uses, When we want execute a block of code for some specific times. Syntax: for (initialize; condition; increment/decrement) { code will be executed; } Example: <html>

<body> <?php for ($m=2; $m<=4; $m++) { echo "R4R Welcomes You!<br />"; } ?> </body> </html> 4.foreach:Uses, When When we want execute a block of code for each element in an array. Syntax: foreach (array as value) { code will be executed; } Example: <html> <body> <?php $arr=array("one", "two", "three"); foreach ($arr as $value) { echo "Value: " . $value . "<br />"; } ?> </body> </html

PHP Interview Questions And Answers Page 2


Ques: 21 What do you understand functions in PHP?How we create them? Ans: Functions are one the main property in PHP.It makes PHP useful as compare to others.PHP provides more than 701 in-build functions. How to create Functions in PHP:For creating functions in PHP we have to keep in mind these steps. Step1.To start PHP function with function(). Step2.Suppose if we want set name of function than we can write that after function.?But function name should start with letter or underscore'_'. Step3.After creating PHP function we open a curly brace'{'. Step4.After that write a block of code. Step5.Close PHP function with closed curly brace'}'. When we follow these steps than definitely PHP function will created. Example: <?php function name() { echo "Abhi"; } name(); ?> Ques: 22 How to handle form in PHP?

Ans: When we handle form in PHP keep that most important thing any form element of HTML page will be automatically goes on PHP scripts. Example: <html> <body> <form action="R4R Welcome.php" method="post"><input type="hidden" name="phpMyAdmin" value="f43d4e0b88acea2d2a393515f6bf38f2" /><input type="hidden" name="phpMyAdmin" value="70ac9566533a2665b6597346aab7f985" /> Name: <input type="text" name="Name" /> Password: <input type="password" name="Password" /> <input type="Submit" /> </form> </body> </html> When this code is executed.The value of both fields are display on R4R Welcome.php page. Automatically generated code on R4R Welcome page are: <html> <body> R4R Welcomes You <?php echo $_POST["Name"]; ?>.<br /> Your password is <?php echo $_POST["Password"]; ?> </body> </html> Output: R4R Welcomes You Abhi. Your password is love. Ques: 23 What is form validation?What is Client Side and Server Side validation? Ans: If programmer created a file it should be properly validate.Using form validation we can stop the processing of incorrect input.Because when user enter a invalid input than it may be our form will processed and generated wrong input. We can validate our form on two sides. 1.Client Side 2.Server Side In Client Side we validate form using only JavaScript.In Server Side we create backup for that case when user off the JavaScript of web page or maybe if you uses different web Browsers because they can generate different output of JavaScript that you have written. Client Side validation is much faster than Server Side validation. Some general value that you have to validate when you create form. 1.empty values 2.numbers only 3.input length 4.email address 5.strip HTML tags Ques: 24 How we used $_get and $_post variable in PHP? Ans: $_get is used to retrieve the data_values by using HTTP GET method.When we send the data from get method it will display on URL.It has also a limit to send variables.You can send maximum 100 character from GET method. Example: <form action="R4R Welcome.php" method="get"><input type="hidden" name="phpMyAdmin" value="f43d4e0b88acea2d2a393515f6bf38f2" /><input type="hidden" name="phpMyAdmin" value="70ac9566533a2665b6597346aab7f985" /> Name: <input type="text" name="name" /> Age: <input type="text" name="age" />

<input type="submit" /> </form> When we press submit button than it will send this information on URL. http://www.R4R.co.in/R4R Welcome.php?name=Abhi&age=22 And data_values will collect on R4R Welcome page using $_GET variable. R4R Welcomes You<?php echo $_GET["name"]; ?>.<br /> You are <?php echo $_GET["age"]; ?> years old! We uses $_post variable to send the array of variable names with their data_values using HTTP POST method.When we send data_values from post method than it will not display the data_values on URL & their is no limit to send data_values. Example: <form action="R4R Welcome.php" method="post"><input type="hidden" name="phpMyAdmin" value="f43d4e0b88acea2d2a393515f6bf38f2" /><input type="hidden" name="phpMyAdmin" value="70ac9566533a2665b6597346aab7f985" /> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> When we pressed submit button than URL is looking like that, http://www.R4R.co.in/R4R Welcome.php means that it not display the data_values that you enter.And data_values will collect on R4R Welcome page using $_POST variable. R4R Welcomes You <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old! Ques: 25 When we used $_GET and $_POST variable? Ans: We know that when we use $_GET variable all data_values are display on our URL.So,using this we don't have to send secret data (Like:password, account code).But using we can bookmarked the importpage. We use $_POST variable when we want to send data_values without display on URL.And their is no limit to send particular amount of character. Using this we can not bookmarked the page. Ques: 26 Why we use $_REQUEST variable? Ans: We use $_REQUEST variable in PHP to collect the data_values from $_GET,$_POST and $_COOKIE variable. Example: R4R Welcomes You <?php echo $_REQUEST["name"]; ?>.<br /> You are <?php echo $_REQUEST["age"]; ?> years old! Ques: 27 Why we use Date() function in PHP and How? Ans: We use Data() function in PHP to format the local time and date. Syntax: string date( string $format[, int $timestamp ]) Where,timestamp is optional.Timestamp is the no of seconds after 1st Jan,1970 at 00:00:00 GMT. Example: <?php echo Date("Year/month/date"); echo "<br />"; echo Date("Year.month.date"); echo "<br />"; echo Date("Year-month-date"); ?> Ques: 28 Why we used Server Side include function?

Ans: We use Server Side Include(SSL) to create functions,footer,header or elements.For multiple reuse those on different pages.In this we uses two functions include() and require().Both functions are same except how they handle errors. 1.include() function 2.require() function 1.include() function:When error comes it show warning but not stop the execution of JavaScript. 2.require() function:When error comes it show fatal error and also stop the execution of JavaScript. Ques: 29 How we use include() and require() function in PHP? Ans: When we use include() function it will contain all the text into a file and this will send to a file when we use include() function. Example: <html> <body> <?php include("CorruptFile.php"); echo "R4R Welcomes You!"; ?> </body> </html> By using include() function is use to include the header file in a page.It will generate warning but not stopped the execution of JavaScript. When we use require() function it will contain all the text into a file and this will send to a file when we use require() function. Example: <html> <body> <?php require("CorruptFile.php"); echo "R4R Welcomes You!"; ?> </body> </html> It will generate warning and also stopped the execution of JavaScript. Ques: 30 How to use File Handling in PHP? Ans: We Done File Handling in PHP by using fopen() function. Example: <html> <body> <?php $file=fopen("R4R Welcome.doc","r"); ?> </body> </html> first parameter of fopen use for which file you want to open and the second parameter use for which mode you want to perform on that file(Like:read,write,append etc). Ques: 31 What types of modes we use in PHP for File Handling? Ans: Some modes that we use in PHP are given below: 1.r :This perform only read operation and start at the beginning of file.

2.r+ :This perform both read and write operation and start at the beginning of file. 3.w :This perform only write operation.we can open and create the content of file.If file is not exist creates a new file. 4.w+ :This perform both read and write operation. we can open and create the content of file.If file is not exist creates a new file. 5.a :We can open and append the content of file. If file is not exist creates a new file. 6.a+ :We can open,read and append the content of file. 7.x :This perform only write operation.Also create new files.It will show error or return False when file is already exist. 8.x+ :This perform both read and write operation. Also create new files.It will show error or return False when file is already exist. Ques: 32 How we use fopen(),fclose(),feof(),fgets() and fgetc()in PHP? Ans: fopen() function is use to open a file in a specific mode(read write etc.). <html> <body> <?php $R4R_file=fopen("R4R Welcome.doc","r"); ?> </body> </html> fclose() function is use to close the file. <?php $R4R_file = fopen("R4R Welcome.doc","r"); //block of code fclose($R4R_file); ?> feof() is used to confirmed that 'end-of-file' has been achieved. if (feof($R4R_file)) echo "End of file"; fgets() is used when we want to read a single line from the file. <?php $R4R_file = fopen("R4R Welcome.doc", "r") ; while(!feof($R4R_file)) { echo fgets($R4R_file). "<br />"; } fclose($R4R_file); ?> fgetc() is used when we want to read a single character from the file. <?php $R4R_file=fopen("R4R Welcome.doc","r"); while (!feof($R4R_file)) { echo fgetc($R4R_file); } fclose($R4R_file); ?> Ques: 33 What you know about Cookie? Ans: We use cookie to authenticate the client.Cookie file is attached with the client computer browser.Every time client computer sends the requested page with their cookies. Their is advantage in PHP.In this we can create and retrieve the cookies values. We can create the cookie using setcookie () function. Syntax:

setcookie(Cookie_Name, Cookie_Value, expire_time, path, domain); Ques: 34 What operation we can perform with Cookie?Explain it? Ans: We can create the cookie,retrieve heir value and destroy them. 1.Creating a cookie: Using setcookie() function we can create a cookie. Example: <?php setcookie("client", "Abhi", time()+3600); ?> <html> ..... ..... 2.Retrieve cookie value: Using $_COOKIE we can retrieve the cookie value. Example: <?php // Print a cookie value echo $_COOKIE["client"]; // Using them we show the all cookie values print_r($_COOKIE); ?> 3.Destroy the cookie: Keep one thing in mind when you destroying cookie that its expiry date should has been gone. Example: <?php // set the expiration date to one hour ago setcookie("client", "", time()-3600); ?> Ans: We can create the cookie,retrieve heir value and destroy them. 1.Creating a cookie: Using setcookie() function we can create a cookie. Example: <?php setcookie("client", "Abhi", time()+3600); ?> <html> ..... ..... 2.Retrieve cookie value: Using $_COOKIE we can retrieve the cookie value. Example: <?php // Print a cookie value echo $_COOKIE["client"]; // Using them we show the all cookie values print_r($_COOKIE); ?> 3.Destroy the cookie: Keep one thing in mind when you destroying cookie that its expiry date should has been gone. Example: <?php // set the expiration date to one hour ago setcookie("client", "", time()-3600); ?> Ques: 35 How we Sessions in PHP? Ans: We use session variable to store information or change setting about client session.A session variable is assign to the each client. Session has a particular working cycle like that 1.It create a unique id for each client

2.Store session variable according to client uniquw id. 3.Unique id stored in cookie. Ans: We use session variable to store information or change setting about client session.A session variable is assign to the each client. Session has a particular working cycle like that 1.It create a unique id for each client 2.Store session variable according to client unique id. 3.Unique id stored in cookie. Ans: We use session variable to store information or change setting about client session.A session variable is assign to the each client. Session has a particular working cycle like that 1.It create a unique id for each client 2.Store session variable according to client unique id. 3.Unique id stored in cookie. Ans: We use session variable to store information or change setting about client session.A session variable is assign to the each client. Session has a particular working cycle like that 1.It create a unique id for each client 2.Store session variable according to client unique id. 3.Unique id stored in cookie. Ques: 36 How we handle errors in PHP?Explain it? Ans: In PHP we can handle errors easily.Because when error comes it gives error line with their respective line and send error message to the web browser. When we creating any web application and scripts. We should handle errors wisely.Because when this not handle properly it can make bg hole in security. In PHP we handle errors by using these methods: 1.Simple "die()" statements 2.Custom errors and error triggers 3.Error reporting Ques: 37 How we use Simple "die()" statements error handling method in PHP? Ans: I have given you a example.In this we try to open a file. <?php $file=fopen("R4R Welcome.txt","r"); ?> Suppose if that file does not exist,Than this type of message comes. fopen(R4R Welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\PHP\Welcome.php on line 2 Now, we handle this error like that, <?php if(!file_exists("R4R Welcome.txt")) { die("File does not exist"); } else { $file=fopen("R4R Welcome.txt","r"); } ?> If file does not exist than output comes like that, File does not exist Ques: 38 How we use Custom errors and error triggers error handling method in PHP? Ans: In Custom errors and error triggers,we handle errors by using self made functions.

1.Custom errors : By using this can handle the multiple errors that gives multiple message. Syntax: set_error_handler(\\\"Custom_Error\\\"); In this syntax if we want that our error handle, handle only one error than we write only one argument otherwise for handle multiple errors we can write multiple arguments. Example: <?php //function made to handle errorfunction custom_Error($errorno, $errorstr) { echo \\\"<b>Error:</b> [$errorno] $errorstr\\\"; } //set error handler like that set_error_handler(\\\"custom_Error\\\"); //trigger to that error echo($verify);?> 2.error trigger : In PHP we use error trigger to handle those kind of error when user enter some input data.If data has an error than handle by error trigger function. Syntax: <?php $i=0;if ($i<=1) { trigger_error(\\\"I should be greater than 1 \\\"); } ?> In this trigger_error function generate error when i is less than or greater than 1. Ques: 39 How we use Error logging error handling method in PHP? Ans: In PHP,by default an error log send to the error log system.By using error logging we can send and error log to the specific file. We checked this by using an example.In this we send a mail to our self with error message.And the scripts does not work when error comes. Example: <?php //error handler function function customError($errorno, $errorstr) { echo "<b>Error:</b> [$errno] $errorstr<br />"; echo "program has been notified"; error_log("Error: [$errorno] $errorstr",1, "abc@xyz.com","From: program@xyz.com"); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $i=0; if ($i<=1) { trigger_error("I should be greater than 1", E_USER_WARNING); } ?> o/p: [512] I should be greater than 1 program has been notified

Our mail have reply message like that, Error: [512] I should be greater than 1 Ques: 40 What do you understand about Exception Handling in PHP? Ans: In PHP 5 we introduce a Exception handle to handle run time exception.It is used to change the normal flow of the code execution if a specified error condition occurs. An exception can be thrown, and caught("catched") within PHP. Write code in try block,Each try must have at least one catch block. Multiple catch blocks can be used to catch different classes of exceptions. I have shown some error handler methods given below: 1.Basic use of Exceptions 2.Creating a custom exception handler 3.Multiple exceptions 4.Re-throwing an exception 5.Setting a top level exception handle

PHP Interview Questions And Answers Page 1


Ques: 1 how can we connect more than one database into webpage.. Ques: 2 PHP means? uses of PHP? types of PHP? explain PHP? Ques: 3 How session will work when we disable cookies of client browser? Ans: Session is kind of cookie who is work on server side.For working of session on server side cookies should be enable on server side and also on client side browser. But session will also work when cookies are disable on client side by using URL session passing. Ques: 4 How we use array_search() in PHP? Ans: When we use array_search() function if it found the particular value than it will return index corresponding to array value. Example: <?php $Emp_name_array = array(0 => 'vivek', 1 => 'umang', 2 => 'shrish', 3 => 'jalees'); $key = array_search('umang', $Emp_name_array); // return $key = 1; $key = array_search('vivek', $Emp_name_array); // return $key = 0; ?> Ques: 5 How you differentiate among sort(),assort() and Ksort()? Ans: 1) sort() This function sorts an array. Elements will be arranged from lowest to highest when this function has completed. <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; }

?> ----------------------------OUTPUT--------------------fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange ------------------------------------------------------2) asort() This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> --------------------OUTPUT-----------------------c = apple b = banana d = lemon a = orange -------------------------------------------------3) ksort() Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays. <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> --------------------OUTPUT---------------------------a = orange b = banana c = apple d = lemon -----------------------------------------------------Ans: The sort() function sort the array. Element will arranged in lowest to highest when function has completed. The assort() function sort the associative arrays and where the actual element order is significant. The Ksort() function sort an array by key. This is useful for associative array.

Ans: Sort-sorting arry <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Assort-Sort an array and maintain index association <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> The above example will output: c = apple b = banana d = lemon a = orange ksort Sort an array by key <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> The above example will output: a = orange b = banana c = apple d = lemon Ans: Sort-sorting arry <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n";

} ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Assort-Sort an array and maintain index association <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); asort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> The above example will output: c = apple b = banana d = lemon a = orange ksort Sort an array by key <?php $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); ksort($fruits); foreach ($fruits as $key => $val) { echo "$key = $val\n"; } ?> The above example will output: a = orange b = banana c = apple d = lemon Ans: sort() -> sorting the value in ascending.d assort() -> sorting only the value. Example: $x=array([0]=>32,[1]=>11,[2]=>10) print_r(asort($x); means: [2]=>10,[1]=>11,[0]=>32 Ksort() -> Sorting only key not value Ans: In array we can get both key value and array value.key is refer for index,array is what we are storing.sort() use to sort in ascendending array value.arsort() user array in reverse order. ksort means key valuesare arranged in ascending order Ans: sort() will order the array by its values without preserving the keys. Use it when array is indexed numerically or when you do not care about the keys. asort() will also sort the array by its values, but it will preserve the key -> value association. The ksort() function sorts an array by the keys. The values keep their original keys.

This function returns TRUE on success, or FALSE on failure. Ans: The sort() function sorts an array by the values. This function assigns new keys for the elements in the array. Existing keys will be removed. This function returns TRUE on success, or FALSE on failure. The asort() function sorts an array by the values. The values keep their original keys. This function returns TRUE on success, or FALSE on failure. The ksort() function sorts an array by the keys. The values keep their original keys. This function returns TRUE on success, or FALSE on failure. Ans: bool sort ( array &$array [, int $sort_flags] ) This function sorts an array. Elements will be arranged from lowest to highest when this function has completed. Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys. Returns TRUE on success or FALSE on failure. Example 329. sort() example <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Ans: bool sort ( array &$array [, int $sort_flags] ) This function sorts an array. Elements will be arranged from lowest to highest when this function has completed. Note: This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys. Returns TRUE on success or FALSE on failure.

Example 329. sort() example <?php $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ?> The above example will output: fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange Ans: sort() void sort(array target_array [, int sort_flags]) The sort() function sorts the target_array, ordering elements from lowest to highest value. Note that it doesnt return the sorted array. Instead, it sorts the array in place, returning nothing, regardless of outcome. The optional sort_flags parameter modifies the functions default behavior in accordance with its assigned value: SORT_NUMERIC: Sort items numerically. This is useful when sorting integers or floats. SORT_REGULAR: Sort items by their ASCII value. This means that B will come before a, for instance. A quick search online will produce several ASCII tables. SORT_STRING: Sort items in a fashion that might better correspond with how a human might perceive the correct order. See natsort() for further information about this matter, introduced later in this section. Consider an example. Suppose you wanted to sort exam grades from lowest to highest: $grades = array(42,57,98,100,100,43,78,12); sort($grades); print_r($grades); The outcome looks like this: Array ( [0] => 12 [1] => 42 [2] => 43 [3] => 57 [4] => 78 [5] => 98 [6] => 100 [7] => 100 ) Its important to note that key/value associations are not maintained. Consider the following example: $states = array("OH" => "Ohio", "CA" => "California", "MD" => "Maryland"); sort($states); print_r($states); Heres the output: Array ( [0] => California [1] => Maryland [2] => Ohio ) Ans: sort destroy key association asort keeps key association of values. ksost sort the key value only Ques: 6 How to print \ in php with out using . or *?. Ans: I have given you a example which definitely solved your query. Example: <?php

print "\\"; ?> output: \\ Ans: <?php echo "\\"; ?> Ans: \ for slah and * for adding values Ques: 7 Why is PHP-MySQL used for web Development? Ans: We use PHP-MySQL in web development because both are open source means both free to use. Both when MySQL work with PHP it gives result much faster than when MySQL work with Java/.Net/Jsp. Ques: 8 What function we used to change timezone from one to another ? Ans: I have given you a function using them we can change a timezone into another timezone. date_default_timezone_set() function Example: date_default_timezone_set('India'); And we use date_default_timezone_get() function to get the entered date. Ques: 9 How do you understand about stored procedure,Triggers and transaction in php? Ans: Below I have given how stored procedure,Triggers and transaction work in PHP: 1.Stored Procedure: It is combination of some SQL commands it is stored and can be compiled.Suppose that when user is executed a command than user has don't need to reissue the entire query he can use the stored procedure.Basically main reason to use the stored procedure is that using this we can decrease the time of reissue of that query. Because work done on server side is more than the work done on application side. 2.Trigger: Trigger is a stored procedure.This is used to work stored procedure effectively.It is invoked when a special type of event comes.For effectively understand this i have given you a example. When we attach a trigger with stored procedure than when we delete a record from transaction table than will automatically work and delete the respective client from client table. 3.Transaction: Transaction is that in which particular amount of data goes from the a client to the another client.We maintain the transaction record into a table called transaction table. Ques: 10 How we can upload videos using PHP? Ans: When want to upload videos using PHP we should follow these steps: 1.first you have to encrypt the the file which you want to upload by using "multipartform-data" to get the $_FILES in the form submition. 2.After getting the $_FILES['tmp_name'] in the submition 3.By using move_uploaded_file (tmp_location,destination) function in PHP we can move the file from original location. Ques: 11 How can we create a database using PHP and myqsl? Ans: I have given you a example using this you can create a database. <?php

$con =mysql_connect("localhost","vivek","vivabh"); if (!$con) { die('Could not connect: ' . mysql_error()); } if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database has been created"; } else { echo "Error to create database: " . mysql_error(); } mysql_close($con); ?> Ques: 12 What do you understand about Joomala in PHP? Ans: Joomala is an content management system who is programmed with PHP.Using this we can modified the PHP sit with their content easily. Ques: 13 How you can differentiate abstract class and interface? Ans: There are some main difference between abstract and interface are given below: 1.In an abstract we can use sharable code where in the case of interface their is no facility to use sharable code. 2.In which class we implement an interface class. All method that we use should be defined in interface. Where as class those extending an abstract while a class extending an abstract class their is no need to defined methods in the abstract class. Ques: 14 What do you understand about Implode and Explode functions? Ans: The main difference b/w Implode and Explode functions is that We use Implode function to convert the array element into string where each value of array is separated by coma(,). Example: <?php $array = array('First_Name', 'Email_Id', 'Phone_NO'); $comma_separated_string = implode(",", $array); echo $comma_separated_string; ?> output: First_Name,Email_Id,Phone_No We use Explode function to convert the string value those are separated with coma(,) into array. Example: <?php $comma_separated_string = string('First_Name,Email_Id,Phone_No'); $array = Explode(",", $coma_separated_string); echo $array; ?> output: First_Name Email_Id Phone_No Ques: 15 Can we submit a form without submit button? Ans: Using JavaScript we can submit a form without submit button. Example:

document.FORM_NAME.action="Welcome.php"; document.FORM_NAME.submit();//this is used to submit the form Ques: 16 Can I develop our own PHP extension?if yes,how? Ans: Yes,we can develop a PHP extension like that, Example: <? echo 'PHP'; ?> To save this file as .php extention Ques: 17 What do you understand by nl2br()? Ans: nl2br() function is stands for new line to break tag. Example: echo nl2br("R4R Welcomes\nYou"); output: R4R Welcomes you Ques: 18 How function strstr and stristr both work in PHP? Ans: Generally, Both function strstr and stristr are same except one thing stristr is a case sensitive where as strstr is an non-case sensitive.We use strstr to match the given word from string. Syntax: syntax: strstr(string,match word) Examle: <?php $email_id = 'abc@xyz.com'; $id_domain = strstr($email_id, '@'); echo $id_domain; ?> output: @xyz.com Ques: 19 In PHP can I get the browser properties? Ans: Using get_browser function we can get the browser properties in PHP. Example: $browser_properties = get_browser(null, true); print_r($browser_properties); Ques: 20 How we can increase the execution time of a PHP script? Ans: I have given you some function using them you can increase the execution time of a PHP script.Default time for execution of a PHP script is 30 seconds. These are, 1.set_time_limit()//change execution time temporarily. 2.ini_set()//change execution time temporarily. 3. By modifying `max_execution_time' value in PHP configuration(php.ini) file.//change execution time permanent

ASP.net Interview Questions And Answers

Page 1

Ques: 1 How to Configure SMTP in asp .NET? Ans: This example specifies SMTP parameters to send e-mail using a remote SMTP server and user that are importent. This program shows configuration process<system.net> <mailSettings> <smtp deliveryMethod="Network|PickupDirectoryFromIis|SpecifiedPickupDirec> <network defaultCredentials="true|false" from="r4r@fco.in" host="smtphost" port="26" password="password" userName="user"/> <specifiedPickupDirectory pickupDirectoryLocation="c:\pickupDirectory"/> </smtp> </mailSettings> </system.net> Ques: 2 Print Hello World message using SharePoint in Asp.Net 2.0? Ans: using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MYWP : WebPart { protected override void CreateChildControls() { Content obj = new Content(); string str1 = obj.MyContent<string>("Hello World!"); this.Controls.Add(new System.Web.UI.LiteralControl(str1)); } } } generic method shows that SharePoint site is running on .NET Framework 2.0, and the code of the generic method seems like this: public string MyContent<MyType>(MyType arg) { return arg.ToString(); } Ques: 3 How to create a SharePoint web part using File upload control.give example? Ans: using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls;

using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MYWP : WebPart { FileUpload objFileUpload = new FileUpload(); protected override void CreateChildControls() { this.Controls.Add(new System.Web.UI.LiteralControl ("Select a file to upload:")); this.Controls.Add(objFileUpload); Button btnUpload = new Button(); btnUpload.Text = "Save File"; this.Load += new System.EventHandler(btnUpload_Click); this.Controls.Add(btnUpload); } private void btnUpload_Click(object sender, EventArgs e) { string strSavePath = @"C:\temp\"; if (objFileUpload.HasFile) { string strFileName = objFileUpload.FileName; strSavePath += strFileName; objFileUpload.SaveAs(strSavePath); } else { //otherwise let the message show file was not uploaded. } } } } Ques: 4 What is BulletedList Control in Share Point. Give an example? Ans: Bullet style allow u choose the style of the element that precedes the item.here u can choose numbers, squares, or circles.here child items can be rendered as plain text, hyperlinks, or buttons. This example uses a custom image that requires to be placed in a virtual directory on the server. using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MyWP : WebPart { protected override void CreateChildControls { BulletedList objBullist = new BulletedList(); objBullist.BulletStyle = BulletStyle.CustomImage; objBullist.BulletImageUrl = @"/_layouts/images/rajesh.gif"; objBullist.Items.Add("First");

objBullist.Items.Add("Seciond"); objBullist.Items.Add("Third"); objBullist.Items.Add("Fourth"); this.Controls.Add(objBullist); } } } Ques: 5 DescribeWizard server control with example in Share Point? Ans: This control enables you to build a sequence of steps that are displayed to the end users side. It is alos used either display or gather information in small steps in system. using System; using System.Collections.Generic; using System.Text; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Microsoft.SharePoint.WebPartPages; namespace LoisAndClark.WPLibrary { public class MyWP : WebPart { protected override void CreateChildControls() { Wizard objWizard = new Wizard(); objWizard.HeaderText = "Wizard Header"; for (int i = 1; i <= 6; i++) { WizardStepBase objStep = new WizardStep(); objStep.ID = "Step" + i; objStep.Title = "Step " + i; TextBox objText = new TextBox(); objText.ID = "Text" + i; objText.Text = "Value for step " + i; objStep.Controls.Add(objText); objWizard.WizardSteps.Add(objStep); } this.Controls.Add(objWizard); } } } Ques: 6 Define Life Cycle of Page in ASP.NET? Ans: protected void Page_PreLoad(object sender, EventArgs e) { Response.Write("<br>"+"Page Pre Load"); } protected void Page_Load(object sender, EventArgs e) { Response.Write("<br>" + "Page Load"); } protected void Page_LoadComplete(object sender, EventArgs e) {

Response.Write("<br>" + "Page Complete"); } protected void Page_PreRender(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Render"); } protected void Page_Render(object sender, EventArgs e) { Response.Write("<br>" + "Pre Render"); } protected void Page_PreInit(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Init"); } protected void Page_Init(object sender, EventArgs e) { Response.Write("<br>" + "Page Init"); } protected void Page_InitComplete(object sender, EventArgs e) { Response.Write("<br>" + "Page Pre Init Complete"); } Ques: 7 Write a program in ASP.NET to Show Data With Access? Ans: Page_Load():OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("select * from emp", x); z = y.ExecuteReader(); while (z.Read()) { Response.Write(z["ename"]); Response.Write("<hr>"); } z.Close(); y.Dispose(); x.Close(); } Ques: 8 Write a program to show connection with Oracle in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) { x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger"); x.Open(); y = new OleDbCommand("select * from emp", x); z = y.ExecuteReader();

while (z.Read()) { Response.Write("<li>"); Response.Write(z["ename"]); } z.Close(); y.Dispose(); x.Close(); } Ques: 9 Write a program to show connection to Excel in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; OleDbDataReader z; protected void Page_Load(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\book1.xls;Extended Properties=excel 8.0"); x.Open(); y = new OleDbCommand("select * from [sheet1$]", x); z = y.ExecuteReader(); while (z.Read()) { Response.Write("<li>"); Response.Write(z["ename"]); } z.Close(); y.Dispose(); x.Close(); } Ques: 10 How to add Record in ASP.NET? Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("Insert into emp(empno,ename,sal) values(@p,@q,@r)", x); y.Parameters.Add("@p", TextBox1.Text); y.Parameters.Add("@q", TextBox2.Text); y.Parameters.Add("@r", TextBox3.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Addedd"; y.Dispose(); x.Close(); } Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) {

x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("Insert into emp(empno,ename,sal) values(@p,@q,@r)", x); y.Parameters.Add("@p", TextBox1.Text); y.Parameters.Add("@q", TextBox2.Text); y.Parameters.Add("@r", TextBox3.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Addedd"; y.Dispose(); x.Close(); } Ques: 11 Write a program to Delete Record in ASP.NET ? Ans: OleDbConnection x; OleDbCommand y; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=c:\\db1.mdb"); x.Open(); y = new OleDbCommand("delete from emp where empno=@p",x); y.Parameters.Add("@p", TextBox1.Text); y.ExecuteNonQuery(); Label1.Visible = true; Label1.Text="Record Deleted"; y.Dispose(); x.Close(); } Ques: 12 Write a program to show data in Gridview in ASP.NET? Ans: OleDbConnection x; OleDbDataAdapter y; DataSet z; protected void Button2_Click(object sender, EventArgs e) { x = new OleDbConnection("provider=msdaora;user id=scott;password=tiger"); x.Open(); y = new OleDbDataAdapter("select * from emp", x); z = new DataSet(); y.Fill(z, "emp"); GridView1.DataSource = z.Tables["emp"]; GridView1.DataBind(); y.Dispose(); x.Close(); } Ques: 13 Write a Program to Connect with dropdownlist in ASP.NET Ans: OleDbConnection x; OleDbDataAdapter y;

DataSet z; protected void Button1_Click(object sender, EventArgs e) { x = new OleDbConnection("Provider=msdaora;user id=scott;password=tiger"); x.Open(); y=new OleDbDataAdapter("select * from emp",x); z = new DataSet(); y.Fill(z, "emp"); DropDownList1.DataSource = z; DropDownList1.DataTextField = "ename"; DropDownList1.DataBind(); x.Close(); } Ques: 14 How Repeater is used in ASP.NET? Ans: <asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "Empno") %> <%#DataBinder.Eval(Container.DataItem, "Ename") %> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </ItemTemplate> </asp:Repeater> //the whole structure looks like this <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> Employee Detailed </HeaderTemplate> <ItemTemplate> <font color=gray> <%#DataBinder.Eval(Container.DataItem, "Empno") %> <%#DataBinder.Eval(Container.DataItem, "Ename") %> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </font> </ItemTemplate> <AlternatingItemTemplate> <font color=green> <%#DataBinder.Eval(Container.DataItem, "Empno") %> <%#DataBinder.Eval(Container.DataItem, "Ename") %> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </font> </AlternatingItemTemplate> <FooterTemplate> Thanks </FooterTemplate> <SeparatorTemplate> <hr/> </SeparatorTemplate> </asp:Repeater> Ques: 15 How to show data in HTML table using Repeater? Ans: <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> <table border="10" width="100%" bgcolor=green style="width:100%" > <tr> <th>Empno</th> <th>Ename</th> <th>Sal</th>

</tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <%#DataBinder.Eval(Container.DataItem, "Empno") %> </td> <td> <%#DataBinder.Eval(Container.DataItem, "Ename") %> </td> <td> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </td> </tr> </font> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </td> <td style="width: 100px; height: 226px"> </td> </tr> </table> Ans: dfd Ques: 16 Write a program to show the Use of dataList in ASP.NET? Ans: <asp:DataList ID="DataList1" runat="server" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" GridLines="Both"> <HeaderTemplate>Employee Detailed</HeaderTemplate> <ItemTemplate> <%#DataBinder.Eval(Container.DataItem, "Empno") %> <%#DataBinder.Eval(Container.DataItem, "Ename") %> <%#DataBinder.Eval(Container.DataItem, "Sal") %> </ItemTemplate> Ques: 17 How to make User Control in ASP.net? Ans: a)Add User Controll write code:<hr color=red/> <center><H1><SPAN style="COLOR: #ff9999; TEXT-DECORATION: underline">BigBanyanTree.com</SPAN></H1></center> <hr Color=Green/> b)In .aspx page:<%@ Register TagPrefix=a TagName="MyUserCtl" Src="~/WebUserControl.ascx"%>

c)Now use this :<a:MyUserCtl ID="tata" runat=server/>

Ques: 18 How to create voting poll system in asp.net which allows user to see the results? Ques: 19 What is Benefits of ASP.NET? Ans: >>Simplified development: ASP.NET offers a very rich object model that developers can use to reduce the amount of code they need to write. >>Web services: Create Web services that can be consumed by any client that understands HTTP and XML, the de facto language for inter-device communication. >>Performance: When ASP.NET page is first requested, it is compiled and cached, or saved in memory, by the .NET Common Language Runtime (CLR). This cached copy can then be re-used for each subsequent request for the page. Performance is thereby improved because after the first request, the code can run from a much faster compiled version. >>Language independence >>Simplified deployment >>Cross-client capability Ques: 20 What is ASP.Net? Ans: ASP Stands for Active server Pages.ASP used to create interacting web pages

P.net Interview Questions And Answers Page 1


Ques: 1 What does the keyword virtual declare for a method? Ans: The method or property can be overridden. Ques: 2 Tell me implicit name of the parameter that gets passed into the set property of a class? Ans: The data type of the value parameter is defined by whatever data type the property is declared as. Ques: 3 What is the difference between an interface and abstract class ? Ans: 1. In an interface class, all methods are abstract and there is no implementation. In an abstract class some methods can be concrete. 2. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers. Ques: 4 How to Specify the accessibility modifier for methods inside the interface? Ans: They all must be public, and are therefore public by default. Ques: 5 Define interface class ?

Ans: Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Ques: 6 When you declared a class as abstract? Ans: 1. When at least one of the methods in the class is abstract. 2. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden. Ques: 7 Define abstract class? Ans: 1. A class that cannot be instantiated. 2. An abstract class is a class that must be inherited and have the methods overridden. 3. An abstract class is essentially a blueprint for a class without any implementation Ques: 8 How to allowed a class to be inherited, but it must be prevent the method from being over-ridden? Ans: Just leave the class public and make the method sealed. Ques: 9 How to prevent your class from being inherited by another class? Ans: We use the sealed keyword to prevent the class from being inherited. Ques: 10 What class is underneath the SortedList class? Ans: A sorted HashTable. Ques: 11 What is the .NET collection class that allows an element to be accessed using a unique key? Ans: HashTable. Ques: 12 Difference between the System.Array.Clone() and System.Array.CopyTo()? Ans: The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object. Ques: 13 Difference between System.String and System.Text.StringBuilder classes? Ans: System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed. Ques: 14 What is the top .NET class that everything is derived from? Ans: System.Object. Ques: 15 How can you automatically generate interface for the remotable object in .NET? Ans: Use the Soapsuds tool. Ques: 16 How to configure a .NET Remoting object via XML file? Ans: It can be done via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.

Ques: 17 What is Singleton activation mode? Ans: A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease. Ques: 18 What security measures exist for .NET Remoting? Ans: None. Ques: 19 In .NET Remoting, What are channels? Ans: Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred. Ques: 20 What are remotable objects in .NET Remoting? Ans: 1. They can be marshaled across the application domains. 2. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed. Ques: 21 How does cookies work in ASP.Net? Ans: Using Cookies in web pages is very useful for temporarily storing small amounts of data, for the website to use. These Cookies are small text files that are stored on the user's computer, which the web site can read for information; a web site can also write new cookies. An example of using cookies efficiently would be for a web site to tell if a user has already logged in. The login information can be stored in a cookie on the user's computer and read at any time by the web site to see if the user is currently logged in. This enables the web site to display information based upon the user's current status - logged in or logged out. Ques: 22 Difference Between Thread and Processs? Ans: Process is a program in execution where thread is a seprate part of execution in the program. Thread is a part of process. process is the collection of thread. Ques: 23 What is the difference between an EXE and a DLL? Ans: DLL:Its a Dynamic Link Library .There are many entry points. The system loads a DLL into the context of an existing thread. Dll cannot Run on its own EXE:Exe Can Run On its own.exe is a executable file.When a system launches new exe, a new process is created.The entry thread is called in context of main thread of that process. Ques: 24 Difference bt ASP and asp.net? Ans: 1.Asp .net is compiled while asp is interpreted. 2.ASP is mostly written using VB Script and HTML. while asp .net can be written in C#, J# and VB etc. 3.Asp .net have 4 built in classes session , application , request response, while asp .net have more than 2000 built in classes. 4.ASP does not have any server side components whereas Asp .net have server side components such as Button , Text Box etc. 5.Asp does not have page level transaction while Asp .net have page level transaction. ASP .NET pages only support one language on a single page, while Asp support multiple language on a single page.

6.Page functions must be declared as <script runat=server> in ASP. net . While in Asp page function is declared as <% %>. Ques: 25 ASP.net Versions ? Ans: ASP .NET version 1.0 was first released in January 2002 ASP .NET version 1.1 released in April 2003 (ASP .NET 2003) ASP .NET version 2.0 released in November 2005 (ASP .NET 2005) ASP .NET version 3.5 released in November 2007 (ASP .NET 2008) Ques: 26 What is ASp.net ? Ans: ASP .NET built on .net framework. Asp .net is a web development tool. Asp .net is offered by Microsoft. We can built dynamic websites by using asp .net. Asp .net was first released in January 2002 with version 1.0 of the .net framework. It is the successor of Microsoft's ASP. .NET Framework consists of many class libraries, support multiple languages and a common execution platform. Asp .net is a program run in IIS server. Asp .net is also called Asp+. Every element in Asp .net is treated as object and run on server. Asp .net is a event driven programming language. Most html tags are used by Asp .net. Asp .net allows the developer to build applications faster. Asp .net is a server side scripting. Ques: 27 Define File Name Extensions In Asp .net ? Ans: Applications written in Asp .net have different files with different extension. native files generally have .aspx or .ascx extension . Web services have .asmx extension. File name containing the business logic depend on the language that you are using. For Example a c# file have extension aspx.cs. Ques: 28 What is the structure of ASP.Net Pages ? Ans: 1.Directives:A directive controls how an ASP.NET page is compiled. The beginning of a directive is marked with the characters <%@ and the end of a directive is marked with the characters %>. A directive can appear anywhere within a page.A directive typically appears at the top of an ASP.NET page. 2.Code declaration block:A code declaration block contains all the application logic for your ASP.NET page and all the global variable declarations, subroutines, and functions. It must appear within a <Script Runat="Server"> tag. 3.ASP.Net Controls:ASP.NET controls can be freely interspersed with the text and HTML content of a page. The only requirement is that the controls should appear within a <form Runat= "Server"> tag. And, for certain tags such as <span Runat="Server"> and <ASP:Label Runat="Server"/>, this requirement can be ignored without any dire consequences. 4.Code Render Blocks:If you need to execute code within the HTML or text content of your ASP.NET page, you can do so within code render blocks. The two types of code render blocks are inline code and inline expressions. Inline code executes a statement or series of statements. This type of code begins with the characters <% and ends with the characters %>. 5.Server side comments:You can add comments to your ASP.NET pages by using serverside comment blocks. The beginning of a server-side comment is marked with the characters <%-- and the end of the comment is marked with the characters --%>. 6.Server side include Directives:You can include a file in an ASP.NET page by using one of the two forms of the server-side include directive. If you want to include a file that is located in the same directory or in a subdirectory of the page including the file, you would use the following directive:<!-- #INCLUDE file="includefile.aspx" --> 7.Literal text and html Tags:The final type of element that you can include in an ASP.NET page is HTML content. The static portion of your page is built with plain old HTML tags and text. Ques: 29 Difference between Cookies and Session in Asp.Net ?

Ans: 1.The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for. 2.A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie 3. Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit. Ans: 1.The main difference between cookies and sessions is that cookies are stored in the user's browser, and sessions are not. This difference determines what each is best used for. 2.A cookie can keep information in the user's browser until deleted. If a person has a login and password, this can be set as a cookie in their browser so they do not have to re-login to your website every time they visit. You can store almost anything in a browser cookie 3. Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and passing information while the user has their browser open. The problem with sessions is that when you close your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a session like it could as a cookie, and the user would be forced to re-login every time they visit. Ques: 30 Types of Debbuger ? Ans: Debugger is another program that is used for testing and debugging purpose of other programs. Most of the time it is using to analyze and examine error conditions in application. It will be able to tell where exactly in your application error occurred, Two Types of Debbuger: 1.CorDBG command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch. 2.DbgCLR graphic debugger. Visual Studio .NET uses the DbgCLR. Ques: 31 What is the Difference Between Compiler and Debugger ? Ans: Compiler is a software or set of soetware that translate one computer Language to another computer.Most cases High level Programming Language to low level Programming Language. Most of the time Program analyzed and examined error then Debugger used.Debugger is another program that is used for testing and debugging purpose of other programs. It will be able to tell where exactly in your application error occurred,and tell the where error occured. Ans: Compiler is a software or set of software that translate one computer Language to another computer.Most cases High level Programming Language to low level Programming Language. Most of the time Program analyzed and examined error then Debugger used.Debugger is another program that is used for testing and debugging purpose of other programs. It will be able to tell where exactly in your application error occurred,and tell the where error occurred Ans: Compiler is a software or set of software that translate one computer Language to another computer.Most cases High level Programming Language to low level Programming Language. Most of the time Program analyzed and examined error then Debugger used.Debugger is another program that is used for testing and debugging

purpose of other programs. It will be able to tell where exactly in your application error occurred,and tell the where error occurred NO Ques: 32 What is the Difference between Compiler and Translator? Ans: Compiler converet the program one computer language to another computer language.in other word high level language to low level language. Traslator traslate one language to many other language like english to hindi,french etc. Ques: 33 What is Globalization ? Ans: The process to make a Application according to the user from multiple culture.The process involves translating the user interface in to many languages,like using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues.Accommodating these cultural differences for an application is called Globlization. Three different ways to globalize web applications: 1.Detect and redirect approach 2.Run-time adjustment approach 3.Satellite assemblies approach Ques: 34 What happens when you make changes to an applications Web.config file? Ans: When make change in web.config file.IIS restarts application and automatically applies changes.This effect the Session state variable and effect the application,then user adversely affected. Ques: 35 What are the steps to host a web application on a web server? Ans: Step1.Set up a virtual folder for the application using IIS. 2. Copy the Web application to the virtual directory. 3. Adding the shared .NET components to the servers global assembly cache (GAC). 4. Set the security permissions on the server to allow the application to access required resources. Ques: 36 What is the difference between Session Cookies and Persistent Cookies? Ans: When client broweses session cookie stored in a memmory.when browser closed session cookie lost. //Code to create a UserName cookie containing the name David. HttpCookie CookieObject = new HttpCookie("UserName", "David"); Response.Cookies.Add(CookieObject); //Code to read the Cookie created above Request.Cookies["UserName"].Value; Persistent cookie same as the session cookie except that persistent cookie have expiration date.The expiration date indicates to the browser that it should write the cookie to the client's hard drive. //Code to create a UserName Persistent Cookie that lives for 10 days HttpCookie CookieObject = new HttpCookie("UserName", "David"); CookieObject.Expires = DateTime.Now.AddDays(10); Response.Cookies.Add(CookieObject); //Code to read the Cookie created above Request.Cookies["UserName"].Value; Ques: 37 What are the advantages and disadvantage of Using Cookies? Ans: Advantage:

1.Cookies do not require any server resources since they are stored on the client. 2. Cookies are easy to implement. 3. Cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the computer (persistent cookies). Disadvantage: 1. Users can delete a cookies. 2. Users browser can refuse cookies,so your code has to anticipate that possibility. 3. Cookies exist as plain text on the client machine and they may security risk as anyone can open and tamper with cookies. Ques: 38 Explain Namespace ? Ans: There are many classes in Asp.Net.If Microsoft simply jumbled all the classes together, then you would never find anything. Microsoft divided the classes in the Framework into separate namespaces.All classes working with a file system located in Systen.Io Namespace. All classes working with SQL data base used System.Data.SqlClient Namespace. The ASP.NET Framework gives you the most commonly used namespaces: . System . System.Collections . System.Collections.Specialized . System.Configuration . System.Text . System.Text.RegularExpressions . System.Web . System.Web.Caching . System.Web.SessionState . System.Web.Security . System.Web.Profile . System.Web.UI . System.Web.UI.WebControls . System.Web.UI.WebControls.WebParts . System.Web.UI.HTMLControls Ques: 39 What is CLR? Ans: CLR(Common Language Runtime) provide Environment to debugg and run program and utility developed at the .Net FrameWork.CLR provide memory management, debugging, security, etc. The CLR is also known as Virtual Execution System (VES). The managed and unmanaged code both runs under CLR.Unmanaged code run through the Wrapered Classes.There are many system Utilities run under the CLR. Ques: 40 What is Shallow Copy and Deep Copy in .NET? Ans: Shallow copy:When a object creating and copying nonstatic field of the current object to the new object know as shallow copy. If a field is a value type --> a bit-by-bit copy of the field is performed a reference type --> the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object. Deep copy:Deep cooy little same as shallow copy,deep copy the whole object and make a different object, it means it do not refer to the original object while in case of shallow copy the target object always refer to the original object and changes in target object also make changes in original object. Ques: 41 Explain Web Services?

Ans: Web services are programmable business logic components that provide access to functionality through the Internet. Web services are given the .asmx extension.Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML.In .Net FrameWork Web services convert your application in to Web Application.which published their functionality to whole world on internet.Web Services like a software system that designed to support interoperable machine-to-machine interaction over a Internet. Ques: 42 What is Postback in Asp.net? Ans: When Frist time reqest to the server PostBack is False.When request or an action occurs (like button click), the page containing all the controls within the <FORM... > tag performs an HTTP POST, while having itself as the target URL. This is called Postback.We can say its a mechanism to allow the communication between client side and server side. Ques: 43 Explain the differences between server-side and client-side code in Asp.Net? Ans: In Asp.Net Environment Server side code or scripting means the script will executed by server as interpreted needed.Server side scripting done the bussines logic like transaction and fetching data to Sever. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Since the code is included in the HTML page, anyone can see the code by viewing the page source. Ques: 44 What is the ASP.NET validation controls? Ans: Validation controls applied on client side scripting.List of Validations: 1. RequiredFieldValidator:Makes a input control to required field. 2. RangeValidator:Chek the values falls between to values. 3. CompareValidator:Compares the value of one input control to the value of another input control or to a fixed value. 4. RegularExpressionValidator:Input value matches a specific pattern. 5. CustomValidator:Write a Method to validat input. 6. ValidationSummary:Displays a report of all validation errors occurred in a Web page. Ques: 45 Describe Paging in ASP.NET? Ans: "In computer operating systems there are various ways in which the operating system can store and retrieve data from secondary storage for use in main memory". One such memory management scheme is referred to as paging.In ASP.Net the DataGrid control in ASP.NET enables easy paging of the data. The AllowPaging property of the DataGrid can be set to True to perform paging. ASP.NET automatically performs paging and provides the hyperlinks to the other pages in different styles, based on the property that has been set for PagerStyle.Mode. Ques: 46 What is the difference between Server.Transfer and Response.Redirect? Ans: Response.Redirect:This tells the browser that the requested page can be found at a new location. The browser then initiates another request to the new page loading its contents in the browser.

Server.Transfer: It transfers execution from the first page to the second page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content. The benefit of this approach is one less round trip to the server from the client browser. Ques: 47 What is Data Binding? Ans: Data Binding is binding controls to data from databases.Using Data binding a control to a particular column in a table from the database or we can bind the whole table to the data grid. In other words Data binding is a way used to connect values from a collection of data (e.g. DataSet) to the controls on a web form. The values from the dataset are automatically displayed in the controls without having to write separate code to display them. Ques: 48 Do Web controls support Cascading Style Sheets? Ans: All Web controls inherit a property named CssClass from the base class "System.Web.UI. WebControls. WebControl" which can be used to control the properties of the web control. Ques: 49 What classes are needed to send e-mail from an ASP.NET application? Ans: Following Classes use to sent email from ASP.Net application: 1.MailMessage 2.SmtpMail Both are classes defined in the .NET Framework Class Library's "System. Web. Mail" namespace. Ques: 50 What is ViewState? Ans: State of the object to be stored in hidden field on the page.ViewState is not stored on the server or any other external source. ViewState transported to the client and back to the server. ViewState is used the retain the state of server-side objects between postabacks.Viewstate should be the first choice to save data to access across postbacks. Ques: 51 Define ASP.Net page life cycle in brief ? Ans: 1. OnInit (Init): Initializes each child control. 2. LoadControlState: Loaded the ControlState of the control. To use this method the control must call the Page.RegisterRequiresControlState method in the OnInit method of the control. 3. LoadViewState: Loaded the ViewState of the control. 4. LoadPostData: Controls that implement this interface use this method to retrieve the incoming form data and update the control According to there properties. 5. Load (OnLoad): Allows actions that are common to every request to be placed here. control is stable at this time, it has been initialized and its state has been reconstructed. 6. RaisePostDataChangedEvent: Is defined on the interface IPostBackData-Handler. 7. RaisePostbackEvent: Handling the clien side event caused Postback to occur 8. PreRender (OnPreRender): Allows last-minute changes to the control. This event takes place before saving ViewState so any changes made here are saved. 9. SaveControlState: Saves the current control state to ViewState. 10. SaveViewState: Saves the current data state of the control to ViewState.

11. Render: Generates the client-side HTML Dynamic Hypertext Markup Language (DHTML) and script that are necessary to properly display this control at the browser. In this stage any changes to the control are not persisted into ViewState. 12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this stage. Unmanaged resources are resources that are not handled by the .NET common language runtime such as file handles and database connections. 13. UnLoad Ques: 52 What do you mean by three-tier architecture? Ans: The three-tier architecture was improve management of code and contents and to improve the performance of the web based applications. There are mainly three layers in three-tier architecture.This architecture remove the many drawbacks of previous ClietServer architecture. There are three stages in this Architecture; (1)Presentation Layer: PL(Presentation Layer) Contains only client side scripting like HTML, javascript and VB script etc.The input Validation validate on Cliet side. (2)Business Logic Layer:BL(Business Logic Layer) contain the server side code for data transaction, query and communicate through Data Base,and Pass the data to the user interface. (3)Database layer:Data Layer represents the data store like MS Access, SQL Server, an XML file, an Excel file or even a text file containing data also some additional database are also added to that layers. Ques: 53 Write the code that creates a cookie containing the user name R4R and the current date to the user computer. Set the cookie to remain on the user computer for 30 days? Ans: Code: HttpCookie cookUserInfo = new HttpCookie("UserInfo"); CookUserInfo["Name"] = "R4R"; CookUserInfo["Time"] = DateTime.Now.ToString(); cookUserInfo.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(cookUserInfo); Description: "HttpCookie" :The HttpCookie class is under System.Web namespace. "CookUserInfo" :is the object of class HttpCookie "Expires": is the property that sets the duration,when cookie expire. Ques: 54 Describe the property of cookie in Asp.Net ? Ans: Properties: 1. Domain: The domain associated with the cookie for example, aspx.superexpert.com 2. Expires: The expiration date for a persistent cookie. 3. HasKeys: A Boolean value that indicates whether the cookie is a cookie dictionary. 4. Name: The name of the cookie. 5. Path: The path associated with the Cookie. The default value is /. 6. Secure: A value that indicates whether the cookie should be sent over an encrypted connection only. The default value is False. 7. Value: The value of the Cookie. 8. Values: A NameValueCollection that represents all the key and value pairs stored in a Cookie dictionary. Ques: 55 Differences between Web and Windows applications?

Ans: Web Forms:Web forms use server controls, HTML controls, user controls, or custom controls created specially for Web forms.Web applications are displayed in a browser.Web forms are instantiated on the server, sent to the browser, and destroyed immediately. Windows Forms:Windows forms are instantiated, exist for as long as needed, and are destroyed. Windows applications run on the same machine they are displayed on.Windows applications display their own windows and have more control over how those windows are displayed. Ques: 56 What is the main difference between the Button server control and the Button HTML control? Ans: The Button HTML control triggers the event procedure indicated in the buttons onclick attribute, which runs on the client. When clicked, the Button server control triggers an ASP.NET Click event procedure on the server. Ques: 57 What is the difference between web.config and Machine.config files? Ans: 1. Usually on a webserver there is only one Machine.config file whereas in a web application there is no of files,but in the root directory. 2. Web.config file settings will override machine.config settings. 3. Machine.config file specifies configuration settings for all of the websites on the web server.Web.config file specify configuration settings for a particular web application, and is located in the applications root directory . Ques: 58 How do you require authentication using the Web.config file? Ans: Include the following &ltauthorization> element to require authentication: <authorization> <deny users="?" /> </authorization> Ques: 59 How to create Multivalued Cookie ? Ans: <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void btnSubmit_Click(Object s, EventArgs e) { Response.Cookies["preferences"]["firstName"] = txtFirstName.Text; Response.Cookies["preferences"]["lastName"] = txtLastName.Text; Response.Cookies["preferences"]["favoriteColor"] = txtFavoriteColor.Text; Response.Cookies["preferences"].Expires = DateTime.MaxValue; } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Set Cookie Values</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:"

AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> <br /><br /> <asp:Label id="lblFavoriteColor" Text="Favorite Color:" AssociatedControlID="txtFavoriteColor" Runat="server" /> <br /> <asp:TextBox id="txtFavoriteColor" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat="server" /> </div> </form> </body> </html> Ques: 60 Define Error Events in Asp.Net? Ans: In ASP.Net when any unhandled exception accurs in application then an event occures,that event called Error event.Two types of Event: 1. Page_Error:When exception occures in a page then this event raised. 2. Application_error:Application_Error event raised when unhandled exceptions in the ASP.NET application and is implemented in global.asax. The error event have two method: 1. GetLastError: Returns the last exception that occurred on the server. 2. ClearError: This method clear error and thus stop the error to trigger subsequent error event. Ques: 61 Why the exception handling is important for an application? Ans: Exception handling prevents the unusual error in the asp.net application,when apllication executed.If the exceptions are handled properly, the application will never get terminated abruptly. Ques: 62 Explain the aim of using EnableViewState property?

Ans: When the page is posted back to the server, the server control is recreated with the state stored in viewstate.It allows the page to save the users input on a form across postbacks. It saves all the server side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. Ques: 63 What are the two levels of variable supported by Asp.net? Ans: 1. Page level variable:String ,int ,float. 2. Object level variable:Session level, Application level. Ques: 64 Difference between Session object and Profile object in ASP.NET? Ans: Profile object: 1. Profile object is persistent. 2. Its uses the provider model to store information. 3. Strongly typed 4. Anonymous users used mostly. Session object: 1. Session object is non-persistant. 2. Session object uses the In Proc, Out Of Process or SQL Server Mode to store information. 3. Not strongly typed. 4. Only allowed for authenticated users. Ques: 65 What is the Default Expiration Period For Session and Cookies,and maximum size of viewstate? Ans: The default Expiration Period for Session is 20 minutes. The default Expiration Period for Cookie is 30 minutes. The maximum size of the viewstate is 25% of the page size Ques: 66 What is the use of Global.asax File in ASP.NET Application ? Ans: The Global.asax file, can be stored in root directory and accesible for web-sites,is an optional file.This Global.asax file contained in HttpApplicationClass.we can declare global variables like variables used in master pages because these variables can be used for different pages right.Importent feature is that its provides more security in comparision to other. It handle two event: 1.Application-level 2.Session-level events. Global.asax File itself configured but it can not be accessed.while one request is in processing it is impossible to send another request, we can not get response for other request and even we can not start a new session. while adding this Global.asax file to our application by default it contains five methods, Those methods are: 1.Application_Start. 2.Application_End. 3.Session_Start. 4.Session_End. 5.Application_Error. Ques: 67 What is the Purpose of System.Collections.Generic ? Ans: For more safty and better performance strongly typed collections are useful for the user. System.Collections.Generic having interfaces and classes which define strongly typed generic collections. Ques: 68 What is GAC and name of the utility used to add an assembly into the GAC ?

Ans: GAC(Global Assembly Cache) for an effective sharing of assemblies.GAC refers to the machine-wide code cache in any of the computers that have been installed with common language runtime.Global Assembly Cache in .NET Framework acts as the central place for private registering assemblies. "gacutil.exe" utility used to add assembly in GAC Ques: 69 Whether we can use vbscript and javascript combination for validation? Ans: WE cant use them togather,since compiler are different. Ques: 70 What are the different states in ASP.NET? Ans: There are three types of state: 1. View state: Under the client-side state managment.The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.NET page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. 2. Application state:Under the server side state managment. ASP.NET allows you to save values using application state, a global storage mechanism that is accessible from all pages in the Web application. Application state is stored in the Application key/value dictionary. 3. Session state:Under server side state managment . ASP.NET allows you to save values using session state, a storage mechanism that is accessible from all pages requested by a single Web browser session. Ques: 71 Define State managment? Ans: This is passible to at a time many request occures.State management is the process by which maintained state and page information over multiple requests for the same or different pages. Two types of State Managment: 1. Client side state managment:This stores information on the client's computer by embedding the information into a Web page,uniform resource locator(url), or a cookie. 2. Server side state managment: There are two state Application State,Session State. Ques: 72 What is Authentication and Authorization ? Ans: An authentication system is how you identify yourself to the computer. The goal behind an authentication system is to verify that the user is actually who they say they are. Once the system knows who the user is through authentication, authorization is how the system decides what the user can do. Ques: 73 Discribe Client Side State Management? Ans: Client side state managment have: a. Stores information on the client's computer by embedding the information into a Web page. b. A uniform resource locator(url). c. Cookie. To store the state information at the client end terms are: 1. View State:It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page.Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. 2. Control State:When user create a custom control that requires view state to work properly, you should use control state to ensure other developers dont break your control by disabling view state. 3. Hidden fields:Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

4. Cookies: Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site. 5. Query Strings: Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL. Ques: 74 Describe Server Side State Management ? Ans: Sever side state managment provied Better security,Reduced bandwidth. 1. Application State: This State information is available to all pages, regardless of which user requests a page. 2. Session State Session State information is available to all pages opened by a user during a single visit. Ques: 75 What is SessionID? Ans: To identify the request from the browser used sessionID. SessionId value stored in a cookie. Configure the application to store SessionId in the URL for a "cookieless" session. Ques: 76 What is the Session Identifier? Ans: Session Identifier is : 1. To identify session. 2. It has SessionID property. 3. When a page is requested, browser sends a cookie with a session identifier. 4. Session identifier is used by the web server to determine if it belongs to an existing session or not. If not, then Session ID is generated by the web server and sent along with the response. Ques: 77 Advantages of using Session State? Ans: Advantages: 1. It is easy to implement. 2. Ensures platform scalability,works in the multi-process configuration. 3. Ensures data durability, since session state retains data even if ASP.NET work process restarts as data in Session State is stored in other process space. Ques: 78 Disadvantages of using Session State ? Ans: Disadvatages: 1. It is not advisable to use session state when working with large sum of data.Because Data in session state is stored in server memory. 2. Too many variables in the memory effect performance. Because session state variable stays in memory until you destroy it. Ques: 79 What are the Session State Modes? Define each Session State mode supported by ASP.NET. Ans: ASP.NET supports three Session State modes. 1. InProc:This mode stores the session data in the ASP.NET worker process and fastest among all of the storage modes.Its Also effects performance if the amount of data to be stored is large. 2. State Server:This mode maintained on a different system and session state is serialized and stored in memory in a separate process. State Server mode is serialization and de-serialization of objects. State Server mode is slower than InProc mode as this stores data in an external process. 3. SQL Server:This mode can be used in the web farms and reliable and secures storage of a session state.In this storage mode, the Session data is serialized and stored in a database table in the SQL Server database.

Ques: 80 What is a Master Page in Asp.Net? Ans: For consistent layout for the pages in application used Master Pages.A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application.Then user create individual content pages that share all the information and lay out of a Master Page Ques: 101 Can the action attribute of a server-side <form> tag be set to a value and if not how can you possibly pass data from a form page to a subsequent page. Ans: No, You have to use Server.Transfer to pass the data to another page. Ques: 102 What is the role of global.asax. Ans: Store global information about the application Ques: 103 Whats a bubbled event? Ans: When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents. Ques: 104 Describe the difference between inline and code behind. Ans: Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page. Ques: 105 Which method do you invoke on the DataAdapter control to load your generated dataset with data? Ans: The .Fill() method Ques: 106 Can you edit data in the Repeater control? Ans: No, it just reads the information from its data source Ques: 107 Which template must you provide, in order to display data in a Repeater control? Ans: ItemTemplate Ques: 108 How can you provide an alternating color scheme in a Repeater control? Ans: Use the AlternatingItemTemplate Ques: 109 What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? Ans: You must set the DataSource property and call the DataBind method. Ques: 110 Name two properties common in every validation control? Ans: ControlToValidate property and Text property Ques: 111 Where does the Web page belong in the .NET Framework class hierarchy? Ans: System.Web.UI.Page Ques: 112 Where do you store the information about the users locale? Ans: System.Web.UI.Page.Culture Ques: 113 Can you give an example of what might be best suited to place in the Application Start and Session Start subroutines? Ans: This is where you can set the specific variables for the Application and Session objects. Ques: 114 What is the transport protocol you use to call a Web service?

Ans: SOAP is the preferred protocol. Ques: 115 To test a Web service you must create a windows application or Web application to consume this service? Ans: The webservice comes with a test page and it provides HTTP-GET method to test. Ques: 116 Whats the difference between struct and class in C#? Ans: 1. Structs cannot be inherited. 2. Structs are passed by value, not by reference. 3. Struct is stored on the stack, not the heap. Ques: 117 Where do the reference-type variables go in the RAM? Ans: The references go on the stack, while the objects themselves go on the heap. However, in reality things are more elaborate. Ques: 118 What is the difference between the value-type variables and reference-type variables in terms of garbage collection? Ans: The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects are picked up by GC when their references go null. Ques: 119 What is main difference between Global.asax and Web.Config? Ans: ASP.NET uses the global.asax to establish any global objects that your Web application uses. The .asax extension denotes an application file rather than .aspx for a page file. Each ASP.NET application can contain at most one global.asax file. The file is compiled on the first page hit to your Web application. ASP.NET is also configured so that any attempts to browse to the global.asax page directly are rejected. However, you can specify application-wide settings in the web.config file. The web.config is an XMLformatted text file that resides in the Web sites root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web site, compilation options for the ASP.NET Web pages, if tracing should be enabled, etc Ques: 120 What is SOAP and how does it relate to XML? Ans: The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

Introduction PHP- Hypertext Preprocessor is server side script language like ASP. Its scripts executes on server. PHP is open source software. The goal of PHP language is to allow web developers to write dynamically generated pages quickly.

PHP was released in 1995 by a programmer Rasmus Lerdorf and is now maintained by PHP Group. Its original full form was personal homepage tools.

Zeev and Andi rewrote the parser for PHP to launch PHP3 with a full form "Hypertext Pre-processor". It can be used with different operating systems like Microsoft Windows, Linux, UNIX and Solaris. It can be linked to different database systems easily.

History The origins of PHP date back to 1995.PHP was written in the C programming language by Rasmus Lerdorf in 1995 for use in monitoring his online resume and related personal information. For this reason, PHP originally stood for "Personal Home Page".

Lerdorf combined PHP with his own Form Interpreter, releasing the combination publicly as PHP/FI (generally referred to as PHP 2.0) on June 8, 1995. Zeev Suraski and Andi Gutmans, rebuilt PHP's core, releasing the updated result as PHP/FI 2 in 1997. PHP 3 was released in 1998, , which was the first widely used version. PHP 4 was released in May 2000, with a new core, known as the Zend Engine 1.0. PHP 4 featured improved speed and reliability over PHP 3. PHP 5 was released in July 2004, with the updated Zend Engine 2.0. PHP 6 has been in development since October of 2006.

How PHP works? Here i am giving example for form like<FORM ACTION="display.html" METHOD=POST> <INPUT TYPE="text" name="name"> <INPUT TYPE="text" name="age"> <INPUT TYPE="submit"> <FORM>

the content can be like <?php echo "Hi $ name, you are $ age years old!<p>" >

It's that simple! PHP automatically creates a variable for each form input field in your form. You can then use these variables in the ACTION URL file. The next step once you have figured out how to use variables is to start playing with some logical flow tags in your pages. For example, if you wanted to display different messages based on something the user inputs, you would use if/else logic.

<?php if($age>50); echo "Hi $name, you are ancient!<p>"; elseif($age>30); echo "Hi $name, you are very old!<p>"; else; echo "Hi $name."; endif; >

PHP provides a very powerful scripting language which will do much more than what the above simple example demonstrates. See the section on the PHP Script Language for more information. Difference from Other languagePHP and ASP

ASP is a Microsoft product based on the very awkward Visual Basic syntax. PHP is a C-Like, very compact and well organized. ASP requires the registration of components to do that and very ackward object declarations. Most of these components are not free.PHP can be easily installed with a very large number of tools such as image manipulation, upload, email, etc. ASP is very slow, PHP is way faster. ASP works better with SQL Server and Access. I have not used it with MySQL, because it does not make sense. PHP works very very well with MySQL. It works fine with SQL Server, SQL Server is costly.

PHP and JSP

JSP is Java and based on the J2EE specifications. PHP is PHP. JSP has strong typed data. All variables should be declared. PHP has flexible, variable behave 'naturally' although they all have a type defined behind the scenes (like integer, string, etc) JSP is Object-oriented, always. In PHP You can mix in Object-oriented stuff to your liking. JSP is really resident and running on a server, so you always have some running processes you can use for timers, etc. In PHP you can fire up the PHP-engine when a request arrives from a client. So if you need scheduled tasks, you have to fall back to cron and the like.

Advantages

Reduce the time to create large websites.

Create a customized user experience for visitors based on information that you have gathered from them. Open up thousands of possibilities for online tools. Check out PHP - Hot Scripts for examples of the great things that are possible with PHP. Allow creation of shopping carts for e-commerce websites.

Disadvantages

PHP is not pure Object Oriented scripting language. PHP has very poor handling errors qualities

Question: What is RDBMS? Answer: Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. What is normalization? Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, andmodifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships. What are different normalization forms? 1NF: Eliminate Repeating Groups Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain. 2NF: Eliminate Redundant Data If an attribute depends on only part of a multi-valued key, remove it to a separate table. 3NF: Eliminate Columns Not Dependent On Key If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key BCNF: Boyce-Codd Normal Form If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables. 4NF: Isolate Independent Multiple Relationships No table may contain two or more 1:n or n:m relationships that are not directly related. 5NF: Isolate Semantically Related Multiple Relationships There may be practical constrains on information that justify separating logically related many-to-many relationships.

ONF: Optimal Normal Form A model limited to only simple (elemental) facts, as expressed in Object Role Model notation. DKNF: Domain-Key Normal Form A model free from all modification anomalies. Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database. What is Stored Procedure? A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database. e.g. sp_helpdb, sp_renamedb, sp_depends etc. What is Trigger? A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures. Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. What is View? A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views. What is Index? An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when

there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. Clustered indexes define the physical sorting of a database tables rows in the storage media. For this reason, each database table may have only one clustered index. Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself.

Oracle Concepts and Architecture

Database Structures Q1. What are the components of physical database structure of Oracle database? Ans:Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files. Q2. What are the components of logical database structure of Oracle database? Ans:There are tablespaces and database's schema objects. Q3. What is a tablespace? Ans:A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together. Q4. What is SYSTEM tablespace and when is it created? Ans:Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. Q5. Explain the relationship among database, tablespace and data file. Ans:Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace. Q6. What is schema? Ans:A schema is collection of database objects of a user. Q7. What are Schema Objects? Ans:Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links. 8. Can objects of the same schema reside in different table spaces? Ans:Yes. Q9. Can a tablespace hold objects from different schemes? Ans:Yes. Q10. What is Oracle table? Ans:A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns. Q11. What is an Oracle view?

Ans:A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.) Q12. Do a view contain data? Ans:Views do not contain or store data.

Tolal:174 Click: 1 2 3 4 5 6 7 8 9

SQL Interview Questions And Answers

Page 1
Ques: 1 What are the difference between DDL, DML and DCL commands? Ans: SQL can be divided into two parts: > The Data Manipulation Language (DML) > The Data Definition Language (DDL). The query and update commands form the DML part of SQL: > SELECT - extracts data from a database > UPDATE - updates data in a database > DELETE - deletes data from a database > INSERT INTO - inserts new data into a database The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are: > CREATE DATABASE - creates a new database > ALTER DATABASE - modifies a database > CREATE TABLE - creates a new table > ALTER TABLE - modifies a table > DROP TABLE - deletes a table > CREATE INDEX - creates an index (search key) > DROP INDEX - deletes an index Data Control Language (DCL) statements. Some examples: > GRANT - gives user's access privileges to database > REVOKE - withdraw access privileges given with the GRANT command Ques: 2 Which one is faster DELETE/TRUNCATE? Ans: Truncante is more faster than delete because when we delete the records from the database, database has to perform 2 actions. > Delete from the database > Write the deleted records into "rollback" segments. But incase of "Truncate" the second activity is not required.It is faster than becouse truncate is a ddl command so it does not produce any rollback information and the storage space is released while the delete command is a dml command and it produces rollback information too and space is not deallocated using delete command. Ques: 3 What is RDBMS? Ans: RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM

DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collections of related data entries and it consists of columns and rows.Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. Ques: 4 What are different normalization forms? Ans: normalisation have a se veral forms that a database structure can be subject to, each with rules that constrain the database further and each creating what is called a Normal Form. These are, in order: > First Normal Form (1NF) > Second Normal Form (2NF) > Third Normal Form (3NF) > Boyce Codd Normal Form (BCNF) > Fourth Normal Form (4NF) > Fifth Normal Form (5NF) > Optimal Normal Form (ONF) > Domain-Key Normal Form (DKNF) Theses are defined as : > 1NF: Eliminate Repeating Groups : Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain. > 2NF: Eliminate Redundant Data : If an attribute depends on only part of a multi-valued key, remove it to a separate table. > 3NF: Eliminate Columns Not Dependent On Key : If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key. > BCNF: Boyce-Codd Normal Form : If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables. > 4NF: Isolate Independent Multiple Relationships : No table may contain two or more 1:n or n:m relationships that are not directly related. > 5NF: Isolate Semantically Related Multiple : Relationships There may be practical constrains on information that justify separating logically related many-to-many relationships. > ONF: Optimal Normal Form : A model limited to only simple (elemental) facts, as expressed in Object Role Model notation. > DKNF: Domain-Key Normal Form : A model free from all modification anomalies. Ques: 5 What is normalization? Ans: Normalisation is a process whish is the tables in a database are optimised to remove the potential for redundancy. Two main problems may arise if this is not done: > Repeated data makes a database bigger. > Multiple instances of the same values make maintaining the data more difficult and can create anomalies. Ques: 6 What is Stored Procedure Ans: A stored procedure is a named group of SQL statements that have been

previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database. e.g. sp_helpdb, sp_renamedb, sp_depends etc Ques: 7 What is Trigger? Ans: A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures. Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. Ques: 8 What is View? Ans: A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views. Ques: 9 What is Index? Ans: An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application . A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance. Ques: 10 What is SQL? Ans: SQL is a bassically standard language for accessing and manipulating databases. Its is defines as : > SQL stands for Structured Query Language > SQL lets you access and manipulate databases > SQL is an ANSI (American National Standards Institute) standard. SQL have a many properties, It can do : > SQL can execute queries against a database. > SQL can retrieve data from a database. > SQL can insert records in a database.

> SQL can update records in a database. > SQL can delete records from a database. > SQL can create new databases. > SQL can create new tables in a database. > SQL can create stored procedures in a database. > SQL can create views in a database. > SQL can set permissions on tables, procedures, and views. Ques: 11 What are the components of physical database structure of Oracle database? Ans: Physical components of oracle database are: > Control files, > Redo log files and > Datafiles. > Control file : control file is basicaly a type of file .Its read in the mount state of database. control file is a small binary file which records the physical structure of database which includes * Database name * names and locations of datafiles and online redo log files. * timestamp of database creation * check point information * current log sequence number. Redo log files : Redo log files usually use for the saving to the files. This files saves all the changes that are made to the database as they occur. This plays a great role in the database recovery. Datafiles : Datafiles are the physicalfiles which stores data of all logical structure. Ques: 12 What are the components of logical database structure of Oracle database? Ans: The Logical Database Structure of an Oracle include : > The schema objects, > Data blocks, > Extents, > Segments and > Tablespaces. > schema objects : means table, index, synonyms, sequences etc. > Data blocks : are the smallest part of the oracle database defined by DB_BLOCK_SIZE parameter. > Extent : A group of data blocks forms an extent. > Segments : An extents groups tends to segments, > Table space : lastly a group of segment forms a tablespace. Ques: 13 What is a tablespace? Ans: A Tablespace is bassically a logical storage unit within an Oracle database. It is logical because a tablespace is not visible in the file system of the machine on which the database resides. A tablespace, in turn, consists of at least one data

file which are physically located in the file system of the server. b/w datafile belongs to exactly one tablespace. Each table index and so on that is stored in an Oracle database belongs to a tablespace. The tablespace builds the bridge between the Oracle database and the filesystem in which the table's or index' data is stored. There are three types of tablespaces in Oracle: > Permanent tablespaces > Undo tablespaces > temporary tablespaces A tablespace is created with the create tablespace sql command. Ques: 14 What is SYSTEM tablespace and when is it created? Ans: Every ORACLE database have a table space which name is SYSTEM . when the database is created taht a time its also automatically created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. Ques: 15 Explain the relationship among database, tablespace and data file. Ans: Database : Database is the Collection of data is called database. Table Space : The table space ismany use for storing the data in the database. When a database is created two table spaces are created. i) System Table Space : This data file stores all the tables related to the system and dba tables. ii) User Table Space : This data file stores all the user related tables. We should have separate table spaces for storing the tables and indexes so that the access is fast. Data Files : Every Oracle Data Base has one or more physical data files. They store the data for the database. Every data-file is associated with only one database. Once the Data file is created the size cannot change. To increase the size of the database to store more data we have to add data file. Ques: 16 What is schema? Ans: Schema bassically Pronounce skee-ma, It is the structure of a database system,It described in a formal language supported by the database management system (DBMS). In the RDBMS (Relational database System) , the schema defines the tables, the fields in each table, and the Schemas are generally stored in a data dictionary . Even a schema is defined in text database language , the term is often used to refer to a graphical depiction of the database structure. Ques: 17 What are Schema Objects? Ans: Schema is bassically a Associated with each database user . It is a collection of schema objects. Examples of schema objects include tables, views, sequences, synonyms, indexes, clusters, database links, snapshots, procedures, functions, and packages. Schema objects are logical data storage structures. Schema objects don't have a one-to-one correspondence to physical files on disk that store their information. Even Oracle stores a schema object logically within a tablespace of the database. The data of each object is physically contained in one or more of the tablespace's datafiles. Ques: 18 Can objects of the same schema reside in different table spaces? Ans: Yes we can objects of the same schema reside in different table space. Schema objects can stored in different tablespace and a tablespace can contained one or more schema objects data. Ques: 19 Can a tablespace hold objects from different schemes?

Ans: Yes we can a template hold objects from different schemes. Ques: 20 What is Oracle table? Ans: The Collection of informations stored in the strutrued format which is in rows and columns formate that is called a table.

Database management interview questions Database Q148. What is a Cartesian product? What causes it? Ans: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. Q149. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application? Ans: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. Q150. What is the difference of a LEFT JOIN and an INNER JOIN statement? Ans: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 Q151. When a query is sent to the database and an index is not being used, what type of execution is taking place? Ans:A table scans. Q152. What are the pros and cons of using triggers? Ans: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. Triggers enhance the security, efficiency, and standardization of databases. Triggers can be beneficial when used: to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format. to run other non-database operations coded in user-defined functions to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information. To check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints arent appropriate, or when table check constraints limit checking to the current table only.

Q139. Display the number value in Words Ans:SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred 1600 one thousand six hundred

1250 one thousand two hundred fifty If you want to add some text like, Rs. Three Thousand only. SQL> select sal "Salary ", (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.')) "Sal in Words" from emp / Salary Sal in Words ------- -----------------------------------------------------800 Rs. Eight Hundred only. 1600 Rs. One Thousand Six Hundred only. 1250 Rs. One Thousand Two Hundred Fifty only. Q140. Display Odd/ Even number of records Ans:Odd number of records: select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp); 1 3 5 Even number of records: select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp) 2 4 6 Q141. Which date function returns number value? Ans: months_between Q142. Any three PL/SQL Exceptions? Ans:Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others Q143. What are PL/SQL Cursor Exceptions? Ans:Cursor_Already_Open, Invalid_Cursor Q144. Other way to replace query result null value with a text Ans:SQL> Set NULL N/A to reset SQL> Set NULL Q145. What are the more common pseudo-columns? Ans:SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM Q146. What is the output of SIGN function? Ans:1 for positive value, 0 for Zero, -1 for Negative value. Q147. What is the maximum number of triggers, can apply to a single table? Ans:12 triggers.

.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Q128. To see current user name ? Ans:SQL> show user; Q129. Change SQL prompt name ? Ans: SQL> set sqlprompt R4R > Q130. Switch to DOS prompt ? Ans: SQL> host Q131. How do I eliminate the duplicate rows ? Ans:SQL> delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name); or SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv); Example. Table Emp Empno Ename 101 Scott 102 Jiyo 103 Millor 104 Jiyo 105 Smith delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename = b.ename); The output like, Empno Ename 101 Scott 102 Millor 103 Jiyo 104 Smith Q132. How do I display row number with records? Ams:To achive this use rownum pseudocolumn with query, like SQL> select rownum, ename from emp; Output: 1 Scott 2 Millor 3 Jiyo 4 Smith Q133. Display the records between two range Ans:select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start); Enter value for upto: 10 Enter value for Start: 7 ROWNUM EMPNO ENAME --------- --------- ---------1 7782 CLARK 2 7788 SCOTT 3 7839 KING 4 7844 TURNER

Q134. I know the nvl function only allows the same data type(ie. number or char or date Nvl(comm, 0)), if commission is null then the text Not Applicable want to display, instead of blank space. How do I write the query? Ans:SQL> select nvl(to_char(comm.),'NA') from emp; Output : NVL(TO_CHAR(COMM),'NA') ----------------------NA 300 500 NA 1400 NA NA Q135. Oracle cursor ? Ans: Implicit & Explicit cursors Oracle uses work areas called private SQL areas to create SQL statements. PL/SQL construct to identify each and every work are used, is called as Cursor. For SQL queries returning a single row, PL/SQL declares all implicit cursors. For queries that returning more than one row, the cursor needs to be explicitly declared. Q136. Explicit Cursor attributes ? Ans:There are four cursor attributes used in Oracle cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN Q137. Implicit Cursor attributes ? Ans:Same as explicit cursor but prefixed by the word SQL SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after executing SQL statements. : 2. All are Boolean attributes. 11. Find out nth highest salary from emp table SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal); Enter value for n: 2 SAL --------3700 Q138. To view installed Oracle version information Ans:SQL> select banner from v$version;

Q119. Where the integrity constraints are stored in data dictionary? Ans:The integrity constraints are stored in USER_CONSTRAINTS. Q120. How will you activate/deactivate integrity constraints? Ans:The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT. Q121. If unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE? Ans:It won't, Because SYSDATE format contains time attached with it.

Q122. What is a database link? Ans:Database link is a named path through which a remote database can be accessed. Q123. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value? Ans:Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed. Q124. What is CYCLE/NO CYCLE in a Sequence? Ans:CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum. NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value. Q125. What are the advantages of VIEW? Ans:- To protect some of the columns of a table from other users. - To hide complexity of a query. - To hide complexity of calculations. Q126. Can a view be updated/inserted/deleted? If Yes - under what conditions? Ans:A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

Q95. What are disadvantages of having raw devices? Ans:We should depend on export/import utility for backup/recovery (fully reliable) The tar command cannot be used for physical file backup, instead we can use dd command, which is less flexible and has limited recoveries. Q96. List the factors that can affect the accuracy of the estimations? Ans:- The space used transaction entries and deleted records, does not become free immediately after completion due to delayed cleanout. - Trailing nulls and length bytes are not stored. - Inserts of, updates to and deletes of rows as well as columns larger than a single data block, can cause fragmentation a chained row pieces. Database Security & Administration Q97. What is user Account in Oracle database? Ans:A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges. Q98. How will you enforce security using stored procedures? Ans:Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. Q99. What are the dictionary tables used to monitor a database space? Ans:DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. SQL*Plus Statements

Q100. What are the types of SQL statement? Ans:Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT. Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT. Transactional Control: COMMIT & ROLLBACK Session Control: ALTERSESSION & SET ROLE System Control: ALTER SYSTEM. Q101. What is a transaction? Ans:Transaction is logical unit between two commits and commit and rollback. Q102. What is difference between TRUNCATE & DELETE? Ans:TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. Q103. What is a join? Explain the different types of joins? Ans:Join is a query, which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself. Equi Join - Joining two tables by equating two common columns. Non-Equi Join - Joining two tables by equating two common columns. Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table. Q104. What is the sub-query? Ans:Sub-query is a query whose return values are used in filtering conditions of the main query. Q105. What is correlated sub-query? Ans:Correlated sub-query is a sub-query, which has reference to the main query. Q106. Explain CONNECT BY PRIOR? Ans:Retrieves rows in hierarchical order eg. select empno, ename from emp where. Q95. What are disadvantages of having raw devices? Ans:We should depend on export/import utility for backup/recovery (fully reliable) The tar command cannot be used for physical file backup, instead we can use dd command, which is less flexible and has limited recoveries. Q96. List the factors that can affect the accuracy of the estimations? Ans:- The space used transaction entries and deleted records, does not become free immediately after completion due to delayed cleanout. - Trailing nulls and length bytes are not stored. - Inserts of, updates to and deletes of rows as well as columns larger than a single data block, can cause fragmentation a chained row pieces. Database Security & Administration Q97. What is user Account in Oracle database? Ans:A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges. Q98. How will you enforce security using stored procedures?

Ans:Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. Q99. What are the dictionary tables used to monitor a database space? Ans:DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. SQL*Plus Statements

Q100. What are the types of SQL statement? Ans:Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT. Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT. Transactional Control: COMMIT & ROLLBACK Session Control: ALTERSESSION & SET ROLE System Control: ALTER SYSTEM. Q101. What is a transaction? Ans:Transaction is logical unit between two commits and commit and rollback. Q102. What is difference between TRUNCATE & DELETE? Ans:TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. Q103. What is a join? Explain the different types of joins? Ans:Join is a query, which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself. Equi Join - Joining two tables by equating two common columns. Non-Equi Join - Joining two tables by equating two common columns. Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table. Q104. What is the sub-query? Ans:Sub-query is a query whose return values are used in filtering conditions of the main query. Q105. What is correlated sub-query? Ans:Correlated sub-query is a sub-query, which has reference to the main query. Q106. Explain CONNECT BY PRIOR? Ans:Retrieves rows in hierarchical order eg. select empno, ename from emp where.

Q71. What is meant by free extent? Ans:A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free.

Q72.Which parameter in Storage clause will reduce number of rows per block? Ans:PCTFREE parameter Row size also reduces no of rows per block. Q73. What is the significance of having storage clause? Ans:We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updating, etc., Q74. How does Space allocation table place within a block? Ans:Each block contains entries as follows Fixed block header Variable block header Row Header, row date (multiple rows may exists) PCTEREE (% of free space for row updating in future) Q75. What is the role of PCTFREE parameter is storage clause? Ans:This is used to reserve certain amount of space in a block for expansion of rows. Q76. What is the OPTIMAL parameter? Ans:It is used to set the optimal length of a rollback segment. Q77. What is the functionality of SYSTEM table space? Ans:To manage the database level transactions such as modifications of the data dictionary table that record information about the free space usage. Q78. How will you create multiple rollback segments in a database? - Create a database, which implicitly creates a SYSTEM rollback segment in a SYSTEM tablespace. - Create a second rollback segment name R0 in the SYSTEM tablespace. - Make new rollback segment available (after shutdown, modify init.ora file and start database) - Create other tablespaces (RBS) for rollback segments. - Deactivate rollback segment R0 and activate the newly created rollback segments. Q79. How the space utilization takes place within rollback segments? Ans:It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is in use then it forced to acquire a new extent (number of extents is based on the optimal size) Q80. Why query fails sometimes? Ans:Rollback segment dynamically extent to handle larger transactions entry loads. A single transaction may wipeout all available free space in the rollback segment tablespace. This prevents other user using rollback segments. Q81. How will you monitor the space allocation? Ans:By querying DBA_SEGMENT table/view Q82. How will you monitor rollback segment status? Ans:Querying the DBA_ROLLBACK_SEGS view IN USE - Rollback Segment is on-line. AVAILABLE - Rollback Segment available but not on-line. OFF-LINE - Rollback Segment off-line INVALID - Rollback Segment Dropped. NEEDS RECOVERY - Contains data but need recovery or corrupted.

PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed database.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Contact Us Q107. Difference between SUBSTR and INSTR? Ans:INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1. SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1, starting from n-th position of string1. Q108. Explain UNION, MINUS, UNION ALL and INTERSECT? Ans:INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct rows selected by the first query but not by the second. UNION - returns all distinct rows selected by either query UNION ALL - returns all rows selected by either query, including all duplicates. Q109. What is ROWID? Ans:ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID. Q110. What is the fastest way of accessing a row in a table? Ans:Using ROWID. CONSTRAINTS Q111. What is an integrity constraint? Ans:Integrity constraint is a rule that restricts values to a column in a table. Q112. What is referential integrity constraint? Ans:Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table. Q113. What is the usage of SAVEPOINTS? Ans:SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed. Q114. What is ON DELETE CASCADE? Ans:When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed. Q115. What are the data types allowed in a table? Ans:CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW. Q116. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type? Ans:CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2. Q117. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY?

Ans:Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause. Q118. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULL constraint? Ans:- To modify the datatype of a column the column must be empty. - To add a column with NOT NULL constrain, the table must be empty.
Q127. If a view on a single base table is manipulated will the changes be reflected on the base table? Ans:If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view. Ques: 21 What is an Oracle view?

Ans: A view is a bassically logical table which makes a change complex query to easy term .We can even create a complex view by joining two tables. Ques: 22 Do a view contain data? Ans: Ofcourse the View don't contain any data. The basic property of a view is to extract a set of data columns to display from a large number. And this is useful in future by jst stating the view name instead writing the select statement every time. Ques: 23 Why we use Semicolon after SQL Statements? Ans: Some database systems are very curious about the its must be semicolon at the end of each SQL statement. Semicolon is the very good way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server. We are always try to using MS Access and SQL Server 2000 and we don't have to put a semicolon after each SQL statement, but some database programs force us to use it. Ques: 24 Define the Primary key? Ans: The Primary Key is bassically a key that is frequently used to identify a specific row other keys also may exist and all the other values are dependent on that value to be meaningfully identified. A primary key is usually one attribute or column in a relation or table, But can be a combination of attributes. Ques: 25 What do you mean by Candidate key? Ans: Condidate key is bassically use for when we added a new attribute in the table, We could also use the combination of other attribute with this new attribute to identify the row, as together they form a Composite Key. Thus we have two potential or Candidate Keys. Ques: 26 What is the Foriegn Key? Ans: Play History Catalogue No. Date Times Played

Supose we have a table whihc name is Play history and its have a three colums Catalogue No and Date anf Times Play.These are three Colums in a 1 row. In this situation the Catalogue No. number is a Primary Key in the CDs table but only part of the Composite Key in the Play History table as the date is required to form the whole key. An alternative could have been to create a new unique single-attribute Primary Key for the table. As we still need to know the catalogue number in order to work out how many times a DJ has played Britney, Christina or Pink. The catalogue number would become the Foreign Key in the Play History table,that is Foreign Key is a attribute or column in a table that refers to a Primary Key in another table. Ques: 27 What are the use of Null?

Ans: NULLs are bassically for use in database for descraibe that no value or attributes are exist, But are not really values themselves. Instead they are just an indictor that a particular field has no value. Some decussions are clarifying that it is better than no value i mean blank value or a default value. we are individually can see little value in a blank field, but default values can be useful. The interesting point about NULLs is that no Primary Key can contain a NULL and thus it's useful when comparing Candidate Keys to see if one could potentially contain a NULL, thus disqualifying that key. Ques: 28 What are the properties of the Relational tables? Ans: Relational tables have six properties which is there : > In this table Values are atomic. > In this table Column values are of the same kind. > In this table Each row is unique. > In this table The sequence of columns is insignificant. > In this table The sequence of rows is insignificant. > In this table Each column must have a unique name. Ques: 29 What is De-Normalization? Ans: De-Normalization is bassically the process, Which is attempting to optimize the performance of a database by adding redundant data. It is very important sometimes because current DBMS's implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, Even providing physical storage of data that is tuned for high performance. De-Normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. Ques: 30 What is the mean of Nested Trigger? Ans: A Trigger have a many authorities it can also perform to the INSERT,UPDATE and DELETE oprations or logic within itself, And whenever the trigger is fired the reason is that data modification, It can also the reason is another data modification, may be firing another trigger. A Trigger that contains data modification logic within itself is called a nested trigger. Ques: 31 What is a Linked Server? Ans: Linked Servers is bassically a concept in SQL Server, Its mainly use we can add the other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, We can also create very clean,easy to follow, And SQL statements that allow remote data to be retrieved, joined and combined with local data. Ques: 32 What is Cursor? Ans: Cursor is bassically a database object,which is manily used by applications to manipulate data in a set on a Row by Row basis, Inastead of use the typical SQL commands that operate on all the rows in the set at one time. In order to workwith a cursor we need to perform some steps in theFollowing order : > Declare cursor > Open cursor > Fetch row from the cursor

> Process fetched row > Close cursor > Deallocate cursor Ques: 33 What is Collation? Ans: Collation is bassically a collection to a set of rules that determine how to data is sorted and compared. Character data is sorted with using rules that defined the sequence of correct character, with specifying case sensitivity options,and accent marks, and kana character types and character width. Ques: 34 What is Difference between Function and Stored Procedure? Ans: Many didd are there : > UDF can be used WHERE/HAVING/SELECT section anywhere in the SQL statements, But in case of Stored procedures cannot be. > UDF's that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF's can be thought of as views that take parameters and can be used in JOINs and other Rowset operations. Ques: 35 What is the Sub-Query?And what is the properties of Sub-Query? Ans: Sub-queries are bassically defined as sub-selects, Its allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is mainly executed by enclosing in a set of parenthesis. Sub-queries are generally used to return a single row as an atomic value, They may be used to comparision, Its may be use for compare the values against multiple rows with the IN-keyword. A Subquery is a SELECT statement that is nested within another T-SQL statement. A Subquery SELECT statement if executed independently of the T-SQL statement, In which it is nested, will return a resultset. Meaning a subquery SELECT statement can stand alone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, The column list of a SELECT statement,FROM, GROUP BY,HAVING,and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used. Ques: 36 Give the list how many type of Joine? Ans: There are diff types of join : > Cross Join > Inner Join > Outer Join * Left Outer Join * Right Outer Join

* Full Outer Join > Self Join Ques: 37 Define : What is the Cross Join? Ans: A cross join is he type of join , That does not have a WHERE clause which is produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is bassically equal to the number of rows in the first table multiplied by the number of rows in the second table. For the example we can see when company wants to combine each product with a pricing table to analyze each product at each price. Ques: 38 give us a definition of Inner Join? Ans: Inner Join is a bassically use for presention the tables or formate, A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer.

Ques: 39 What do you mean by Outer Join? and define also how many types of Outer Join? Ans: Outer Join is the bassically use for a rows. That join includes rows even if related rows in the joined table are absent is an Outer Join. We can create three different outer join to specify the unmatched rows to be included : > Left Outer Join : In Left Outer Join all rows in the first& named table i.e. "left" table, which appears leftmost in the JOIN clause are included. Unmatched rows in the right table do not appear. > Right Outer Join: In Right Outer Join all rows in the second;named table i.e. "right" table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included. > Full Outer Join: In Full Outer Join all rows in all joined tables are included, whether they are matched or not. Ques: 40 Defeine : Self Join? Ans: Self Join is bassically use for the editing in the table itself , This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can joined tables which are the same. A self join is rather unique in that it involves a relationship with only one table. For the example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join also use can be Outer Join or Inner Join. Ques: 41 What is User Defined Functions? Ans: User Defined Functions is bassically signifies UDF, Its allow to define only its own T-SQL functions which is accept 0 or more parameters and return a single scalar data value or a table data type. Ques: 42 What kind of User-Defined Functions can be created? Ans: We can a creat User-Defined Functions in a many ways they are defined as : > Scalar User-Defined Function : A Scalar user-defined function is bassically a return value like one of the scalar data types. It is not a type of supported data types like Text,ntext,image and timestamp. These are the type of user-defined functions and most developers are used to in other programming languages. We pass in 0 to many parameters and We get a return value. > Inline Table-Value User-Defined Function : An Inline Table-Value user-defined function mainly returns the value like a table data type and It is an exceptional alternative to a view as the user-defined function, It can pass parameters into a T-SQL select command

and Its is poivide the essence with a parameterized, non-updateable view of the underlying tables. > Multi-statement Table-Value User-Defined Function : A Multi-Statement Table-Value user-defined function is bassically a returns a table and It is a type of view which we can say like an exceptional alternative view as the function can support multiple T&#8208;SQL statements to build the final result where the view is limited to a single SELECT statement. And Its also the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non&#8208;updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user&#8208;defined function, It can be used in the FROM clause of a T&#8208;SQL command unlike the behavior found when using a stored procedure which can also return record sets. Ques: 43 What is Identity? Ans: Identity is a bassically called as AutoNumber. It is mainly a column that automatically generates numeric values. When A start and increment value can be set, but most DBA leave these at 1. A identity or GUID column also generates numbers; thease type of values cannot be controlled. Identity/GUID columns do not need to be indexed. Ques: 44 What is DataWarehousing? Ans: DataWarehousing is the bassically mean that It is Subject-oriented, Its a meaning that the data in the database is organized so that all the data elements relating to the same real-world event or object are linked together. > It is Time-variant, Its a meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time. > It is Non-volatile, Its a meaning that data in the database is never over-written or deleted, Onaly once committed, The data ahould be static, And read-only, But retained for future reporting. > It is Integrated, Its meaning that the database contains data from most or all of an organization's operational applications, And that this data is made consistent. Ques: 45 What is the clustered index? Ans: A Clustered index is bassically a special type of index,its is mainly use for reorders the way of records in the table which is in the physically stored. Even table can have only one clustered index. the data pages contained on the leaf nodes of the clustered index . Ques: 46 What do you mean by A non clustered index? Ans: A Non Clustered Index is a special type of index, Which Indexes are in the logical order of the index, Its does not match the physical stored order of the rows on disk. The leaf node does not consist of the data pages Which is from non clustered index. Instead, The leaf nodes contain index rows. Ques: 47 What are the different index configurations a table can have? Ans: A Table can have Diff type of the index configurations, Which are following as : > No Indexes > A clustered index > A clustered index and many nonclustered indexes > A nonclustered index > Many nonclustered indexes Ques: 48 What are different types of Collation Sensitivity? Ans: There are many diff types of Collation Sensitivity, Which are following here : > Case Sensitivity : A and a, B and b, etc . > Accent Sensitivity : a and , o and , etc. > Kana Sensitivity : When the Japanese kana characters Hiragana and Katakana are treated differently, It is called Kana sensitive.

> Width Sensitivity : it is Bassically a single-byte character or half-width and the same character represented as a double-byte character or full-width are treated differently than it is width sensitive. Ques: 49 What is OLTP? Ans: OLTP stands for Online Transaction Processing Systems. It is mainly use for relational database design for use the discipline of data modeling and generally follow the Code rules of data normalization, It is in order to ensure absolute data integrity. It is Using these rules complex information is broken down into its most simple structures or a table, where all of the individual atomic level elements relate to each other and satisfy the normalization rules. Ques: 50 What do you mean by TRUNCATE? Ans: Truncate is bassically defined as : > It cannot be rolled back. > It is DDL Command. > It Resets identity of the table. > It is faster and uses fewer system and transaction log resources than DELETE. > It removes the data by deallocating the data pages used to store the tables data, and only the page deallocations are recorded in the transaction log. > It removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column. > We can't use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. Ques: 51 What do you mean by DELETE command? Ans: Delete Command bassically defines as : > It Can be used with or without a WHERE clause. > It Activates Triggers. > It can be rolled back. > It is DML Command. > It does not reset identity of the table. > DELETE removes rows one at a time and records an entry in the transaction log for each deleted row. > If we want to retain the identity counter, Which is use DELETE instead. If we want to remove table definition and its data, use the DROP TABLE statement. Ques: 52 When is the use of UPDATE_STATISTICS command? Ans: UPDATE_STATISTICS command is mainly used for the solving a problem when a large processing of data has occurred. If a large amount of deletions wants any modification or when the Bulk Copy into the tables has occurred, that time it has to update the indexes to take these changes into account. Its updates the indexes on these tables accordingly. Ques: 53 What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Ans: There are a many differences b/w HAVING CLAUSE and a WHERE CLAUSE : Having Clause is mainly used for the Group By function Its only with the GROUP BY function in a query, But In case of WHERE Clause is using only for rows, Its applied to each row before they are part of the GROUP BY function in a query. Both of Clouses are mainly specify a search condition for a group or an aggregate. But differences are there in the case of HAVING CLAUSE, it can be used only with the SELECT statement. And It is typically used in a GROUP BY clause. Even GROUP BY is not used, HAVING behaves something like a WHERE clause. Ques: 54 What are the properties of SUB-QUERY? Ans: There are many Properties of Sub-Query are there :

> Its must be enclosed in the parenthesis. > Its must be put in the right hand of the comparison operator. > Its cannot contain an ORDER-BY clause. > A query can contain more than one sub-query. Ques: 55 What are the type of SUB-QUERy? Ans: There are many types of SUB-QUERY : > Single-row sub-query: where the sub-query returns only one row. > Multiple-row sub-query : where the sub-query returns multiple rows, and > Multiple column sub-query : where the Sub-query returns multiple columns. Ques: 56 What is SQL Profiler? Ans: SQL Profiler is bassically a graphical tool, Which is maily use for alow to system administrators to monitor events in an instance of Microsoft SQL Server. We can capture and save data about each event to a file or SQL Server table to analyze later. For example, we can monitor a production environment to see which stored procedures are hampering performances by executing too slowly. Its mainly Use SQL Profiler to monitor only the events in which we are interested. We can filter the events based on the information we want, when It traces are becoming too large, That's why only a subset of the event data is collected.In server many overhead events are added from the Monitor and the monitoring process and becouse the trace file or trace table to grow very large, Specially when the monitoring process takes place over a long period of time. Ques: 57 What are the authentication modes in SQL Server? How can it be changed? Ans: Mainly Two modes are the Authentication Modes in SQL Server they are following as : Windows mode and Mixed Mode : SQL And Windows. Process of change the Authentication Mode in SQL Server : To change authentication mode in SQL Server click Start > Programs > Microsoft SQL Server > click SQL Enterprise Manager . When the open the Window of SWL Enterprise Manager it means it start to run from the Microsoft SQL Server program group. Now Select the server then going to Tools menu > select SQL Server Configuration Properties, and choose the Security page. Ques: 58 What is SQL Server Agent? Ans: SQL Server Agent is the very important for the Database administrator. Its a very good role or important role in database administrator (DBA) for work on day to day tasks. It is use overlooked as one of the main tools for SQL Server management. Its mainly use of the implementation of tasks for the DBA, with its full function scheduling engine, which allows us to schedule our own jobs and scripts. Ques: 59 Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible? Ans: Yes we can stored procedure call itself or recursive storeed procedure. Because Stored procedures is bassically are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. we can nest stored procedures and managed code references up to 32 levels. T-SQL supports recursion, we can write the stored procedures becouse of call, Recursion have a techniques or methods of problem solving, Where in the solution is appying o the problems it can be use of subset of problems only. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Ques: 60 What is Log Shipping? Ans: Log shipping is bassically a process of the datatbase and its maily use for transaction of the lof files on the production SQL Server, And its the process of automating the backup

of database. And then restoring them onto a standby server. Enterprise Editions is only supports log shipping. In the case of log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same database and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval. Memory Management Q95. What are disadvantages of having raw devices? Ans:We should depend on export/import utility for backup/recovery (fully reliable) The tar command cannot be used for physical file backup, instead we can use dd command, which is less flexible and has limited recoveries. Q96. List the factors that can affect the accuracy of the estimations? Ans:- The space used transaction entries and deleted records, does not become free immediately after completion due to delayed cleanout. - Trailing nulls and length bytes are not stored. - Inserts of, updates to and deletes of rows as well as columns larger than a single data block, can cause fragmentation a chained row pieces. Database Security & Administration Q97. What is user Account in Oracle database? Ans:A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges. Q98. How will you enforce security using stored procedures? Ans:Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. Q99. What are the dictionary tables used to monitor a database space? Ans:DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. SQL*Plus Statements

Q100. What are the types of SQL statement? Ans:Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT. Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT. Transactional Control: COMMIT & ROLLBACK Session Control: ALTERSESSION & SET ROLE System Control: ALTER SYSTEM.

Q101. What is a transaction? Ans:Transaction is logical unit between two commits and commit and rollback. Q102. What is difference between TRUNCATE & DELETE? Ans:TRUNCATE commits after deleting entire table i.e., cannot be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. Q103. What is a join? Explain the different types of joins? Ans:Join is a query, which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself. Equi Join - Joining two tables by equating two common columns. Non-Equi Join - Joining two tables by equating two common columns. Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table. Q104. What is the sub-query? Ans:Sub-query is a query whose return values are used in filtering conditions of the main query. Q105. What is correlated sub-query? Ans:Correlated sub-query is a sub-query, which has reference to the main query. Q106. Explain CONNECT BY PRIOR? Ans:Retrieves rows in hierarchical order eg. select empno, ename from emp where.

XHTML Interview Questions And Answers Page 1


Ques: 1 What you understand about XHTML? Ans: XHTML stands for eXtensible HyperText Markup Language.It is more formal and more Hard and fast version of HTML.We can define XHTML with XML dtd which make easy to handle XHTML. Some information about XHTML are given below: 1.Target of XHTML is to replace HTML. 2.We can say that HTML4.01 and XHTML are almost same. 3.It is an more Hard and Fast version of HTML. 4.XHTML has a W3C recomendation. 5.We can say that XHTML is an Transition/combination of HTML and XML. 6.It has got official recommendation from W3C on 26th Jan 2000. 7.Using XHTML we can easily validate our document. Ques: 2 Why we use XHTML? Ans: We use XHTML because of some important reasons those are given below: 1.XHTML can run on all new browsers. 2.It is an combination of HTML and XML so,it support many important features of them. 3.XHTML also give us facilitty to write well formed document.

4.XHTML has facility to extend.We perform this task with use of extra modules to do things withour pages.Wher as this facility not provided by HTML. I have given you a HTML example in that example can on browsers successfully but it is not support all rules of HTML. <html> <head> <title>This is wrong HTML code</title> <body> <h1>Wrong HTML code </body> In above example both html and head tags are not close.According to HTML rule it should not run.But it run successfully.So, It is an example of wrong html code. Ques: 3 How XHTML is differ from HTML? Ans: XHTML is an more formal,Hard and Fast version of HTML.Some main difference b/w XHTML and HTML are given below: 1.In XHTML element should be properly nested. 2.In XHTML when we started an element it must have closed tag. 3.XHTML support only lowercase element. 4.In an XHTML document one root element is necessary. But we can say that their is no much difference b/w HTML4.01 and XHTML. Ques: 4 Give an example shows properly nested element in XHTML? Ans: Ans: In HTML we can improperly nested some element each other like that, <b><i>Gives text as bold and italic</b></i> Where as In XHTML, all elements must be properly nested within each other like that, <b><i>Gives text as bold and italic</i></b> When you create nested lists keep one thing in mind list must be within <li> and </li> tags. <ul> <li>Coca cola</li> <li>Pepsi <ul> <li>black</li> <li>blue</li> </ul> </li> </ul> Ques: 5 Give example shows Element must be closed in XHTML? Ans: XHTML said an Empty and Non-Empty Elements must be closed. Example shows the case of Non-Empty Element. <p>Write here paragraph</p> <p>Write here another paragraph</p> Example shows the case of Empty Element. 1.Use to break <br /> 2.Use to horizontal rule <hr /> 3.<img src="r4r.gif" alt="r4r logo" /> Ques: 6 Give example shows Element must be written in XHTML? Ans: In XHTML Your Element must be Written in Lower Case. Example: <body> <p>Here write a paragraph</p> </body>

Ques: 7 Give example shows Document must have one root element in XHTML? Ans: In XHTML all elements should be nested in the <html> root element.Elements inside the <html> root element can have their child or elements an so on. I have given you basic structure of XHTML document. <html> <head>Write here heading</head> <body>Write here some code</body> </html> Ques: 8 What are the rule essential for XHTML Syntax? Ans: I have given you rules keep in mind when you want to create an XHTML document. Rule1:Write attribute names only in lower case letters. Rule2:Assigned attribute values must be quoted. Rule3:Attribute minimization must be prohibited. Rule4:In XHTML name attribute is replaced by id attribute. Rule5:In XHTML DTD must set mandatory elements. Example of Rule1:Write attribute names only in lower case letters. <table width="200%"> Example of Rule2:Assigned attribute values must be quoted. <table width="100%"> Example of Rule3:Attribute minimization must be prohibited. <input checked="checked" /> <input readonly="readonly" /> <input disabled="disabled" /> <option selected="selected" /> <frame noresize="noresize" /> Example of Rule4:In XHTML id attribute is replaced by name attribute. HTML 4.01 defines a name attribute for the elements a, applet, frame, iframe, img, and map. <img src="r4r.gif" id="r4r" /> I have add a extra space before '/' to make our XHTML document with current browsers. Using lang attribute we can specify the language of content. <div lang="no" xml:lang="no">Arial</div> Example of Rule5:In XHTML DTD must set mandatory elements. DOCTYPE declaration is essential for each XHTML document. The html, head and body elements must be present.Write title element inside the head. <!DOCTYPE Doctype write here> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Write here title</title> </head> <body> </body> </html> DOCTYPE declaration is not an XHTML element.So, Their is no need to closed DOCTYPE declaration. Ques: 9 How you define DTD in XHTML?

Ans: Before I given use of DTD. I want to remember what is DTD. DTD: Its stand for Document Type Declaration. It specify the syntax of web page in SGML. We use DTD on SGML applications like: HTML,XML etc.In XHTML we can say that DTD is an computer readable language which is used to allow syntax of XHTML. In XHTML we use These three DTD's, 1.STRICT 2.TRANSITIONAL 3.FRAMESET 1.Strict DTD: We use strict DOCTYPE if we want really clean markup, free of presentational clutter.And also use together with CSS. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2.Transitional DTD: We use transitional DOCTYPE if we want to still use HTML's presentational features. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3.Frameset DTD:We use frameset DOCTYPE if we want to use HTML Frames to split our web page into two or more frames. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> Ques: 10 How to print "Hello World!" using XHTML? Ans: To print "Hello World!" you have to write following code. <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Hello World!</title> </head> <body> <p>This is first XHTML coded web page.</p> </body> </html> </p> Ques: 11 How you use img and hr tag in XHTML because both tags doesn't have closed tag? Ans: I have given you solution of how to use img and hr tag in XHTML.Now,the solution for given problem is that, Add only hte forward slash in element. <img src="r4r.gif" /> Write text <hr /> Keep in mind when use forward slash you should add an extra slash before forward slash. Ques: 12 Why their is a need of modular DTDs in XHTML? Ans: Using modularity it easier to deploy new developments. An application may wish to support only a subset of XHTML. For example a mobile phone, an Internet TV or even a Web-aware cooker may only require a subset of XHTML.

Ques: 13 How you perform validation in XHTML? Ans: We can Validate our XHTML document by using W3C's validator. Here, I given you example which is validate our XHTML document with DTD. Example In which I validate our XHTML document using strict DTD. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>title of the document</title> </head> <body> <p>Here write a paragraph</p> </body> </html> Ques: 14 What assumption that we use with XHTML? Ques: 15 What are the advantages of XHTML? Ans: Some main advantage of XHTML are given below: 1.In XHTML we can use mixed namespaces. 2.work on XHTML is much simple than HTML. 3.When your document is not well formed than it will immediately informed to you due to an error from your UA in XHTML. Ques: 16 Tell me how to convert an HTML page into XHTML? Ans: If we want to convert HTML pages into XHTML than you have to insert some lines at the starting of document. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> Ques: 17 Write example that shows every attribute must have a value in XHTML? Ans: Using example I will show you in XHTML every attribute must have a value. Example in HTML: <ol compact> <input type="radio" name="title" value="decline" checked>decline</input> Below, I write a same example in XHTML. <ol compact="compact" > <input type="radio" name="title" value="decline" checked="checked">decline</input> In this we assign value compact, checked to element compact and checked. Ques: 18 In XHTML tags may overlap or not? Ans: In XHTML tags may not be overlapped. Example: <em> emphasized text and <b>bold </em>text</b> We can use above example in XHTML like that, <em>emphasized text </em> is <b>bold text</b> Ques: 19 Is is right only certain tags may nest inside other tags in XHTML? Ans: Yes, In XHTML we can insert only certain tags inside other tags. Example: <ol>

Some my favorite flowers are: <li>lotus</li> <li>lilly</li> <li>sunflower</li> and my most favorite flower is: <li>red rose</li> </ol> In the above example we insert the paragraph between <li> tag.It's wrong. In case of XHTML our example looks like that, becomes <p>Some my favorite flowers are:</p> <ol> <li>lotus</li> <li>lilly</li> <li>sunflower</li> <li>red rose</li> </ol> Ques: 1 Is is right only certain tags may nest inside other tags in XHTML? Ans: Yes, In XHTML we can insert only certain tags inside other tags. Example: <ol> Some my favorite flowers are: <li>lotus</li> <li>lilly</li> <li>sunflower</li> and my most favorite flower is: <li>red rose</li> </ol> In the above example we insert the paragraph between <li> tag.It's wrong. In case of XHTML our example looks like that, becomes <p>Some my favorite flowers are:</p> <ol> <li>lotus</li> <li>lilly</li> <li>sunflower</li> <li>red rose</li> </ol> Ques: 2 In XHTML tags may overlap or not? Ans: In XHTML tags may not be overlapped. Example: <em> emphasized text and <b>bold </em>text</b> We can use above example in XHTML like that, <em>emphasized text </em> is <b>bold text</b> Ques: 3 Write example that shows every attribute must have a value in XHTML? Ans: Using example I will show you in XHTML every attribute must have a value. Example in HTML: <ol compact> <input type="radio" name="title" value="decline" checked>decline</input> Below, I write a same example in XHTML. <ol compact="compact" > <input type="radio" name="title" value="decline" checked="checked">decline</input>

In this we assign value compact, checked to element compact and checked. Ques: 4 Tell me how to convert an HTML page into XHTML? Ans: If we want to convert HTML pages into XHTML than you have to insert some lines at the starting of document. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> Ques: 5 What are the advantages of XHTML? Ans: Some main advantage of XHTML are given below: 1.In XHTML we can use mixed namespaces. 2.work on XHTML is much simple than HTML. 3.When your document is not well formed than it will immediately informed to you due to an error from your UA in XHTML. Ques: 6 What assumption that we use with XHTML? Ques: 7 How you perform validation in XHTML? Ans: We can Validate our XHTML document by using W3C's validator. Here, I given you example which is validate our XHTML document with DTD. Example In which I validate our XHTML document using strict DTD. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>title of the document</title> </head> <body> <p>Here write a paragraph</p> </body> </html> Ques: 8 Why their is a need of modular DTDs in XHTML? Ans: Using modularity it easier to deploy new developments. An application may wish to support only a subset of XHTML. For example a mobile phone, an Internet TV or even a Web-aware cooker may only require a subset of XHTML. Ques: 9 How you use img and hr tag in XHTML because both tags doesn't have closed tag? Ans: I have given you solution of how to use img and hr tag in XHTML.Now,the solution for given problem is that, Add only hte forward slash in element. <img src="r4r.gif" /> Write text <hr /> Keep in mind when use forward slash you should add an extra slash before forward slash. Ques: 10 How to print "Hello World!" using XHTML? Ans: To print "Hello World!" you have to write following code. <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head>

<title>Hello World!</title> </head> <body> <p>This is first XHTML coded web page.</p> </body> </html> </p> Ques: 11 How you define DTD in XHTML? Ans: Before I given use of DTD. I want to remember what is DTD. DTD: Its stand for Document Type Declaration. It specify the syntax of web page in SGML. We use DTD on SGML applications like: HTML,XML etc.In XHTML we can say that DTD is an computer readable language which is used to allow syntax of XHTML. In XHTML we use These three DTD's, 1.STRICT 2.TRANSITIONAL 3.FRAMESET 1.Strict DTD: We use strict DOCTYPE if we want really clean markup, free of presentational clutter.And also use together with CSS. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2.Transitional DTD: We use transitional DOCTYPE if we want to still use HTML's presentational features. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3.Frameset DTD:We use frameset DOCTYPE if we want to use HTML Frames to split our web page into two or more frames. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> Ques: 12 What are the rule essential for XHTML Syntax? Ans: I have given you rules keep in mind when you want to create an XHTML document. Rule1:Write attribute names only in lower case letters. Rule2:Assigned attribute values must be quoted. Rule3:Attribute minimization must be prohibited. Rule4:In XHTML name attribute is replaced by id attribute. Rule5:In XHTML DTD must set mandatory elements. Example of Rule1:Write attribute names only in lower case letters. <table width="200%"> Example of Rule2:Assigned attribute values must be quoted. <table width="100%"> Example of Rule3:Attribute minimization must be prohibited. <input checked="checked" /> <input readonly="readonly" /> <input disabled="disabled" />

<option selected="selected" /> <frame noresize="noresize" /> Example of Rule4:In XHTML id attribute is replaced by name attribute. HTML 4.01 defines a name attribute for the elements a, applet, frame, iframe, img, and map. <img src="r4r.gif" id="r4r" /> I have add a extra space before '/' to make our XHTML document with current browsers. Using lang attribute we can specify the language of content. <div lang="no" xml:lang="no">Arial</div> Example of Rule5:In XHTML DTD must set mandatory elements. DOCTYPE declaration is essential for each XHTML document. The html, head and body elements must be present.Write title element inside the head. <!DOCTYPE Doctype write here> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Write here title</title> </head> <body> </body> </html> DOCTYPE declaration is not an XHTML element.So, Their is no need to closed DOCTYPE declaration. Ques: 13 Give example shows Document must have one root element in XHTML? Ans: In XHTML all elements should be nested in the <html> root element.Elements inside the <html> root element can have their child or elements an so on. I have given you basic structure of XHTML document. <html> <head>Write here heading</head> <body>Write here some code</body> </html> Ques: 14 Give example shows Element must be written in XHTML? Ans: In XHTML Your Element must be Written in Lower Case. Example: <body> <p>Here write a paragraph</p> </body> Ques: 15 Give example shows Element must be closed in XHTML? Ans: XHTML said an Empty and Non-Empty Elements must be closed. Example shows the case of Non-Empty Element. <p>Write here paragraph</p> <p>Write here another paragraph</p> Example shows the case of Empty Element. 1.Use to break <br /> 2.Use to horizontal rule <hr /> 3.<img src="r4r.gif" alt="r4r logo" /> Ques: 16 Give an example shows properly nested element in XHTML? Ans: Ans: In HTML we can improperly nested some element each other like that,

<b><i>Gives text as bold and italic</b></i> Where as In XHTML, all elements must be properly nested within each other like that, <b><i>Gives text as bold and italic</i></b> When you create nested lists keep one thing in mind list must be within <li> and </li> tags. <ul> <li>Coca cola</li> <li>Pepsi <ul> <li>black</li> <li>blue</li> </ul> </li> </ul> Ques: 17 How XHTML is differ from HTML? Ans: XHTML is an more formal,Hard and Fast version of HTML.Some main difference b/w XHTML and HTML are given below: 1.In XHTML element should be properly nested. 2.In XHTML when we started an element it must have closed tag. 3.XHTML support only lowercase element. 4.In an XHTML document one root element is necessary. But we can say that their is no much difference b/w HTML4.01 and XHTML. Ques: 18 Why we use XHTML? Ans: We use XHTML because of some important reasons those are given below: 1.XHTML can run on all new browsers. 2.It is an combination of HTML and XML so,it support many important features of them. 3.XHTML also give us facilitty to write well formed document. 4.XHTML has facility to extend.We perform this task with use of extra modules to do things withour pages.Wher as this facility not provided by HTML. I have given you a HTML example in that example can on browsers successfully but it is not support all rules of HTML. <html> <head> <title>This is wrong HTML code</title> <body> <h1>Wrong HTML code </body> In above example both html and head tags are not close.According to HTML rule it should not run.But it run successfully.So, It is an example of wrong html code. Ques: 19 What you understand about XHTML? Ans: XHTML stands for eXtensible HyperText Markup Language.It is more formal and more Hard and fast version of HTML.We can define XHTML with XML dtd which make easy to handle XHTML. Some information about XHTML are given below: 1.Target of XHTML is to replace HTML. 2.We can say that HTML4.01 and XHTML are almost same. 3.It is an more Hard and Fast version of HTML. 4.XHTML has a W3C recomendation. 5.We can say that XHTML is an Transition/combination of HTML and XML. 6.It has got official recommendation from W3C on 26th Jan 2000. 7.Using XHTML we can easily validate our document. Ques: 1 What do you understand about DOCTYPE in HTML? Ans: DOCTYPE is stands for Document Type Declaration.In an HTML every HTML document is

started with DOCTYPE declaration.It may be differ for different versions of HTML.DOCTYPE is used only bySGML tools like as HTML validator. Example of Document Type Declaration in HTML 4 are, <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> Ques: 2 How Cell Padding is differ from Cell Spacing? Ans: I have given you how cell padding is differ from cell spacing given below: Cell Padding: Cell Padding in HTML: is used to define the how much space need b/n cell content and cell edges. Syntax: < table width="200" border="1" cellpadding="3"> means that it takes 3 pixels of padding inside the each cell. Cell Spacing: It is also used to format the table.but it differ than cell padding because in cell padding we can set an extra space to seperate the cell content with cell edges.Where as we use cell spacing to set the space b/w the cells.

Page 1
Ques: 1 What is the features of DHTML? Ans: Some most important features of DHTML are given below: 1.Using DHTML we can change the tags and their properties. 2.It is use for Real-time positioning. 3.It is used to generate dynamic fonts (Netscape Communicator). 4.Used for Data binding (Internet Explorer). Ans: 4. Ques: 2 How FontSize and Font Size is differ in DHTML? Ans: font size is an attribute that we used in font tag.Where as font-size is an style property. <font size="5"> use in font tag. p{font-size:"5"} use in CSS.

Ques: 3 What is the difference b/w DHTML and HTML? Ans: Some main difference b/w DHTML(Dynamic HTML) and HTML(Hyper Text Markup Language)are given below. 1.Using DHTML we can use JavaScript and style sheets in our HTML page. 2.Using DHTML we can insert small animations and dynamic menus into our HTML page. 3.If use want that your web page display your DHTML effects(object or word can highlighted, larger,a different color etc) than you have to save your web page with .dhtml extension except .html or .htm . Ques: 4 How to Handle Events with DHTML? Ans: Event is use to trigger actions in the browser. When client click on the element, associated action will started.Like: an JavaScript will started when client click on element. Using Event Handler we can do like that,When an event occur it will execute code associated with that element. Example: In this example header will changes when client clicks.

<h1 onclick="this.innerHTML='abc!'">Click on this text</h1> We can add a script in the head section and then we call the function from the event handler. Example: <html> <head> <script type="text/javascript"> function changetext(id) { id.innerHTML="abc!"; } </script> </head> <body> <h1 onclick="changetext(this)">Click on this text</h1> </body> </html> Ques: 5 How to change HTML Attribute using HTML DOM? Ans: I have given you example to change HTML Attribute by using HTML DOM. Example: <html> <body> <img id="image" src="oldimage.gif"> <script type="text/javascript"> document.getElementById("image").src="newimage.jpg"; </script> </body> </html> In the above example we load an image on HTML document by using id="image".Using DOM we get the element with id="image".JavaScript that we used in example to changes the src attribute from oldimage.gif to newimage.jpg Ques: 6 How to change an HTML element using HTML DOM? Ans: Here,I have given you example to change an HTML element using HTML DOM.<html><body><h1 id=\"header\">This is your Old Header</h1><script type=\"text/javascript\">document.getElementById(\"header\").innerHTML=\"This is your New Header\";</script></body></html>Output:This is your New Header In the above example it will store header with an id="header". And get the element with id="header" by using DOM.We used JavaScript to change the content of HTML. Ques: 7 How you define HTML DOM? Ans: HTML DOM is an Document Object Model for HTML. HTML DOM is an standard set of objects and way to access and manipulate HTML document.Using HTML DOM we can view whole HTML document as tree structure.Using this DOM tree we can access and manipulate all elements with their text and attributes. Some important points about HTML DOM are given below: 1.It is an standard object model and standard programming interface for HTML. 2.HTML DOM is an plateform and language dependant. 3.It is an W3C standard to get,change,add or delete HTML element. Ques: 8 How we used JavaScript with CSS? Ans: Using CSS with JavaScript we can change the style of HTML elements.Like that, document.getElementById(id).style.property=new style Ques: 9 How to use JavaScript with HTML event?

Ans: In HTML4, we use HTML event to trigger the events than they perform their action.We can do like that when we click on event it will JavaScript. Example: onclick=JavaScript Ques: 10 How we used JavaScript with HTML DOM? Ans: In HTML4, We use them to dynamically change the inner content and attributes of HTML elements. I have you example which shows you how to change the content of HTML element. document.getElementById(id).innerHTML=new HTML We can change the attribute of an HTML element like that, document.getElementById(id).attribute=new value Ques: 11 How DHTML work with JavaScript? Ans: Using JavaScript we can made dynamic HTML content. We can use document.write() to show dynamic content on your web page.Below I have given you HTML page which made dynamic after using JavaScript.This example will show current date. Example: <html> <body> <script type="text/javascript"> document.write(Date()); </script> </body> </html> Ques: 12 Tell about technologies that we use in DHTML? Ans: Some technologies that we used in DHTMl are given below: 1.JavaScript 2.HTML DOM 3.HTML EVENT 4.CSS 1.JavaScript: It is an standard of scripting for HTML. Using JavaScript DHTML can control,access and manipulate HTML element. 2.HTML DOM: It is an Document Object Model which is an W3C Standard for HTML.Using HTML DOM is used to define standard to set of objects and to access and manipulate them for HTML.Using HTML DOM, DHTML can access and manipulate HTML elements. 3.HTML Events: It is an part of HTML DOM and used to handle HTML elements.We use DHTML with HTML Events to make web pages those perform action when event occour. 4.CSS: It is an W3C standard style and layout model made only for HTML. DHTML use JavaScript and DOM to change position and style of HTML elements. Ques: 13 What is DHTML? Ans: Defination of DHTML according to W3c(World Wide Web Consortium) is: "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated." DHTML stands for Dynamic HTML.DHTML is not an language. Using DHTML we can use DOM, CSS , JavaScript and HTML together. We use DHTML to make the web pages dynamic and interactive.

You might also like