How SOAP server process the requests

  1. The SOAP server receives the request from the client as an HTTP request.

  2. The request is passed to the HTTP request handler that redirects the request to the appropriate SOAP servlet. This SOAP servlet is responsible for decoding the HTTP request.

  3. The SOAP servlet directs the request to the HTTP/SOAP decoder. The decoder extracts the original service call from the HTTP request.

  4. The request is processed by the SOAP server, and the result is passed to the HTTP/SOAP encoder.

  5. The HTTP/SOAP encoder wraps the result in an HTTP response and passes it back to the SOAP servlet.

  6. The SOAP servlet, in turn, passes the response to the client.

Explain SOAP messaging model

  1. The client application discovers a server application by using its discovery document and makes a service call to the server application by invoking its appropriate method.

  2. The SOAP serializer converts the invocation by the client application to a SOAP request.

  3. The SOAP serializer sends the SOAP request to an HTTP encoder, which wraps the SOAP request in an HTTP request, because the request needs to be sent from the client to the SOAP server as an HTTP request.

  4. The response from the server is received in the HTTP format by the HTTP decoder module.

  5. The HTTP decoder module decodes the HTTP response and extracts the SOAP message from the response. The SOAP message is sent to the SOAP deserializer.

  6. The SOAP deserializer decodes the SOAP message and passes the result to the client application.

Explain SOAP messaging model

  1. The client application discovers a server application by using its discovery document and makes a service call to the server application by invoking its appropriate method.

  2. The SOAP serializer converts the invocation by the client application to a SOAP request.

  3. The SOAP serializer sends the SOAP request to an HTTP encoder, which wraps the SOAP request in an HTTP request, because the request needs to be sent from the client to the SOAP server as an HTTP request.

  4. The response from the server is received in the HTTP format by the HTTP decoder module.

  5. The HTTP decoder module decodes the HTTP response and extracts the SOAP message from the response. The SOAP message is sent to the SOAP deserializer.

  6. The SOAP deserializer decodes the SOAP message and passes the result to the client application.

What are SOAP attribtutes

A client can use SOAP attributes to specify how SOAP messages should be processed.

SOAP attributes are generally used to specify the serialization rules to indicate the recipient of the Header element of the SOAP message.

Attributes also indicate whether or not the recipient should process certain header entries.

example1:

The mustUnderstand attribute states whether or not the SOAP processor should process the header information. The usage of this attribute is given below:

soap:mustUnderstand = "true"

After the mustUnderstand attribute is set to true, the SOAP toolkit needs to compulsorily process the statement. If the toolkit is unable to process the statement, it should return a fault code signifying that there was an error in interpreting the statement.

example 2:

The actor attribute of a SOAP message specifies URI to indicate who should receive the Header element of the SOAP message. If no URI is specified, it is assumed that the ultimate SOAP receiver should receive the SOAP message.

The actor attribute has the following syntax:

soap:actor="URI"

What is SOAP fault

SOAP defines a Fault element that is used to indicate errors that might be raised when the SOAP message is processed. The Fault element is defined below:

<soap:Fault>
   <faultcode>SOAP-ENV:Server.BadTargetObjectURI</faultcode>
   <faultstring>Unable to resolve target object: 
   HelloWorld</faultstring>
</soap:Fault>

After you include the Fault element described above, every time the target URI is irresolvable, the application will return a fault packet.

Why SOAP header is optional

Tthe Header element is optional in a SOAP message. If the Header element is present in a SOAP message, it should be the first child element of the Envelope element.

To understand why a SOAP header element is optional, consider a scenario in which you want to invoke a Web method of a Web service by using the SOAP protocol. The Web method might expect three parameters. However, to ensure that the call to the Web method is secure, you might have to encrypt the request that is sent to the Web service.

The Web method is not concerned with the encrypted information. Instead, the Web method only expects three parameters to process business logic. To have the call to the Web method decrypted before the method is executed, you can add the necessary encoded information in the Header element.

However, if the request to the Web method is sent in an unencrypted form, you might not need the Header element.

Explain different Web Services communication Models

RPC-Based Communication Model

The RPC-based communication model defines a request/response-based synchronous communication. When the client sends a request, the client waits until a response is sent back from the server before continuing any operation. Typical to implementing CORBA or RMI communication, the RPC-based Web services are tightly coupled and are implemented with remote objects to the client application.

 

Messaging-Based Communication Model

The messaging-based communication model defines a loosely coupled and document-driven communication. The service requestor invoking a messaging-based service provider does not wait for a response.

Define ebXML

ebXML provides a standard framework for building an electronic marketplace by enabling the standardization of business processes, business partner profiles, and partner agreements. In general, ebXML complements other Web services standards like SOAP, WSDL, and UDDI.

The following are major features of ebXML:

  • ebXML Messaging Service (MS) is a value-add over SOAP that provides reliability and security mechanisms.

  • ebXML BPSS enables business processes to be described.

  • ebXML CPP/CPA is a value-add over WSDL that enables business partner profiles and partner agreements to be described.

  • ebXML reg/rep provides a registry and repository, while UDDI is just a registry.

  • ebXML Core components provide a catalogue of business process components for the business community.

Define UDDI

Universal Description, Discovery, and Integration, or UDDI, defines a mechanism to register and categorize Web services in a general-purpose registry that users communicate to in order to discover and locate registered services. While querying a UDDI registry for a service, the WSDL description describing the service interface will be returned. Using the WSDL description, the developer can construct a SOAP client interface that can communicate with the service provider.

UDDI can be implemented as a public registry to support the requirements of a global community or as a private registry to support an enterprise or a private community.

Define SOAP

SOAP is an XML-based protocol that is used to access services, objects, and servers in a platform- and vendor- independent manner.it is an XML-based protocol.SOAP generally uses HTTP, a firewall-friendly protocol, as its transport protocol.

SOAP includes three components: SOAP messages, SOAP attributes, and SOAP encoding.

SOAP Messages

SOAP is an XML-based protocol, SOAP messages are encoded in the XML format. A SOAP message contains the following XML elements:

Envelope: It is a mandatory element of SOAP message and it identifies the XML document as SOAP message. It contains other elements, declarations and attributes required for processing SOAP message.

Header: The SOAP header, which is an optional element, defines the header information. it should be the first child element of the Envelope element. It is used to provide encription information.

Body: The SOAP body, which is a mandatory element, contains all the information that the message recipient needs. It typically contains method calls and response information for the SOAP message.

Example:

<soap:Envelope>
    <soap:Header>
          ...Header informations ...
    </soap:Header>
    <soap:Body>
       <GetStockValue>
            <Item>Cake</Item>
       </GetStockValue>
    </soap:Body>
</soap:Envelope>

Explain benefits of web services

  • Provides a simple mechanism for applications to become services that are accessible by anyone, anywhere, and from any device.

  • Defines service-based application connectivity facilitating EAI, and intra-enterprise and inter-enterprise communication.

  • Defines a solution for businesses, which require flexibility and agility in application-to-application communication over the Internet.

  • Enables dynamic location and invocation of services through service brokers (registries).

  • Enables collaboration with existing applications that are modeled as services to provide aggregated Web services.

What are disadvantages/challenges in web services

Distributed transactions. If the environment requires distributed transactions with heterogeneous resources, it should be studied and tested with standard solutions based on BTP, WS-Transactions, and WS-Coordination.

Quality of Service (QoS). In case of a mission-critical solution, the service providers must examine the reliability and performance of the service in peak load and uncertain conditions for high availability. The exposed infrastructure must provide load balancing, and fail-over and fault tolerance, to resolve these scenarios.

Security. Web services are exposed to the public using http-based protocols. As Web services is publicly available, it must be implemented using authentication and authorization mechanisms and using SSL-enabling encryption of the messages for securing the usage. Adopting open security standards like SAML, XML Encryption, XML Signature, or XACML may be a solution.

What is WSDL

  • The Web Services Definition Language (WSDL) standard is an XML format for describing the network services and its access information.
  • WSDL is used as the metadata language for defining Web services and describes how service providers and requesters communicate with one another.
  • WSDL describes the Web services functionalities offered by the service provider, where the service is located, and how to access the service.
  • Usually the service provider creates Web services by generating WSDL from its exposed business applications. A public/private registry is utilized for storing and publishing the WSDL-based information.

Explain Basic Architecture of Web Services

Service provider. The service provider is responsible for developing and deploying the Web services. The provider also defines the services and publishes them with the service broker.

Service broker. The service broker (also commonly referred to as a service registry) is responsible for service registration and discovery of the Web services. The broker lists the various service types, descriptions, and locations of the services that help the service requesters find and subscribe to the required services.

Service requestor. The service requestor is responsible for the service invocation. The requestor locates the Web service using the service broker, invokes the required services, and executes it from the service provider.

Why to use webservices

  1. Web services can be invoked through XML-based RPC mechanisms across firewalls.
  2. Web services provide a cross-platform, cross-language solution based on XML messaging.
  3. Web services facilitate ease of application integration using a lightweight infrastructure without affecting scalability.
  4. Web services enable interoperability among heterogeneous applications.

What are Web Services

  • Web services are based on the concept of service-oriented architecture (SOA). SOA is the latest evolution of distributed computing, which enables software components, including application functions, objects, and processes from different systems, to be exposed as services.
  • Web services are loosely coupled software components delivered over Internet standard technologies.”
  • Web services are self-describing and modular business applications that expose the business logic as services over the Internet through programmable interfaces and using Internet protocols for the purpose of providing ways to find, subscribe, and invoke those services.
  • Web services can be developed as loosely coupled application components using any programming language, any protocol, or any platform. This facilitates delivering business applications as a service accessible to anyone, anytime, at any location, and using any platform.
  • Web services are typically implemented based on open standards and technologies specifically leveraging XML. The XML-based standards and technologies, such as Simple Object Access Protocol (SOAP); Universal Description, Discovery, and Integration (UDDI); Web Services Definition Language (WSDL); and Electronic Business XML (ebXML), are commonly used as building blocks for Web services.

Design Patterns : Drill

What is a design pattern.
————————————–
“Design patterns are recurring solutions to design problems you see over
Alpert, et. al., 1998).
“Design patterns constitute a set of rules describing how to accomplish
certain tasks in the realm of software development.” (Pree, 1994)

How many catogeries are there in Java patterns.
————————————————–
Creational patterns are ones that create objects for you, rather than
having you instantiate objects directly. This gives your program more
flexibility in deciding which objects need to be created for a given case.
Structural patterns help you compose groups of objects into larger
structures, such as complex user interfaces or accounting data.
Behavioral patterns help you define the communication between objects
in your system and how the flow is controlled in a complex program.

Design Patterns is a catalog of 23 generally useful patterns for writing objectoriented software.

Give me an example of Creational Patterns.
——————————————————
All of the creational patterns deal with the best way to create instances of objects. This is important because your program should not depend on how objects are created and arranged. In Java, of course, the simplest way to create an instance of an object is by using the new operator.

Sharat = new Sharat(); //instance of Fred class

However, this really amounts to hard coding how you create the object within your program. In many cases, the exact nature of the object that is created could vary with the needs of the program from time to time and abstracting the creation process into a special “creator” class can make your program more flexible and general.

The Factory Pattern is used to choose and return an instance of a class from a number of similar classes based on data you provide to the factory.
The Abstract Factory Pattern is used to return one of several groups of classes. In some cases it actually returns a Factory for that group of classes.
The Builder Pattern assembles a number of objects to make a new object, based on the data with which it is presented. Frequently, the choice of which way the objects are assembled is achieved using a Factory.
The Prototype Pattern copies or clones an existing class rather than creating a new instance when creating new instances is more expensive.
The Singleton Pattern is a pattern that insures there is one and only one instance of an object, and that it is possible to obtain global access to that one instance.

What is Singleton pattern. Where did you use it.
——————————————————
Definition: Singleton pattern is used whenever we require a class to have only one instance throughout the application. Sometimes it’s appropriate to have exactly one instance of a class: If we need some data to be stored , used and manipulated the same instance by the whole application, we will use singleton pattern. 

  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class’s clients

Examples:

  • window managers, print spoolers, and filesystems are prototypical examples.
  • Search window in Microsoft word, even if multiple documents are open, only one search window will be opened.  
  • One important usage of singleton pattern is when you need to instantiate a subclass and check which class to be instantiated during run time. For example there are two subclasses one for production and one for development and we need to instantiate one during run time depending on the environment.

Syntax:

public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

public class SingletonInstantiator {
  public SingletonInstantiator() {
   ClassicSingleton instance = ClassicSingleton.getInstance();
ClassicSingleton anotherInstance =
new ClassicSingleton();
       …
  }
}
Explanation: In the first line we have created an instance of this class as null. We have declared a private constructor for the class to make sure that no object of class can be created outside the class.

getInstance() method is the entry point for the class which will return the only instance present for the class. This method is marked as static as it will be called directly from other classes. In this method we check if the instance of singletonExample is already present, if yes, return that instance else create the instance and return it. This makes sure that only one instance of the class is present at any point.

In the user class, that is calling our singleton class, we just need to call our singletonExample.getinstance() method which will return us the instance of singletonExample.

Types:

  • we create an instance of singleton class only when it is called for the first time is called lazy instantiation.
  • Another variation can be creating the instance before it is called, this kind of instantiation is called eager instantiation.

Problems:

  • A side effect of using singleton class: as the constructor of the singleton class is private, you cannot create a subclass of a singleton class, but in most of the cases that is desirable.
  • Additionally you can declare the class as final to explicitly show that the class can’t be subclassed. But in case if it is required to create a subclass of singleton class one can define the constructor of singleton class as protective instead of private.
  • Another point to note is that the singleton classes are not thread-safe.

Making your singleton class thread-safe is easy, you just have to make your getinstance method synchronized.

Public synchronized static singletonExample getInstance()
{
//if instance is null create else return old instance
}

What is Factory pattern. Explain it.
——————————————————

  • if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.
  • provides a simple decision making class which returns one of several possible subclasses of an abstract base class depending on data it is provided.
  • Usually all of the classes it returns have a common parent class and common methods,but each of them performs a task differently and is optimized for differentkinds of data.

You should consider using a Factory pattern when
· A class can’t anticipate which kind of class of objects it must create.
· A class uses its subclasses to specify which objects it creates.
· You want to localize the knowledge of which class gets created.

Needs to isolate concrete classes from their super classes.

  • A system needs independent of how its products are created, composed, and represented.
  • Java Design Pattern

    1.What is a design pattern.
    2.How many catogeries are there in Java patterns.
    3. How many patterns did you use in your project.
    4.Give me an example of Creational Patterns.
    5.What is Singleton pattern. Where did you use it.
    6.How do you use Factory pattern.
    7.Can explaing examples of Structural Patterns.
    8.What is difference between adapter pattern and decorator pattern.
    9.What is Facade Pattern. Give an example.
    10.Did you use proxy pattern.
    11.Give me some examples of Behavioral Patterns.
    12.What is Observer Pattern.
    13.Do you know the difference between Command pattern and interpreter pattern.
    14.What is Visitor Pattern.

    Java Drill – 2

    1.Can a private method of a superclass be declared within a subclass?
    2.Why Java does not support multiple inheritence ?
    3.What is the difference between final, finally and finalize?
    4.Where and how can you use a private constructor.
    5.In System.out.println(),what is System,out and println,pls explain?
    6.What is meant by “Abstract Interface”?
    7.Can you make an instance of an abstract class? For example – java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.
    8.What is the output of x<y? a:b = p*q when x=1,y=2,p=3,q=4?
    9.Why Java does not support pointers?
    10.Parsers? DOM vs SAX parser
    11.What is the main difference between Java platform and other platforms?
    12.What is the Java Virtual Machine?
    13.What is the Java API?
    14.What is the package?
    15.What is native code?
    16.Is Java code slower than native code?
    17.What is the serialization?
    18.How to make a class or a bean serializable?
    19.How many methods in the Serializable interface?
    20.How many methods in the Externalizable interface?
    21.What is the difference between Serializalble and Externalizable interface?
    22.What is a transient variable?
    23.What is synchronization and why is it important?
    24.What are synchronized methods and synchronized statements?
    25.What are three ways in which a thread can enter the waiting state?
    26.Can a lock be acquired on a class?
    27.What is thread?
    28.What is multithreading?
    29.How does multithreading take place on a computer with a single CPU?
    30.What is the purpose of the wait(), notify(), and notifyAll() methods?
    31.What are the high-level thread states?
    32.What is the Collections API?
    33.How does Java handle integer overflows and underflows?
    34.What is the Vector class?
    35.If a method is declared as protected, where may the method be accessed?
    36.What is an Iterator interface?
    37.What is the difference between yielding and sleeping?
    38. Is sizeof a keyword?
    39.What are wrapped classes?
    40.What is the difference between preemptive scheduling and time slicing?
    41.How can you write a loop indefinitely?
    42.Can an anonymous class be declared as implementing an interface and extending a class?
    43.Which class is the superclass for every class.
    44. What is the difference between the Boolean & operator and the && operator?
    45.What is the GregorianCalendar class?
    46.What is the SimpleTimeZone class?
    47.What is the Properties class?
    48.What is the purpose of the Runtime class?
    49.What is the purpose of the System class?
    50.What is the purpose of the finally clause of a try-catch-finally statement?
    51.What must a class do to implement an interface?
    52.What is a static method?
    53.What is the difference between a static and a non-static inner class?
    54.What is an object’s lock and which object’s have locks?
    55.When can an object reference be cast to an interface reference?
    56.What’s the difference between J2SDK 1.5 and J2SDK 5.0?
    57.Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
    58.Can an inner class declared inside of a method access local variables of this method?
    59.What can go wrong if you replace && with & in the following code:
    String a=null; if (a!=null && a.length()>10) {…}
    60.What’s the main difference between a Vector and an ArrayList
    61.When should the method invokeLater()be used?
    62.How can a subclass call a method or a constructor defined in a superclass?
    63.What’s the difference between a queue and a stack?
    64.You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
    65.What comes to mind when someone mentions a shallow copy in Java?
    66.What comes to mind when you hear about a young generation in Java?
    67.You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
    ArrayList or LinkedList?
    68.How would you make a copy of an entire Java object with its state?
    69.There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
    70.How can you minimize the need of garbage collection and make the memory use more effective?
    71.What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
    72.How do I deserilaize an Object?
    73.What are different types of inner classes ?
    74.Difference Between String and String Buffer?
    75.difference between verses (==) and .equals().

    Java Drill – 1

    1.What is the difference between an Interface and an Abstract class?
    2.What is the purpose of garbage collection in Java, and when is it used?
    3.Describe synchronization in respect to multithreading.
    4.Explain different way of using thread?
    5.What are pass by reference and passby value?
    6.What is HashMap and Map?
    7.Difference between HashMap and HashTable?
    8.Difference between Vector and ArrayList?
    9.Difference between Swing and Awt?
    10.What is the difference between a constructor and a method?
    11.What is an Iterator?
    12.State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
    13.What is an abstract class?
    14.What is static in java?
    15.What is final?
    16.What if the main method is declared as private?
    17.What if the static modifier is removed from the signature of the main method?
    18.What if I write static public void instead of public static void?
    19.What if I do not provide the String array as the argument to the method?
    20.What is the first argument of the String array in main method?
    21.If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
    22.How can one prove that the array is not null but empty using one line of code?
    23.What environment variables do I need to set on my machine in order to be able to run Java programs?
    24.Can an application have multiple classes having main method?
    25.Can I have multiple main methods in the same class?
    26.Do I need to import java.lang package any time? Why ?
    27.Can I import same package/class twice? Will the JVM load the package twice at runtime?
    29.What are Checked and UnChecked Exception?
    30.What is Overriding?
    31.What are different types of inner classes?
    32.Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
    33.Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
    34.What is the difference between declaring a variable and defining a variable?
    35.What is the default value of an object reference declared as an instance variable?
    36.Can a top level class be private or protected?
    37.What type of parameter passing does Java support?
    38.Primitive data types are passed by reference or pass by value?
    39.Objects are passed by value or by reference?
    40.What is serialization?
    41.How do I serialize an object to a file?
    42.Which methods of Serializable interface should I implement?
    43.How can I customize the seralization process? i.e. how can one have a control over the serialization process?
    44.What is the common usage of serialization?
    45.What is Externalizable interface?
    46.When you serialize an object, what happens to the object references included in the object?
    47.What one should take care of while serializing the object?
    48.What happens to the static fields of a class during serialization?
    49.Does Java provide any construct to find out the size of an object?
    50.Give a simplest way to find out the time a method takes for execution without using any profiling tool?
    51.What are wrapper classes?
    52.Why do we need wrapper classes?
    53.What are checked exceptions?
    54.What are runtime exceptions?
    55.What is the difference between error and an exception??
    56.How to create custom exceptions?
    57.If I want an object of my class to be thrown as an exception object, what should I do?
    58.If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
    59.How does an exception permeate through the code?
    60.What are the different ways to handle exceptions?
    61.What is the basic difference between the 2 approaches to exception handling…1> try catch block and 2> specifying the candidate exceptions in the throws clause?
    62.When should you use which approach?
    63.Is it necessary that each try block must be followed by a catch block?
    64.If I write return at the end of the try block, will the finally block still execute?
    65.If I write System.exit (0); at the end of the try block, will the finally block still execute?
    66.How are Observer and Observable used?
    67.What is synchronization and why is it important?
    68.How does Java handle integer overflows and underflows?
    69.Does garbage collection guarantee that a program will not run out of memory?
    70.What is the difference between preemptive scheduling and time slicing?
    71.When a thread is created and started, what is its initial state?
    72.What is the purpose of finalization?
    73.What is the Locale class?
    74.What is the difference between a while statement and a do statement?
    75.What is the difference between static and non-static variables?
    76.How are this() and super() used with constructors?
    77.What are synchronized methods and synchronized statements?
    78.What is daemon thread and which method is used to create the daemon thread?
    79.Can applets communicate with each other?
    80.What are the steps in the JDBC connection?
    81.How does a try statement determine which catch clause should be used to handle an exception?
    82.Can an unreachable object become reachable again?
    83.What method must be implemented by all threads?
    84.What are synchronized methods and synchronized statements?
    85.What is Externalizable?
    86.What modifiers are allowed for methods in an Interface?
    87.What are some alternatives to inheritance?
    88.What does it mean that a method or field is “static”? ?
    89.What is the difference between preemptive scheduling and time slicing?
    90.What is the catch or declare rule for method declarations?

    91.Is Empty .java file a valid source file?
    92.Can a .java file contain more than one java classes?
    93.Is String a primitive data type in Java?
    94.Is main a keyword in Java?
    95.Is next a keyword in Java?
    96.Is delete a keyword in Java?
    97.Is exit a keyword in Java?
    98.What happens if you dont initialize an instance variable of any of the primitive types in Java?
    99.What will be the initial value of an object reference which is defined as an instance variable?
    100.What are the different scopes for Java variables?
    101.What is the default value of the local variables?

    102.How many objects are created in the following piece of code?
    MyClass c1, c2, c3;
    c1 = new MyClass ();
    c3 = new MyClass ();

    104.Can a public class MyClass be defined in a source file named YourClass.java?
    105.Can main method be declared final?

    106.What will be the output of the following statement?
    System.out.println (“1” + 3);

    107.What will be the default values of all the elements of an array defined as an instance variable?

    Java Coding Drill – One

    1. Factorial finding

    public class Fact {
            public static int factorial(int n) {
                if (n==0)
                      return 1;
               else
                     return n * factorial(n-1);
            }
            public static void main(String argv[]) {
                 int x;
                 x=9;
                 System.out.println(“Factorial of “+x+” is “+factorial(x));
            }
    }

    2. Divisible by number

    public class Divisor{
              public static void main(String[] args){
                   int a = 10;
                   int b = 2;
                   if ( a % b == 0 ){
                          System.out.println(a + ” is divisible by “+ b);
                  }else{
                          System.out.println(a + ” is not divisible by ” + b);
                  }
             }
    }

    3. Compound Interest

    public class CompoundInterest {
                public static void main(String[] args) {
                   double principal;
                   double rate;
                   double interest;
                   principal = 17000;
                   rate = 0.07;
                   interest = principal * rate; 
                   principal = principal + interest;
                   System.out.print(“The interest earned is $”);
                   System.out.println(interest);
                   System.out.print(“The value of the investment after one year is $”);
                   System.out.println(principal);
              }
    }

    4. Printing Square of number

    public class PrintSquare {
            public static void main(String[] args) throws Exception {
                 int square = 0;
                 int userInput = 0;
                 userInput = Integer.parseInt(args[0]);
                 square = userInput * userInput ;
                 System.out.print(“The square of “+userInput+” is “+square);
            }
    }

    5. Sum of Numbers

         import java.util.*;
          public class SumNo{
                public static void main(String args[]){
                      Scanner console = new Scanner(System.in);
                      System.out.print(“Type a number: “);
                      int num1 = console.nextInt();
                      System.out.print(“Type a number: “);
                      int num2 = console.nextInt();
                      System.out.print(“Type a number: “);
                      int num3 = console.nextInt();
                      int sum = num1 + num2 + num3;
                      System.out.println(“The sum is ” + sum);
                 }
          }

    6. Finding even/odd numbers

    public class EvenOdd{
           public static void main(String[] args) {
                 for (int i = 1; i <= 20; i++) {
                      if (i % 2 == 0) {
                         System.out.println(i + ” is even”);
                      } else {
                         System.out.println(i + ” is odd”);
                      }
                 }
           }
    }

    7. Finding Prime Number

    public class PrimeNo {
             public static void main(String[] args) {
                 for(int i=0;i<100;i++){
                      if(countFactor(i)==2){
                        System.out.println(i);
                      }
                  }
              }
             public static int countFactor(int num){
                  int cnt = 0;
                  for(int j = 1; j <= num; j++) {
                     if (num % j == 0) {
                         cnt++;
                     }
                   }
                    return cnt;
               }
     }

    8.Counting the charectors

    public class CountChar {
          public static void main(String[] args) {
               String str = “mississippi”
               int tot = cntCh(str);
               System.out.println(“Total count :”+tot);
          }
          public static int cntCh(String str) {
              int count = 0;
              for (int i = 0; i < str.length(); i++) {
                 if (str.charAt(i) == ‘s’) {
                      count++;
                  }
             }
            return count;
          }
    }

    9. Printing Time and Date format

    import java.util.*;
         public class TimeDateFormat {
             public static void main(String args[]) {
                 Formatter fmt = new Formatter();
                 Calendar cal = Calendar.getInstance();
                 // Display standard 12-hour time format.
                 fmt.format(“%tr”, cal);
                 System.out.println(fmt); 
                 // Display complete time and date information. 
                 fmt = new Formatter();
                 fmt.format(“%tc”, cal);
                 System.out.println(fmt);
                 // Display just hour and minute.
                 fmt = new Formatter(); 
                 fmt.format(“%tl:%tM”, cal, cal);
                 System.out.println(fmt);
                 // Display month by name and number.
                 fmt = new Formatter();
                 fmt.format(“%tB %tb %tm”, cal, cal, cal);
                System.out.println(fmt);
          }
    }

    10. Find In Line

    import java.util.*;
            public class FindInLine{
                public static void main(String args[]) {
                String instr = “Name: Tom Age: 28 ID: 77”
                Scanner conin = new Scanner(instr); 
                // Find and display age.
                conin.findInLine(“Age:”); // find Age
                if(conin.hasNext())
                     System.out.println(conin.next());
                else
                      System.out.println(“Error!”);
             }
     }

    11.File Read / Write

    import java.util.*;
    import java.io.*;
    public class ScanMixed {
    public static void main(String args[])
    throws IOException {
    int i;
    double d;
    boolean b;
    String str;
    // Write output to a file.
    FileWriter fout = new FileWriter(“test.txt”);
    fout.write(“Testing Scanner 10 12.2 one true two false”);
    fout.close();
    FileReader fin = new FileReader(“Test.txt”);
    Scanner src = new Scanner(fin);
    while(src.hasNext()) {
    if(src.hasNextInt()) {
    i = src.nextInt();
    System.out.println(“int: ” + i);
    }
    else if(src.hasNextDouble()) {
    d = src.nextDouble();
    System.out.println(“double: ” + d);
    }
    else if(src.hasNextBoolean()) {
    b = src.nextBoolean();
    System.out.println(“boolean: ” + b);
    }
    else {
    str = src.next();
    System.out.println(“String: ” + str);
    }
    }
    fin.close();
    }
    }

    Database Drill

    1.What is DDL and DML ?

    DDL :-  Data defination Language

    its having four commands

     Create , Alter , Drop , Truncate

    DML :- Data manuplation language

     Insert , Update , Delete , select

    2.How can you compare a part of the name rather than the entire name ?

    SELECT * FROM people WHERE empname LIKE ‘%ab%’
    Would return a recordset with records consisting empname the sequence ‘ab‘ in empname .

    3.How could I get distinct entries from a table ?

    The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a database. The values selected from the database table would of course depend on the various conditions that are specified in the SQL query. 

       SELECT DISTINCT empname FROM emptable

    4.How to get the results of a Query sorted in any order ?

    You can sort the results and return the sorted results to your program by using ORDER BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting.

       SELECT empname, age, city FROM emptable ORDER BY empname

    5.How can I find the total number of records in a table ?

       You could use the COUNT keyword , example
           SELECT COUNT(*) FROM emp WHERE age>40

    6.What is GROUP BY ?

    The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible

    7.What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table ?

    Dropping :  (Table structure  + Data are deleted), Invalidates the dependent objects ,Drops the indexes

    Truncating:  (Data alone deleted), Performs an automatic commit, Faster than delete

    Delete : (Data alone deleted), Doesn’t perform automatic commit

    8.What are the Large object types suported by Oracle ?

    Blob and Clob

    9.Difference between a “where” clause and a “having” clause ?

    Having clause is used only with group functions whereas Where is not used with.

    10.What’s the difference between a primary key and a unique key ?

    Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

    11.What are triggers? How to invoke a trigger on demand ?

    Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.

    Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.

    Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

    12. What is a join and explain different types of joins ?

    Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

    Types of  Joins

    INNER JOINS: It will pull all the rows from both tables where there is a match.

    SELECT postid, posts.title, commentid, comments.title FROM posts INNER JOIN comments ON posts.postid = comments.postid

    LEFT OUTER JOIN: It will pull all the rows from left side of a join regardless of whether there is a match on the right side of join. Anything missing on the right side will be replaced by NULL.

    SELECT postid, posts.title, commentid, comments.title FROM posts LEFT OUTER JOIN comments ON posts.postid = comments.postid

    RIGHT OUTER JOIN: It will pull all the rows from the right side of a join regardless of whether there is a match on the left side of join. Anything missing on the left side will be replaced by NULL.

    SELECT postid, posts.title, commentid, comments.title FROM posts
    RIGHT OUTER JOIN comments ON posts.postid = comments.postid

    CROSS JOIN: It returns a row of each combination of rows between the two tables. If you had 5 rows in each table, you’ed end up with 25 rows in the result set.

    SELECT Products.ProductName, Products.UnitPrice, Temporary.Amount FROM Products CROSS JOIN Temporary ORDER BY Products.ProductName, Temporary.Amount

    13.What is a Self Join ?

    Self join is just like any other join, except that two instances of the same table will be joined in the query.

    SELECT DISTINCT c1.ContactName, c1.Address, c1.City, c1.Region
    FROM Customers AS c1, Customers AS c2
    WHERE c1.Region = c2.Region
    AND c1.ContactName <> c2.ContactName
    ORDER BY c1.Region, c1.ContactName;

    14.What is Cursor  ?

    It is private SQL area to execute the sql quries and store the information. There are two types of cursors implicit cursors and explicit cursors.

    Implicit cursors are system defined and returns one row. Explicit cursors are user defined and returns multiple rows

    15.How do you get Column names only for a table (SQL Server)  ?

    select name from syscolumns
    where id=(select id from sysobjects where name=’user_hdr’)
    order by colid –user_hdr is the table name

    16.How to find stored procedures  ?

    select procedure_name from all_procedures

    17.What are Extended stored procedures  ?

    Extended stored procedures let you create your own external routines in a programming language such as C. Extended stored procedures are DLLs that an instance of Microsoft SQL Server can dynamically load and run. Extended stored procedures run directly in the address space of an instance of SQL Server and are programmed by using the SQL Server Extended Stored Procedure API.

    18. Explain about Cursors ?

    Cursors are database objects used to traverse the results of an SQL query. They point to a certain location within a recordset and allow the operator to move forward (and sometimes backward, depending upon the cursor type) through the results one record at a time. There are different types of  cursors: Static, Dynamic, Forward-only, Keyset-driven.

    Cursors extend result processing by:

    • Allowing positioning at specific rows of the result set.
    • Retrieving one row or block of rows from the current position in the result set.
    • Supporting data modifications to the rows at the current position in the result set.
    • Supporting different levels of visibility to changes made by other users to the database data that is presented in the result set.
    • Providing Transact-SQL statements in scripts, stored procedures, and triggers access to the data in a result set.

    Disadvantages of cursors:

    Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

    Example:

    CREATE OR REPLACE Function FindCourse
    ( name_in IN varchar2 )
    RETURN number
    IS
    cnumber number;

    CURSOR c1
    IS
    SELECT course_number
    from courses_tbl
    where course_name = name_in;

    BEGIN

    open c1;
    fetch c1 into cnumber;

    if c1%notfound then
    cnumber := 9999;
    end if;

    close c1;

    RETURN cnumber;

    END;

    19.Explain about Stored Procedures ?

    A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server.For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.

    No Param
    CREATE OR REPLACE PROCEDURE myproc IS
    BEGIN
    INSERT INTO oracle_table VALUES(‘string 1’);
    END;
    IN Param
    CREATE OR REPLACE PROCEDURE myprocin(x VARCHAR) IS
    BEGIN
    INSERT INTO oracle_table VALUES(x);
    END;
    OUT Param
    CREATE OR REPLACE PROCEDURE myprocout(x OUT VARCHAR) IS
    BEGIN
    INSERT INTO oracle_table VALUES(‘string 2’);
    x := ‘outvalue’; // Assign a value to x
    END;
    IN/OUT Param
    CREATE OR REPLACE PROCEDURE myprocinout(x IN OUT VARCHAR) IS
    BEGIN
    INSERT INTO oracle_table VALUES(x); // Use x as IN parameter
    x := ‘outvalue’; // Use x as OUT parameter
    END;

    20.Explain about Views ?

    View is a virtual or logical table composed of the result set of a query. Unlike orginary tables in a relational database, a view is not part of the physical schema. It is a dynamic virtual table computed or collated from data in the database. Chainging the data in a table alters the data shown in the view.

    Views can provide advantages over tables

    • They can subset the data contained in a table
    • They can join and simplify multiple tables into a single virtual table
    • Views can act as aggregated tables, where aggregated data (sum,average etc.) are calculated and presented as part of the data
    • Views can hide the complexity of data,
    • Views do not incur any extra storage overhead
    • Depending on the SQL engine used, views can provide extra security.
    • Limit the exposure to which a table or tables are exposed to outer world
    • Rows in a view are not sorted. So we cannot use ORDER BY clause in the view definition.

              CREATE VIEW V_Customer
              AS SELECT First_Name, Last_Name, Country
             FROM Customer

     

    21.Stored Function Vs Stored Procedure

    Function :

    1. Should return atleast one output parameter.Can return more than one parameter using OUT argument.

    2. Parsed and compiled at runtime.

    3.Cannot affect the state of database.

    4.Can be invoked from SQL statement e.g. SELECT.

    5. Functions are mainly used to compute values.

    Procedure:

    1. Doesn’t need to return values, but can return value.

    2.Stored as a pseudo-code in database i.e. compiled form.

    3.Can affect the state of database using commit etc.

    4.Cannnot be invoked from SQL statements e.g. SELECT.

    5.Procedures are mainly used to process the tasks.

    Java based DB Questions

    1.How do you call a Stored Procedure from JDBC ? 

    The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.

    	CallableStatement cs =
    		con.prepareCall("{call SHOW_SUPPLIERS}");
    	ResultSet rs = cs.executeQuery();
    

    2.What is cold backup, hot backup ? 

    Cold backup means all these files must be backed up at the same time, before the databaseis restarted. Hot backup or online backup is a backup taken of each tablespace while the database is running and is being accessed by the users.

    3.What is a “dirty read” ? 

    Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

    4.What is Metadata and why should I use it  

    Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns

    5.Different types of Transaction Isolation Levels

    The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur:

    • Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.
    • Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data.
    • Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.

    1.TRANSACTION_READ_UNCOMMITTED : Dirty-read, Non-repeatable read and Phantoms can occur

    2.TRANSACTION_READ_COMMITTED : Dirty-reads are prevented. Non-repeatable read and Phantoms can occur.

    3.TRANSACTION_REPEATABLE_READ : Dirty-reads and Non-repeatable read are prevented and Phantoms can occur.

    4.TRANSACTION_SERIALIZABLE : Dirty-reads,Non-repeatable read and Phantoms are prevented.

    6.How do you handle your own transaction ?

    Connection Object has a method called setAutocommit(Boolean istrue)
    Default is true. Set the Parameter to false , and begin your transaction