Net multithreading interview questions – Threading Interview Questions in .NET

Net multithreading interview questions: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Threading

Question 1.
What is multi-tasking?
Answer:
It is a feature of modern operating systems with which we can run multiple programs at same time, for example Word, Excel, etc.

Question 2.
What is multi-threading?
Answer:
Multi-threading forms a subset of multi-tasking. Instead of having to switch between programs, this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

Question 3.
What is a thread?
Answer:
A thread is a basic unit to which the operating system allocates processor time.

Question 4.
Did VB6 support multi-threading?
Answer:
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.

Question 5.
Can we have multiple threads in one App domain?
Answer:
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread but can create additional threads from any of its threads.

Note: All threading classes are defined in System. Threading namespace.

Question 6.
Which namespace has threading?
Answer:
‘ Systems. Threading’ has all the classes related to implement threading. Any .NET application which can implement threading has to import this namespace.

Note:NETprogram always has at least two threads running one is the main program and second is the garbage collector.

Question 7.
Can you explain in brief how can we implement threading?
Answer:

Private Sub Forml_Load (ByVal sender As System. Object, ByVal e as
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread (AddressOf Thread1)
Dim pthread2 As New Thread (AddressOf Thread2) 
pthread1.Start ( ) 
pthread2.Start ()
End Sub
Public Sub Threadl ( )
Dim pint count As Integer
Dim pstr As String
Pstr = "This is first thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1
Loop 
End Sub
Public Sub Thread2 ()
Dim pint count As Integer
Dim pstr As String
Pstr = "This is second thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1 
Loop 
End Sub
Note: If you run the sample, you will see that sometimes the first thread runs first and then the second thread. 
This happens because of thread priorities. The first thread is run with highest priority.

Question 8.
How can we change the priority and what levels of priority are provided by .NET?
Answer:
Thread Priority can be changed by using

Thread name.Priority = ThreadPriority.Highest

Following are different levels of Priority provided by .NET:

  • ThreadPriority.Highest
  • ThreadPriority.above normal
  • ThreadPriority.Normal
  • ThreadPriority.below normal
  • ThreadPriority.Lowest

Question 9.
What does the AddressOf operator do in the background?
Answer:
The AddressOf operator creates a delegate object to the Background Process method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the start () method of the thread.

Question 10.
How can you reference the current thread of the method?
Answer:
“Thread. CurrentThread” refers to the current thread running in the method. “CurrentThread” is public static property.

Question 11.
What is Thread.Sleep ( ) in threading?
Answer:
Thread’s execution can be paused by calling the Thread. sleep method. This method takes an integer value that determines how long the thread should sleep. For example, Thread.CurrentThread. Sleep(2000).

Question 12.
How can we make a thread sleep for the infinite period?
Answer:
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread. Sleep (System.Threading.Timeout. Infinite). To interrupt this sleep you can call the Thread. Interrupt method.

Question 13.
What is Suspend and Resume in Threading?
Answer:
It is similar to Sleep and Interrupt Suspend allows you to block a thread until another Thread calls Thread. Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

Note: In threading interviews, most people get confused with Sleep and Suspend. They look very similar.

Question 14.
What is the way to stop a long-running thread?
Answer:
Thread. Abort ( ) stops the thread execution at that moment itself.

Question 15.
How do I debug the thread?
Answer:
This window is only seen when the program is running in debug mode. In windows, one of the Windows is “Threads” (See Figure 17.1).

Threading Interview Questions in .NET chpter 17 img 1

Question 16.
What is Thread. Join ( ) in threading?
Answer:
There are two versions of Thread join-

  • Thread, join ( ).
  • Thread. join (Integer) returns a Boolean value.

The Thread. join method is useful for determining if a thread has been completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise, it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done.

For example, you have “Thread1” and “Thread2” and while executing ‘Thread1″ you call “Thread2 .Join ( ) “.So “Thread1” will wait until “Thread2” has completed its execution and again invoke “Thread1”.

Thread. Join (Integer) ensures that threads do not wait for a long time. If it exceeds a specific time, which is provided in integer the waiting thread will start.

Question 17.
What are Daemon threads and how can a thread be created as Daemon?
Answer:
Daemon thread’s run in the background and stops automatically the program is not running. An example of a Daemon thread is ‘Garbage collector’. The garbage collector runs until some .NET code is running or else it is idle.
You can make a thread Daemon by

Thread, Isbackground-true

Question 18.
How is shared data managed in threading?
Answer:
There are certain situations that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you’ll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time, you will have a deadlock problem. To avoid dead lock we need to use the ‘ SyncLock’ keyword as shown in the code snippet below.

SyncLock x
         'Do something with x 
End SyncLock

Question 19.
Can we use events with threading?
Answer:
Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.

Question 20.
How can we know a state of a thread?
Answer:
“Threadstate” property can be used to get the detail of a thread. Thread can have one or a combination of status. ‘System.Threading.Threadstate’ enumeration has all the values to detect a state of the thread. Some sample states are running, isAlive, suspended, etc.

Question 21.
What is the use of interlocked class?
Answer:
The interlocked class provides methods by which you can achieve the following functionalities:

  • Increment Values
  • Decrement values
  • Exchange values between variables
  • Compare values from any thread. in a synchronization mode Example: System.Threading.Interlocked.Increment(IntA)

Question 22.
What is a monitor object?
Answer:
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor objects.

Question 23.
What are wait handles?
Answer:
Wait handles send signals of a thread status from one thread to another thread. There is three kinds of wait modes:

  • WaitOne
  • WaitAny
  • WaitAII

When a thread wants to release a Wait handle it can call the set method. You can use Mutex (mutually exclusive) objects to avail for the following modes. Mutex objects are synchronization objects that can only be owned by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource.

The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to be signaled and the next waiting thread gets ownership

Question 24.
What is ManualResetEvent and AutoResetEvent?
Answer:
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signal using Set, but they automatically return to non signaled as soon as a waiting thread is notified that the event became signaled.

Question 25.
What is Reader-Writer Locks?
Answer:
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows non-exclusive access when reading the resource. Reader-Writer locks are a good alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.

Question 26.
How can you avoid deadlock in threading?
Answer:
Good and careful planning can avoid deadlocks. There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to another thread, and using ThreadState property you can poll and act accordingly.

Question 27.
What is TPL (Task Parallel Library)?
Answer:
TPL stands for Task Parallel Library. It’s introduced in .NET 4.0 framework to simplify threading.TPL is a set of APIs (Application Programming Interface) that sits on top of core threading and simplifies threading. When we use threading API directly you need to take care of pooling, ensure that the thread executes on multiple processors, data and task parallelism, etc. When you use TPL all these things are taken care of so that you concentrate on the work rather than these lower-level technical details.
TPL simplifies the following things from development aspect:

  • Thread pooling is taken care of internally.
  • TPL ensures that threads will execute on multiple processors.
  • Cancellation of threads made easier.
  • State management is simplified as compared to core threading.

All components of TPL (task parallel library) exist in the below namespace.

using System. Threading. Tasks;

To invoke a thread using TPL we need to use the below syntax. We need to create the object of task object to invoke a thread.

Task tsk = new Task(MyTask); // Run the task. 
tsk.Start( );

Question 28.
What is the difference between thread and process?
Answer:
A thread is a path of execution that runs on a CPU (Central Processing Unit), a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always runs in a process context.

Note: Its difficult to cover threading interview question in this small chapter. These questions can take only 
to a basic level. If you are attending interviews where people are looking for threading specialist, try to get 
deeper in to synchronization issues, as that is the important point they will stress.

Journaldev core java interview questions – Exception Handling Interview Questions in Java

Journaldev core java interview questions: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Exception Handling Interview Questions in Java

Question 1.
What is an Exception in Java?
Answer:
An exception is an error event that can happen during the execution of a program and disrupts its normal flow. An exception can arise from different kinds of situations such as wrong data entered by the user, hardware failure, network connection failure, etc.

Whenever any error occurs while executing a java statement, an exception object is created, and then JREtries to find an exception handler to handle the exception. If a suitable exception handler is found then the exception object is passed to the handler code to process the exception, known as catching the exception. If no handler is found then the application throws the exception to the runtime environment and JRE terminates the program.

Java Exception handling framework is used to handle runtime errors only, compile-time errors are not handled by exception handling framework.

Question 2.
What are the different kinds of exceptions? How do you catch a Runtime exception?
Answer:
There are 2 types of exceptions.

  1. Checked exception
  2. Unchecked exception.

The checked exception is cached at the compile-time while the unchecked exception is checked at run time.
1. Checked Exceptions: Environmental error that cannot necessarily be detected by testing; e.g. disk full, broken socket, database unavailable, etc.
2. Unchecked exception. Errors: Virtual machine error: class not found, out of memory, no such method, illegal access to a private field, etc.
Runtime Exceptions: Programming errors that should be detected in testing: index out of bounds, null pointer, illegal argument, etc. Checked exceptions must be handled at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Question 3.
What is the Exception Handling Keywords in Java?
Answer:
There are four keywords used in java exception handling.

• throw: Sometimes we explicitly want to create an exception object and then throw it to halt the normal processing of the program, throw keyword is used to throw exceptions to the runtime to handle it.

• throws: When we are throwing any checked exception in a method and not handling it, then we need to use the throws keyword in the method signature to let the caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate them to its caller method using the throws keyword. We can provide multiple exceptions in the throws clause and it can be used with the main( ) method also.

• try-catch: We use try-catch block for exception handling in our code, try is the start of the block and catch is at the end of the try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also, the catch block requires a parameter that should be of type Exception.

• finally: finally block is optional and can be used only with a try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block, finally block gets executed always, whether an exception occurs or not.

Question 4.
Explain Java Exception Hierarchy?
Answer:
Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exceptions.

Errors are exceptional scenarios that are out of the scope of application and it’s not possible to anticipate and recover from them, for example, hardware failure, JVM crash, or out of memory error.

Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example, FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for debugging purposes. The exception is the parent class of all Checked Exceptions.

Runtime Exceptions are caused by bad programming, for example, trying to retrieve an element from the Array. We should check the length of the array first before trying to retrieve the element otherwise it might throw ArraylndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.

Question 5.
What are the important methods of the Java Exception Class?
Answer:
Exception and all of its subclasses don’t provide any specific methods and all of the methods are defined in the base class Throwable.
• String get messages( ) – This method returns the message String of Throwable and the message can be provided while creating the exception through its constructor.

• String getLocalizedMessage( ) – This method is provided so that subclasses can override it to provide a locale-specific message to the calling program. Throwable class implementation of this method simply uses the get messages( ) method to return the exception message.

• synchronized Throwable getCause( ) — This method returns the cause of the exception or null if the cause is unknown.

• String to string( ) – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

• void printStackTrace( ) – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as arguments to write the stack trace information to the file or stream.

Question 6.
What is the difference between exception and error?
Answer:
The exception class defines mild error conditions that your program encounters.
Ex: ArithmeticException, FileNotFound exception
Exceptions can occur when trying to open the file, which does not exist

  • the network connection is disrupted
  • operands being manipulated are out of prescribed ranges
  • the class file you are interested in loading is missing

The error class defines serious error conditions that you should not attempt to recover from. In most cases, it is advisable to let the program terminate when such an error is encountered.
Ex: Running out of memory error, Stack overflow error.

Question 7.
Explain Java 7 ARM Feature and multi-catch block?
Answer:
If you are catching a lot of exceptions in a single try block, you will notice that catch block code looks very ugly and mostly consists of redundant code to log the error, keeping this in mind Java 7 one of the features was the multi-catch block where we can catch multiple exceptions in a single catch block. The catch block with this feature looks like below:

catch(IoException | SQLException | Exception ex){ 
logger.error(ex);
        throw new MyException(ex.getMessage( ));
}

Most of the time, we use finally block just to close the resources and sometimes we forget to close them and get runtime exceptions when the resources are exhausted. These exceptions are hard to debug and we might need to look into each place where we are using that type of resource to make sure we are closing it. So java 7 one of the improvements was try-with-resources where we can create a resource in the try statement itself and use it inside the try-catch block. When the execution comes out of the try-catch block, the runtime environment automatically closes these resources. Sample of the try-catch block with this improvement is:

try (MyResource Mr = new MyResource( )) {
System.out.println(“MyResource created in try-with-resources”); 
} catch (Exception e) { 
e.printstackTrace( );
}

Question 8.
What is the difference between Checked and Unchecked Exception in Java?
Answer:
• Checked Exceptions should be handled in the code using try-catch block or else the main( ) method should use throws keyword to let JRE know about this exception that might be thrown from the program. Unchecked Exceptions are not required to be handled in the program or to mention them in a throws clause.

• Exception is the superclass of all checked exceptions whereas RuntimeException is the superclass of all unchecked exceptions.

• Checked exceptions are error scenarios that are not caused by the program, for example, FileNotFoundException in reading a file that is not present, whereas Unchecked exceptions are mostly caused by poor programming, for example, NullPointerException when invoking a method on an object reference without making sure that it’s not null.

Question 9.
What is the difference between the throw and throws keyword in Java?
Answer:
throws keyword is used with method signature to declare the exceptions that the method might throw whereas throw keyword is used to disrupt the flow of the program and handing over the exception object to runtime to handle it.

Question 10.
How to write custom exceptions in Java?
Answer:
We can extend the Exception class or any of its subclasses to create our custom exception class. The custom exception class can have its own variables and methods that we can use to pass error codes or other exception-related information to the exception handler.
A simple example of custom exception is shown below.

MyException.java

package com.journaldev.exceptions;
import java.io.IOException;
public class MyException extends IoException {
private static final long serialversionUID = 4664456874499611218L;
private String errorcode=”unknown_Exception”;
public MyException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public string getErrorcode( ){
return this.errorCode;
}
}

Question 11.
What is OutOfMemoryError in Java?
Answer:
OutOfMemoryError in Java is a subclass of java. lang.VirtualMachineError and its thrown by JVM when it ran out of heap memory, and no more memory could be made available by the garbage collector. We can fix this error by providing more memory to run the java application through java options.

$>java MyProgram -xmsl024m -Xmxl024m -xx:Permsize=64M 
-xx:Max Pe rmSize=2 56m
Question 12.
What are different scenarios causing “Exception in thread main”?
Answer:
Some of the common main thread exception scenarios are:
• Exception in thread main java. lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.
• Exception in thread main java. lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with the .class extension. The second scenario is when a Class is not found.
• Exception in thread main java. lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesn’t have a main method.
• Exception in thread “main” java. lang.ArithmeticException: Whenever an exception is thrown from the main method, it prints the exception in the console. The first part explains that exception is thrown from the main method, the second part prints the exception class name and then after a colon, it prints the exception message.
Question 13.
What happens when an exception is thrown by the main method?
Answer:
When an exception is thrown by the main( ) method, Java Runtime terminates the program and prints the exception message and stack trace in the system console.
Question 14.
Can an exception be rethrown?
Answer:
Yes, an exception can be rethrown.
Question 15.
When is the final clause of a try-catch-finally statement executed?
Answer:
The final clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the final clause.
Question 16.
What class of exceptions are generated by the Java run-time system?
Answer:
The Java runtime system generates RuntimeException and Error exceptions.
Question 17.
What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
Answer:
A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
Question 18.
What classes of exceptions may be thrown by a throw statement?
Answer:
A throw statement may throw any expression that may be assigned to the Throwable type.
Question 19.
What happens if an exception is not caught?
Answer:
An uncaught exception results in the uncaught exception( ) method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.
Question 20.
What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
Answer:
The exception propagates up to the next higher level try-catch statement (if any) or results in the program’s termination.
Question 21.
Can try statements be nested?
Answer:
Try statements may be tested.
Question 22.
How does a try statement determine which catch clause should be used to handle an exception?
Answer:
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.
Question 23.
What is the purpose of the final clause of a try-catch-finally statement?
Answer:
The final clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
Question 24.
Is it necessary that each try block must be followed by a catch block?
Answer:
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a final block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method
Question 25.
What classes of exceptions may be caught by a catch clause?
Answer:
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions.
Question 26.
Can we have an empty catch block?
Answer:
We can have an empty catch block but it’s an example of worst programming. We should never have an empty catch block because if the exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least a logging statement to log the exception details in the console or log files.
Provide some Java Exception Handling Best Practices?
Some of the best practices related to Java Exception Handling are:
  • Use Specific Exceptions for ease of debugging.
  • Throw Exceptions Early (Fail-Fast) in the program.
  • Catch Exceptions late in the program, let the caller handle the exception.
  • Use Java 7 ARM feature to make sure resources are closed or use a final block to close them properly.
  • Always log exception messages for debugging purposes.
  • Use a multi-catch block for cleaner close.
  • Use custom exceptions to throw a single type of exception from your application API.
  • Follow naming convention, always end with Exception.
  • Document the Exceptions Thrown by a method using @throws in java does.
  • Exceptions are costly, so throw it only when it makes sense. Else you can catch them and provide a null or empty response.
Question 27.
What is the use of the final block?
Answer:
Finally is the block of code that is always executed even when an exception has occurred.
Question 28.
Does the code in the final block get executed if there is an exception and a return statement in a catch block?
Answer:
If an exception occurs and there is a return statement in the catch block, the final block is still executed. The final block will not be executed when the System. exit(l) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
Question 29.
Does the code in the final block get executed if there is an exception and a return statement in a catch block?
Or
What is the purpose of the final clause of a try-catch-finally statement?
Answer:
 The final clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in the catch block, the final block is still executed. The final block will not be executed when the System. exit(O) statement is executed earlier or on the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
try{
//some statements
}
catch{
//statements when exception is caught } 
finally{
//statements executed whether exception occurs or not
}

Question 30.
Does the order of placing catch statements matter in the catch block?
Answer:
Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception

Question 31.
Explain the user-defined Exceptions?
Answer:
User-defined Exceptions are custom Exception classes defined by the user for a specific purpose. A user-defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.
Example:
class CustomException extends Exception {
}
Question 32.
When is finally block NOT called?
Answer:
  • Finally block is NOT called in the following cases: If the JVM exits while the try or catch code is being executed. This may happen due to System. exit( ) call.
  • If the thread executing the try or catch code gets interrupted or killed. In this case, the final block may not execute although the application keeps working.
  • If an exception is thrown in finally block is not handled. In this case, the remaining code in the final block may not execute.
Question 33.
What is the difference between final, finally, and finalize( )?
Answer:
final:
  • It is a modifier that can be applied to a class, method, or variable.
  • It is not possible to inherit the final class, override the final method and change the final variable.
finally:
  • It is an exception handling code section.
  • It gets executed whether an exception is raised or not by the try block code segment.
finalize( )
  • It is a method of Object class.
  • It is executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.
Out of the three, only finally is related to java exception handling.
Question 34.
What is the difference between throws and throws?
Answer:
Throw keyword Throws keywords
1. throw is used to explicitly throw an exception. Throws is used to declare an exception.
2. checked exceptions cannot be propagated with throw only. Checked exception can be propagated with throws.
3. throw is followed by an instance. Throws is followed by class.
4. throw is used within the method. Throws Is used with the method signature.
5. you cannot throw multiple exceptions You can declare multiple exception e.g. public void method( ) throws IOException , SQL Exception

Question 35.
What things should be kept in mind while creating your own exceptions in Java?
Answer:
While creating your own exception:

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • You want to write a runtime exception, you need to extend the RuntimeException class.

Question 36.
What is NullPointerException?
Answer:
A NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object, etc.

Question 37.
Does it matter in what order catch statements for FileNotFoundException and IoException are written?
Answer:
Yes, it does. The FileNoFoundException is inherited from the IoException. Exception’s subclasses have to be caught first.

Question 38.
When is the ArrayStpreException thrown?
Answer:
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

Question 39.
When ArithmeticException is thrown?
Answer:
The ArithmeticException is thrown when an integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

Question 40.
What will happen if the static modifier is removed from the signature of the main method?
Answer:
The program throws a “NoSuchMethodError” error at runtime.

Question 41.
If System. exit (0); is written at the end of the try block, will the finally block still execute?
Answer:
No in this case the final block will not execute because when you say System. exit (0); the control immediately goes out of the program, and thus finally never executes.

Question 42.
When is the ArrayStoreException thrown?
Answer:
When copying elements between different arrays, if the source or destination arguments are not arrays or their types are not compatible, an ArrayStoreException will be thrown.

Question 43.
What is the problem with following code?
if (x == null && x.getMethodO == true)
Answer:
It will throw NPE in case x is null.

Question 44.
What is an Assertion and why using assertion in your program is a good idea?
Answer:
In a Java program, several times, one would like to make certain assumptions for executing a program. For example, while taking a square root of a numeric value it has to be assumed that this value should not be negative. An assertion is a statement in the Java programming language that enables to test assumptions about one’s program. Assertions are supported from J2SE1.4 and later. A simple example of assertion can be checking off an employee object from being null: Employee employee = null;

Question 45.
Explain Assertions with a code example.
Answer:
The main reason for introducing assertions in Java from R1.4 onwards is to reduce the chances of bugs that otherwise would have gone unnoticed, in one’s code. In fact, finding and removing bugs is one tedious and not-so-exciting task. Assertions should be used for scenarios that ideally should never happen in the lifecycle of a program, check assumptions about data structures (such as ensuring that an array is. of the correct length), or enforcing constraints on arguments of private methods. Assertions help in a way to block these bugs at the beginning of writing actual logic inside your code that saves a lot of effort, time, and most significantly, costs. A simple assertion facility provides a limited form of design-by-contract programming.

In design-by-contract programming identification of preconditions and postconditions to a program are a must before even starting the coding itself. Here is simple Java code which uses assertions; here the task is to determine the gender of a person. We have used a switch-case statement to define the overall flow of the logic.

Question 46.
How many forms of assertions do we have?
Answer:
There are two forms of assertions:
The first, simpler form is:
assert Expression 1;
where Expression 1 is a boolean expression.
When the system runs the assertion, it evaluates Expression 1 and if it is false throws an AssertionError with no detailed message.
While the second form of the assertion statement is:
assert Expression1: Expression2;
where: Expression1 is a boolean expression.
Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void.)
This form is used when the assert statement has to provide a detailed message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, and this constructor uses the string representation of the value as the error’s detail message. This detailed message helps in analyzing and diagnosing the assertion failure which ultimately helps in resolving the error.

Question 47.
When assertions should be avoided?
Answer:
In the following situations the assertions should be avoided:

  • When assertion becomes a performance issue. It means an assertion should not include too complex logic equaling the implementation of a method.
  • Do not use assertions in argument checking of public methods. As argument checking is part of a method implementation and if these arguments are erroneous then it will throw runtime exception and. assertion failure will not result in any error.

Question 48.
What situations are best suitable for implementing assertions?
Answer:
Assertions can best be implemented:

  • As Internal Invariants
  • As Control flow Invariants
  • As Preconditions and Postconditions
  • As Class Invariants.

Question 49.
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?
Answer:
One cannot do anything in this scenario. Because Java does not allow multiple inheritances and does not provide any exception interface as well.

Question 50.
How does an exception permeate through the code?
Answer:
An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code that is wrapped in a try block followed by one or more catch blocks, a search is made for a matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. The same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

Question 51.
What are the different ways to handle exceptions?
Answer:
There are two ways to handle exceptions,

  1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. And
  2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

Question 52.
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?

When should you use which approach?
Answer: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in the best position to decide what should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with its own exceptions, then do not use this approach. In this case, use the second approach. In the second approach, we are forcing the caller of the method to catch the exceptions that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

Question 53.
Is it necessary that each try block must be followed by a catch block?
Answer:
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a final block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Question 54.
If I write return at the end of the try block, will the finally block still execute?
Answer:
Yes even if you write return as the last statement in the try block and no exception occurs, the final block will execute. The final block will execute and then the control return.

 

HTML5 css3 interview questions – HTML 5 and CSS 3 Interview Questions in .NET | Top HTML 5 and CSS 3 Interview Questions and Answers

HTML5 and CSS3 Interview Questions in .NET

HTML5 css3 interview questions: HTML is an important language and learning it will definitely land you with plenty of opportunities. The latest version of HTML is HTML5. We have compiled the most frequently asked HTML5 and CSS3 .NET Interview Questions which will help you with different expertise levels. Use them as a quick reference to test your knowledge of the concepts of HTML5 and CSS3 and improves on the areas of need.

.NET Interview Questions on HTML 5 and CSS 3

Question 1.
What is the relationship between SGML, HTML, XML and HTML?
Answer:
SGML (Standard Generalized Markup Language) is a standard which tells how to specify document markup. It is only a Metalanguage that describes how a document markup should be. HTML is a markup language that is described using SGML.

So by SGML, they created DTD (Document Type Definition) which the HTML refers to and needs to adhere to the same. So you will always find the “DOCTYPE” attribute at the top of the HTML page which defines which DTD is used for parsing purposes.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http: //www. w3. org/TR/html4/strict. dtd”>

Now parsing SGML was a pain so they created XML to make things better. XML uses SGML. For example, in SGML you have to start and end tags but in XML you can have closing tags that close automatically (“</customer>”).

XHTML (extensible HyperText Markup Language) was created from XML which was used in HTML 4.0. So for example in SGML derived HTML “</br>” is not valid but in XHTML it’s valid. You can refer XML DTD as shown in the below code snippet.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http: //www. w3. org/TR/xhtml 1/D TD/xhtml1 -transitional. dtd">

In short SGML is the parent of every one as shown in Figure 9.1. Older HTML utilizes SGML and HTML 4.0 uses XHTML which derived from XML.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 1

Question 2.
What is HTML 5?
Answer:
HTML 5 is a new standard for HTML whose main target is to deliver everything without the need for any additional plugins like Flash, Silverlight, etc. It has everything from animations, videos, rich GUI, etc.

HTML5 is a cooperation output between World Wide Web Consortium (W3C) and the Web HyperText Application Technology Working Group (WHATWG).

Question 3.
In HTML 5 we do not need DTD why?
Answer:
HTML 5 does not use SGML or XHTML it is completely a new thing so you do not need to refer to DTD. For HTML 5 you just need to put the below DOCTYPE code which makes the browser identify that this is an HTML 5 document.

<!DOCTYPE html>

Question 4.
If I do not put <! DOCTYPE html> will HTML 5 work?
Answer:
No, the browser will not be able to identify that it’s an HTML document and HTML 5 tags will not function properly.

Question 5.
Which browsers support HTML 5?
Answer:
Almost all browsers, i.e., Safari, Chrome, Firefox, Opera, Internet Explorer, support HTML 5.

Question 6.
How is the page structure of HTML 5 different from HTML 4 or previous HTML?
Answer:
A typical Web page has headers, footers, navigation, central area, and sidebars (as shown in Figure 9.2). Now if we want to represent the same in HTML 4 with proper names to the HTML section we would probably use a div tag.

But in HTML 5 they have made it more clear by creating element names for those sections which makes your HTML more readable.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 2

Below are more details of the HTML 5 elements which form the page structure.

  • <header>: Represents header data of HTML.
  • <footer>: Footer section of the page.
  • <nav>: Navigation elements in the page.
  • <article>: Self-contained content.
  • <section>: Used inside article to define sections or group content in to sections.
  • <aside>: Represent side bar contents of a page.

HTML5 and CSS3 Interview Questions

Question 7.
What is datalist in HTML 5?
Answer:
Datalist element in HTML 5 helps to provide auto-complete feature in a textbox as shown in Figure 9.3.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 3

Below is the HTML code for datalist feature.
<input list=”Country”>
<datalist id=”Country”>
<option value=”India”>
<option value=”Italy”>
<option value=”Iran”>
<option value=”Israel”>
<option value=”Indonesia”>
</datalist>

Question 8.
What are the different new form element types in HTML 5?
Answer:
There are ten important new form elements introduced in HTML 5:

  1. Color
  2. Date
  3. Datetime-local
  4. Email
  5. Time
  6. URL
  7. Range
  8. Telephone
  9. Number
  10. Search

Let’s understand these elements step-by-step.

If you want to show a color picker dialog box (See Figure 9.4).

<input type=”color” name=favcolor”>

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 4

If you want to show calendar dialog box (see Figure 9.5)

<input type="date" name="bday">

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 5

If you want to show a calendar with local time (See Figure 9.6).

<input type=”DateTime-local” name=”daytime”>

If you want to create an HTML text with e-mail validation we can set the type as “email”.

<input type=’’email” name=”email”>

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 6

For URL validation set the type as “url” as shown in the Figure 9.8 in which HTML code is given.

<input type=”url” name=”sitename’>

For URL validation set the type as “url” as shown in the below HTML code.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 7

If you want to display textbox with number range you can set type to number (See Figure 9.9).

<input type=”number” name=”quantity” min=”1" max=”5">

If you want to display a range control you can use type as range as shown in code given below (see Figure 9.10)

<input type="range" min="0" max="10" step="2" value="6">

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 8

Want to make textbox as search engine box.

<input type="search" name="googlengine">

Want to only take time input.

<input type-time” name=”usr_time”>

If you want to make textbox to accept telephone numbers.

<input type=”tel” name=”mytel”>

Question 9.
What is output element in HTML 5?
Answer:
Output element is needed when you need calculation from two inputs to be summarized into a label. For instance, you have two textboxes as shown in Figure 9.11 and you want to add numbers from these textboxes and send them to a label.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 9

Below goes the code of how to use output element with HTML 5.

<form onsubmit="return false" oninput="o.value = parselnt(a.value) + parseInt(b.value)"> 
<input name="a" type="number"> + 
<input name="b" type="number"> = 
<output name="o"></output>
</form>

You can also replace “parselnt” with “valueAsNumber” for simplicity. You can also use “for” in the output element for more readability.

<output name=”o"for=”a b”></output>

Question 10.
What is SVG?
Answer:
SVG stands for Scalable Vector Graphics. It is a text-based graphics language that draws images using text, lines, dots, etc. This makes it lightweight and renders it faster.

HTML 5 and CSS 3 Interview Questions in .NET

Top HTML5 and CSS3 Questions and Answers

Question 11.
Can we see a simple example of SVG using HTML 5?
Answer:
Let’s say we want to display as shown in Figure 9.12 simple line using HTML 5 SVG.
Below is how the code of HTML 5. You can see the SVG tag which encloses the polygon tag for displaying the star image.

HTML 5 and CSS 3 Interview Questions in . NET chapter 9 img 10

<svg id="svgelem" height="200" xmlns="HTTP: // 
www.w3.org/2000/svg">
<line x1="0" y1="0" x2="200” y2 = "100"
style="stroke: red;stroke-width: 2"/>
< / svg>

Question 12.
What is the canvas in HTML 5?
Answer:
Canvas is an HTML area in which you can draw graphics.

Question 13.
So how can we draw a simple line on Canvas?
Answer:

  • Define the Canvas area.
  • Get access to the canvas context area.
  • Draw the graphic.

Define the canvas area
So to define the canvas area you need to use the below HTML code. This defines the area on which you can draw.

<canvas id=”mycanvas” width=”600M height=”500” style-’border: 1px solid #000000;”></canvas>

Get access to canvas area

To draw on the canvas area we need to first get reference of the context section. Below is the code for canvas section.

varc=document.getElementByld(“mycanvas”); 
var ctx=c. getContext(“2d’);

Draw the graphic

Now once you have access to the context object we can start drawing on the context. So first call the “moveTo” method and start from a point, use lineTo method and draw the line and then apply stroke over it.

ctx.moveTo(10, 10); 
ctx.lineTo(200, 100); 
ctx.stroke( );

Below is the complete code.

<body onload="DrawMe( );">
<canvas id="mycanvas" width="600" height="500" style="border: 1px solid
#000000;"></canvas>
</body>
<script>
function DrawMe( )
{
        var c=document.getElementByld("mycanvas");
        var ctx=c.getContext("2d");
        ctx.moveTo(10, 10);
        ctx.lineTo(200, 100);
        ctx.stroke();
}

You should get the as shown in Figure 9.12 output.

Question 14.
What is the difference between Canvas and SVG graphics?
Answer:

Note: If you see the previous two questions both canvas and SVG can draw graphics on the browser. 
So in this question interviewer wants to know when will you use what.
SVG Canvas
Here’s it’s like draw and remember. In other words any shape drawn by using SVG can be remembered and manipulated, and browser can render it again. Canvas is like draw and forget. Once something is drawn you cannot access that pixel and manipulate it.
SVG is good for creating graphics like CAD (Computer Aided Design) software where once something is drawn the user wants to manipulate it. Canvas is good for draw and forget scenarios likeanimation and games.
This is slow as it needs to remember the co­ordinates for later manipulations. This is faster as there is no intention of remembering things later.
We can have event handler associated with the drawing object. Here we cannot associate event handlers with drawing objects as we do not have references for them.
Resolution independent. Resolution dependent.

Question 15.
How to draw a rectangle using Canvas and SVG using HTML 5?
Answer:
HTML 5 code Rectangle code using SVG.

<svg xmlns="HTTP: //www.w3.org/2000/svg" version="1.1">
<rect width="300" height="100"
style="fill: rgb(0, 0, 255);stroke-width: l;stroke: rgb(0, 0, 0)"/>
</svg>

HTML 5 Rectangle code using canvas.

var c=document.getElementByld("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20, 20, 150, 100);
ctx. stroke ( ) ;

<svg xmlns=''HTTP: //www. w3 . org/2000/svg" version=" 1.1">
      <circle cx="100" cy="50" r="40" stroke="black"
      stroke-width="2" fill="red"/>
</svg>

var canvas = document.getElementByld('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

context.beginPath( );
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context. fillStyle = 'green';
context .fill ( );
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();

<!DOCTYPE html>
<html>
<body onload="DrawMe( );">
<svg width="500" height="100">
<circle id="circlel" cx="20" cy="20" r="10"
     style="stroke: none; fill: #ff0000;"/>
</svg>
</body>
<script>
var timerFunction = setlnterval(DrawMe, 20);
alert("ddd");

function DrawMe( )
{
      var circle = document.getElementByld("circle1")
      var x = circle.getAttribute("cx");
      var newX = 2 + parselnt(x);
      if(newX > 500)
      {
          newX = 20;
      }
      circle.setAttribute("cx" , newX);
}
</script>
</html>

Using jQuery

var timerFunction = setlnterval(DrawMe, 20);
function DrawMe( )
{
     var circle = $("#circlel");
            alert("ddd");
     var x = circle.attr("cx");
            alert("ddd1");
     var newX = 2 + parselnt(x);
     if (newX > 500)
     {
           newX = 20;
     }
     circle.attr("cx", newX);
}
</script>

Move a circle

<svgid="svg1"xmlns="HTTP: //www.w3.org/2000/svg">
<circleid="circle1"cx="20 "cy="20 "r="10 ’’
style="stroke: none; fill: #ff0000;"/>
</svg>
<script>
$(”#target").mousemove(function (event)
{
       var circle = $("#circlel");
       circle.attr("cx", event.clientX);
       circle.attr("cy", event.clientY);
});
</script>
</body>

SVG grouped with shapes

<svg x="100"
<g transform="rotate(45 50 50)">
<line x1="10" y1="10" x2="85" y2="10"
        Style="stroke: #006600;"/>

<rect x="10“ y="20" height="50" width="75"
        style="stroke: #006600; fill: #006600"/>

<text x="10" y="90" style="stroke: #660000; fill: #660000"> 
         Text grouped with shapes</text>
</g>
</svg>

Rectangle with a rotate

<svg xmlns="HTTP: //www.w3.org/2000/svg"
xmlns: xlink="HTTP: //www.w3.org/1999/xlink"> 

<rect x="50” y="50" height="110" width="110" 
         style="stroke: #ff0000; fill: #ccccff" 
         transform="translate (3 0) rotate(45 50 50)"
>
</rect>
<text x="70" y="100"
         transform="translate(30) rotate(45 50 50)"
>Hello World</text>
</svg>

Transform and translate

<rect x="20" y="20" width="50" height="50" 
          style="fill: #cc3333"/>
<rect x="20" y="20" width="50" height="50"
         style="fill: #3333cc"

transform=”translate(75, 25)” />

Rotate

<rect x="20" y="20" width="40" height="40" 
style="stroke: #3333cc; fill: none;"
/>
<rect x="20" y="20" width="40" height="40" 
style="fill: #3333cc" 
transform="rotate(15)"
/>

Scale ups and downs a size

<rect x="10" y="10" width="20" height="30"
style="stroke: #3333cc; fill: none;" />
<rect x="10" y="10" width="20" height="30" 
style="stroke: #000000; fill: none;"
transform="scale(2)" />

SVG path element

The <path> element is used to define a path.
The following commands are available for path data:

  • M = moveto
  • L = lineto
  • H = horizontal lineto
  • V = vertical lineto
  • C = curveto
  • S = smooth curveto
  • Q = quadratic Byyzier curve
  • T = smooth quadratic Byyzier curveto
  • A = elliptical Arc
  • Z = closepath

Define a path that starts at position 150, 0 with a line to position 75, 200 then from there, a line to 225, 200 and finally closing the path back to 150, 0:

<svg xmlns="HTTP: //www.w3.org/2000/svg" version="1.1">
       <path d="M150 0 L75 200 L225 200 Z" />
</svg>

Question 16.
What are selectors in CSS?
Answer:
Selectors help to select an element to which you want to apply a style. For example, below is a simple style called as ‘. intro” which applies red color to background of a HTML element.

<style>
.intro
{
    background-color: red;
}
</style>

To apply the above “intro” style to div we can use the “class” selector as shown in the code.

<div class="intro">
<p>My name is Shivprasad koirala.</p>
<p>I write interview questions.</p>
</div>

Question 17.
How can you apply CSS style using ID value?
Answer:
So let’s say you have an HTML paragraph tag with id “text” as shown in the below snippet.

<p id=”mytext”>This is HTML interview questions.</p>

You can create a style using ” #” selector with the ” id” name and apply the CSS value to the paragraph tag. So to apply style to “mytext” element we can use “#mytext” as shown in the CSS code.

<style>
#mytext
{
      background-color: yellow;
}
</style>

Quick revision of some important selectors.
Set all paragraph tags background color to yellow.

P, h1
{
background-color: yellow;
}
Sets all paragraph tags inside div tag to yellow background.
div p
{
background-color: yellow;
}

Sets all paragraph tags following div tags to yellow background.

div+p
{
background-color: yellow;
}

Sets all attribute with “target” to yellow background.

a[target]
{
background-color: yellow;
}
<a href="HTTP: //www.questpond.com">ASP.NET interview questions</a>
<a href="HTTP:- //www.questpond.com" target="_blank">c# interview questions</ a>
<a href="HTTP: //www.questpond.org" target="_top">.NET interview questions with answers</a>
Set all elements to yellow background when control gets focus.
input: focus
{
background-color: yellow;
}

Set hyperlinks according to action on links.

a: link (color: green;} 
a: visited (color: green;} 
a: hover (color: red;} 
a: active (color: yellow;}

Most Important HTML 5 and CSS 3 Interview Questions in .Net

Question 18.
What is the use of column layout in CSS?
Answer:
CSS column layout helps you to divide your text into columns. For example, consider the below magazine news which is one big text but we need to divide the same into 3 columns with a border in-between as shown in Figure 9.14. That’s where HTML 5 columns layout comes to help

IMG

To implement column layout we need to specify the following:

  • How many columns do we want to divide the text into?

To specify the number of columns, we need to us,e column count. “Webkit” and “Moz-column” are needed for Chrome and Firefox, respectively.

-moz-column-count: 3; /* Firefox */
-Webkit-column-count: 3; /* Safari and Chrome */ 
column-count: 3;
  • How much gap do we want to give between those columns?
-moz-column-gap: 40px; /* Firefox */
-Webkit-column-gap: 40px; /* Safari and Chrome */ 
column-gap”: 20px;
  • Do you want to draw a line between those columns, if yes how much thick?
-moz-column-rule: 4px outset #ff00ff; /* Firefox */
-Webkit-column-rule: 4px outset #ff00ff; /* Safari and Chrome */ 
column-rule: 6px outset ttffOOff;

Below is the complete code for the same.

<style>
.magazine
{
-moz-column-count: 3; /* Firefox */ _
-Webkit-column-count: 3; /* Safari and Chrome */
column-count: 3;
-moz-column-gap: 40px; /* Firefox */
-Webkit-column-gap: 40px; /* Safari and Chrome */
column-gap: 20px;
-moz-column-rule: 4px outset ttffOOff; /* Firefox */
-Webkit-column-rule: 4px outset #ff00ff; /* Safari and Chrome'*/
column-rule: 6px outset #ff00ff;
}
</style>

You can then apply the style to the text by using the class attribute.

<div class="magazine">
Your text goes here which you want to divide into 3 columns.
</div>

Question 19.
Can you explain the CSS box model?
Answer:
The CSS box model is a rectangular space around an HTML element that defines the border, padding, and margin as shown in Figure 9.15.
Border: This defines the maximum area in which the element will be contained. We can make the border visible, invisible, define height and width, etc.
Padding: This defines the spacing between border and element.

So for example, if we want to send data below is the ASP.NET code for the same. Please note the content type is set to text/event.

Response.ContentType="text/event-stream";
Response.Expires=-1;
Response.Write("data: " + DateTime.Now.ToString( ));
Response .'Flush ( ) ;

To retry after 10 seconds below is the command.

Response. Write(“retry: 10000’);

1 If you want to attach an event we need to use the “addEventListener” event as shown in the below code.

source.addEventListener('message', function(e)
{
console.log(e.data);
: }, false);

From the server side the below message will trigger the “message” function of JavaScript.

event: message
data: hello

Question 20.
What is the local storage concept in HTML 5?
Answer:
Many times we would like to store information about the user locally on the computer. For example, let’s say the user has half-filled a long-form and suddenly the Internet connection breaks off. So the user would like you to store this information locally and when the Internet comes back. He/she would like to get that information and send it to the server for storage.
Modern browsers have storage called “Local storage” in which you can store this information.

Question 21.
How can we add and remove data from local storage?
Answer:
Data is added to local storage using “key” and “value”. Below sample code shows country data “India” added with key value “Key00l”.

localStorage.setltem(“Key001”, “India’);

To retrieve data from local storage we need to use “get item” providing the key name.

var country = localStorage.getltem(“Key001’);

You can also store JavaScript object’s in the local storage using the below code.

var country = { }; 
country.name = "India"; 
country.code = "I001";
localStorage.setltem("I001", country);
var countryl = localStorage.getitem("I001");

If you want to store in JSON format you can use “JSON. stringify” function as shown in the below code.

localStorage.setltem(“l001”, JSON.stringify(country));

Question 22.
What is the lifetime of local storage?
Answer:
Local storage does not have a lifetime it will stay until either the user clear it from the browser or you remove it using JavaScript code.

Question 23.
What is the difference between local storage and cookies?

Answer:

Cookies Local storage
Client-side / Server side Data accessible both at client, side and server-side. Cookie data is sent to the server-side with every request. Data is accessible only at the local browser-side. Server cannot access local storage until deliberately sent to the server via POST or GET.
Size 4095 bytes per cookie. 5 MB per domain.
Expiration Cookies have expiration attached to it. So after that expiration the cookie and the cookie data get’s deleted. There is no expiration data. Either the end user needs to delete it from the browser or programmatically using JavaScript we need to remove the same.

Question 24.
What is session storage and how can you create one?
Answer:
Session storage is the same like local storage but the data is valid for a session. In simple words, the data is deleted as soon as you close the browser.
To create session storage you need to use “sessionStorage.variablename”. In the below code we have created a variable called “click count”.
If you refresh the browser the count increases. But if you close the browser and start again the “clickcount” variable starts from zero.

if(sessionStorage.clickcount)
{
sessionStorage. clickcount-Number (sessionStorage .‘clickcount) +1 ;
}
else
{
sessionStorage.clickcount = 0;
}

Question 25.
What is the difference between session storage and local storage?
Answer:
Local storage data persists forever but session storage is valid until the browser is open, as soon as the browser closes the session variable resets.

Question 26.
What is WebSQL?
Answer:
WebSQL is a structured relational database at the client browser side. It’s a local RDBMS (Relational Database Management System) inside the browser on which you can fire SQL (Structured Query Language) queries.

Question 27.
Is WebSQL a part of HTML 5 specification?
Answer:
No, many people label it as HTML 5 but it is not part of the HTML 5 specification. The specification is based around SQLite.

Question 28.
So how can we use WebSQL?
Answer:
The first step we need to do is open the database by using the “open database” function as shown below. The first argument is the name of the database, the next is the version, then a simple textual title, and finally the size of the database.

var db=openDatabase(‘dbCustomer’, ‘1.0’, ‘Customer app’, 2 * 1024 * 1024);

To execute SQL we then need to use the “transaction” function and call the “execute SQL” function to fire SQL.

db.transaction(function (tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS tblCust(id unique, customername)');
tx.executeSql('INSERT INTO tblcust (id, customername) VALUES(1, "shiv")');
tx.executeSql('INSERT INTO tblcust (id, customername) VALUES (2, "raju")');
}

In case you are firing “SELECT” query you will get data is “results” collection which we can loop (using loop) and display in the HTML Ul (User Interface).

db.transaction(function (tx)
{
      tx.executeSql(’SELECT * FROM tblcust', [], function (tx, results)
      {
            for (i = 0; i <results.rows.length; i++)
            {
                 msg = ”<p><b>" + results . rows . item(i). customerName + " </bx/p>" ;
                 document.querySelector('#customer).innerHTML += msg;
           }
     }, null);
}) ;

Question 29.
What is application cache in HTML5?
Answer:
One of the most demanded things by end-user is offline browsing. In other words, if an internet connection is not available page should come from browser cache, i.e., offline and application cache helps you to achieve the same. Application cache helps you to specify which files should be cached and not cached.

Question 30.
So how do we implement application cache in HTML 5?
Answer:
The first thing in we need to specify is the “MANIFEST” file, “MANIFEST” file helps you to define how your caching should work. Below is the structure of the manifest file:

CACHE MANIFEST
# version 1.0
CACHE:
Login.aspx

  • All manifest file starts with CACHE MANIFEST statement.
  • #( hash tag) helps to provide the version of the cache file.
  • CACHE command specifies which files need to be cached.
  • The content type of the manifest file should be “text/cache-manifest”.

Below is how to cache manifest has been provided using ASP.NET C#.

Response.ContentType = "text/cache-manifest";
Response.Write("CACHE MANIFEST \n"); 
Response.Write("# 2012-02-21 v1.0.0 \n"); 
Response.Write("CACHE: \n"); 
Response.Write("Login.aspx \n"); 
Response.Flush( );
Response.End( );

One the cache manifest file is created the next thing is to provide the link of the manifest file in the HTML page as shown below. ]

<html manifest= "cache. aspx">

When the above file runs the first time it gets added to the browser application cache and in case the server goes down the page is served from the application cache.

Question 31.
So how do we refresh the application cache of the browser?
Answer:
Application cache is removed by changing the version number to a new version number as specified in ‘ the ” #” tag in the below code.

CACHE MANIFEST 
# version 2.0(new) 
CACHE:
Login.aspx 
Aboutus. aspx 
NETWORK: 
Pages.aspx

Question 32.
What is the fallback in the Application Cache?
Answer:
Fallback in the application cache helps you to specify the file which will be displayed if the server is not v reachable. For instance, in the below manifest file we are saying if someone hits “/home” and if the server is not reachable then “homeoffline.html” file should be served. v

FALLBACK: 
/home/ /homeoffline.html

Question 33.
What is a network in Application Cache?
Answer:
Network command says files which should not be cached. For example, in the below code we are s saying that “home.aspx” should never be cached and or available offline.

NETWORK: 
home.aspx

Java struts interview questions – Top STRUTS Interview Questions in Java | STRUTS Framework in Java Interview Question and Answers

STRUTS Interview Questions in Java

Java struts interview questions: We have compiled the most frequently asked Java J2EE Interview Questions which will help you with different expertise levels. You can check out the frequently asked STRUTS Interview Questions & Answers in this tutorial. The Java Interview Questions on Frameworks STRUTS are provided with answers too here. Students can find the Java Questions here based on different levels like for beginners and experienced candidates, etc. Try to test your knowledge of Java Framework STRUTS by answering the questions on your own and improvise on the areas of need.

Java J2EE Interview Questions on STRUTS

Question 1.
What is Struts Definition in Java?
Answer:
Struts are the premier framework for building Java-based Web applications. Using the Model-View-Controller (MVC) design pattern, Struts solves many of the problems associated with developing high-performance, business-oriented Web applications that use Java servlets and JavaServer Pages.

Although the Model-View-Controller architecture is a powerful means of organizing code, developing such code can be a painstaking process. This is where Struts comes in. Struts is a Web application framework that streamlines the building of Web applications based on the MVC design principles. But, what does it mean? Is Struts an MVC Web application that you just add on or extend? Are Struts just some libraries? Actually, Strut is a little bit of both. Struts provide the foundation, or framework, for building MVC-oriented applications along with libraries and utilities for making MVC development faster and easier.

Question 2.
Describe the advantages of using Struts by taking up a suitable analogy?
Answer:
Consider the following analogy. If you were to create a GUI application in Java, you wouldn’t write a text field widget and a drop-down widget yourself. You would instead use Java’s swing API that already has standardized, fully functional code that provides these controls. Not only are the Swing controls ready-to-use, but they are also understood by all Java programmers.

Struts provide the same type of advantages. Struts supply a standard way of implementing an MVC application, the Struts code is tried and true, and the techniques required to use Struts are well known and documented.

Besides, Struts is open source, and information for signing up to be a member of the Struts users mailing list can be found on the Struts Web site at http://struts.apache.org/.

Question 3.
What are the basic components of Struts?
Answer:
The Struts framework is a rich collection of Java libraries and can be broken down into the following major pieces/components:-

  1. The base framework which provides core MVC functionality
  2. JSP tag libraries which enable JSP authors to use HTML-like tags to represent functionality that is defined by a Java class
  3. Tiles plugin or framework which is a rich JSP templating framework that facilitates the reuse of presentation (HTML) code
  4. Validator plugin or framework which provides a rich framework for performing data validation on both the sever side and the client-side (browser),

Question 4.
According to you, is Struts an MVC framework, a collection of utilities, or a set of JSP custom tag libraries?
Answer:
All three viewpoints are legitimate. The answer depends upon what you are going to use it for. However, the most common way of looking at Struts is an MVC framework.

Question 5.
What are the steps involved in installing Struts?
Answer:
Basically, the following three steps are involved in installing and configuring Struts:-

(1) Downloading the Struts code: You can get the latest release build at http:// struts.apache.org/downloads.html. You can get the source code, example applications,
or the documentation, but all that is absolutely required is the struts-blank Web application.

(2) Updating your CLASSPATH: To compile your Struts-based Web application, add struts- core-1.3.5.jar to the CLASSPATH used by your compiler or IDE.

(3) Bookmarking the Struts documentation: You can access the documentation online at http://struts.apache.org/l.x/learning.html. Alternatively, you can download a copy of the documentation for local access.

STRUTS Interview Questions

Question 6.
Explain the Struts flow of control?
Answer:
STRUTS Interview Questions in Java chapter 8 img 1

The Struts flow of control is summarized as follows:-

(1) The user requests a form: The input form is built with the Struts him!: tags. These tags associate a bean with the form so that you can pre-populate the form with values from your application, so that you can redisplay incorrectly filled out forms, and so that Struts knows where to store the request parameters when the form is submitted.

(2) The form is submitted to a URL of the form something.do: The form contains an ACTION ending in something. do. The Struts system receives the request, where an action mapping in struts-config.xml associates the address with an Action object.

(3) The execute method of the Action object is invoked: One of the arguments to ‘execute’ is a form bean that is automatically created and whose properties are automatically populated with the incoming form data. Once it examines the user input data in the bean, the ‘execute’ method invokes business logic and data-access logic, placing the results in normal beans stored in the request, session, or application scope. Finally, the ‘execute’ method uses mapping. find forward to return various conditions that are mapped by struts-config.xml to JSP pages.

(4) Struts forwards the request to the appropriate JSP Page: Struts normally invokes the results page with RequestDispatcherforward, although request.sendRedirect is occasionally used (e.g., with session-scoped data). In most real applications, the results page uses bean: write or the JSP 2.0 EL to output bean properties.

Question 7.
Outline the steps involved in implementing Struts.
Answer:
The following six basic steps are involved in implementing and using Struts.-

(1) Modify struts-config.xml: For basic Struts usage, this file should contain three main sections, viz. a table that maps incoming addresses to Action objects (action entries), a table that maps return conditions to JSP pages (forward entries), and a list of the beans used to handle request parameters (form-bean entries).

(2) Define a form bean: Rather than requiring you to call request.getParameter for each incoming piece of query data, Struts can instantiate and populate a bean representing the incoming form data. This is one of the most useful features of the Struts framework.

(3) Create the results beans: If the JSP page needs data resulting from business logic, then create results beans to hold the data.

(4) Define an Action class to handle the request: Struts automatically invokes the ‘execute’ method of the Action object specified in the action entry of struts-config.xml. The ‘execute’ method typically uses form bean to access data submitted by the user, invokes business logic and data-access logic, stores results in beans based on that logic and calls mapping. find forward to designate the result condition.

(5) Create a form that invokes something.do: Create an HTML form for the user’s input. Use html: form to associate the form with a bean and to specify the address that should handle the form submission. Use HTML: text and related elements to gather user data and to associate bean properties with the input elements.

(6) Display the results in a JSP page: Write a JSP page to display the results. Depending upon the user input and business logic, you could have more than one possible results page. Use bean: write or the JSP EL to output bean properties.

Interview Questions on STRUTS in Java for Experienced

Question 8.
How and why do you lay out pages with Tiles?
Answer:
Many Web sites contain pages with a common header, footer, and menu. If you would like to build your site with a common look and feel, starting with Struts Tiles is an excellent choice. With the Tiles framework, you create a common page layout for your site, and then, based on the layout, use Struts tiles: tags to include JSP fragments and Strings for the main pages of the site. The Tiles approach is much more powerful than the traditional JSP: include for including files in a JSP page. In fact, some developers use Struts just for the sake of the Tiles capability as the servlet/JSP community has very few equivalents.
We outline three main reasons for using Tiles:-

(1) Reuse (not rewrite) repeated sections of pages: For similar content, you need only sections once and then use Tiles to easily add those sections to your JSP pages.

(2) Simplify the creation of similar pages: With templates, you can easily layout similar pages on your site. Then, with the layout template, provide specific content for the layout pieces. ,

(3) Increase flexibility and ease of maintenance: With Tiles, you get a lot more flexibility than with the traditional <jsp: include .. ./> tag. Plus, the supporting elements for Tiles (such as handling relative URLs, inheritance, etc.) eases the overall maintenance of the site. The four basic steps required for using Tiles are enumerated as follows:-

(1) Sketch out the desired page layout

(2) Make a template file that represents the layout using tiles: insert wherever a layout piece should go and tiles: getAsString wherever changeable text goes

(3) Create JSP pages that define the layout pieces

(4) Create JSP pages that populate the layout using tiles: insert to refer to the layout from step 1 and tiles: put to specify the layout pieces that apply to each specific page

Question 9.
How and why do you use the Struts Validation framework?
Answer:
Probably the most tedious and time-consuming part of developing a Web site is I validation of the input data. There is no easy way of getting around it – you have to check for i missing or poorly formatted input values. Unfortunately, the servlet and JSP APIs provide no, the mechanism for easily validating input data. To the rescue come the Struts Validation framework. This framework is incredibly flexible and easy to use, supporting both client-side and server-side validation. For validating form fields, Struts gives you the following options:-

(1) Do validation in the Action: This is the most powerful and flexible approach. Validation in the Action has access to business logic, databases, and so on. However, this validation [ may require repetition of code in multiple Actions and requires you to write the validation rues yourself. Also, you need to manually map conditions back to the input page-

(2) Do validation in the form bean: You can do validation in individual setter methods – not really validation, but useful to modify values. Better, you can use the ‘validate’ method in ActionForm. This approach does not require the repetition of code in multiple Actions but still requires you to write the validation rules. Based on the return value from ‘validate’, Struts can automatically redisplay the input, page.

(3) Use automatic validator: Automatic validation is the most powerful approach. The Struts Validation framework includes many rules for automatically checking the input values (missing data, phone number format, e-mail format, etc.). In addition, the automatic validator can incorporate client-side JavaScript for field validation.

Question 10.
Distinguish between manual and automatic validation?
Answer:
We briefly discuss the differences between manual and automatic validation:-.
“7 Manual Validation: Manual validation of input fields is the most flexible. You have full access to beans, business logic, and the application database. Unfortunately, manual validation often results in repeated logic and often runs only on the server. If you also do client-side validation, then most likely, you are writing lots of tedious JavaScript code embedded in JSP code. This approach violates the Struts strategy of placing as much as possible in editable files versus in code that must be compiled.

Automatic Validation: Automatic validation typically consolidates the amount of validation code needed and lets you use standard validation rules. Also, automatic validation runs on the server, but can optionally include JavaScript that runs on the client. With automatic validation in Struts, instead of building code that requires compilation, you can easily describe the validation rules in XML files.

STRUTS Interview Questions and Answers

Struts Interview Questions and Answers for Experienced in Java

Question 11.
Distinguish between client-side and server-side validation. Should you validate data on the server or the client?
Answer:
A common question for any new Web developer is – “Should I validate data on the client or the server?” For security reasons alone, you must always validate the data on the server – a hacker (or the user) can deliberately or accidentally bypass your input forms completely (especially JavaScript validation on the client). We briefly discuss the differences between client-side and server-side ‘validation:-‘

  • Client-side Validation: For client-side validation, JavaScript code verifies the format of input fields. If any fields are bad, a dialog box can warn the user of any illegal values. If the input is bad, JavaScript can block the submission to the server. Client-side validation with JavaScript tends to be very fast. The validation does not require a trip to the server. However, there are limitations. You cannot do validation that requires application logic, such as talking to the database server. Finally, with client-side validation, you need to consider the possibility of the user deliberately or accidentally bypassing JavaScript (i.e., turning it off).
  •  Server-side Validation: For server-side validation, Java code on the server can validate the fields. Most likely, server-side validation performs similar checks as client-side validation but can invoke stronger application logic for additional checks. Instead of a pop-up dialog box, you can display warning messages back on the input form. Unfortunately, server-side validation is slower, but you really have no choice here. You must do server-side validation regardless of whether or not you do client-side validation.

Question 12.
What do you understand by properties files? What are the advantages of using properties files in the Struts framework?
Answer:
In the simplest terms, properties files are nothing more than text files containing name-value pairs, or rather, key-message pairs. By using the bean: message from the Struts tag library, you can easily retrieve your properties files and display them on your JSP pages. Nearly, all Struts developers use properties files to simplify the development of their Web applications. We summarize the two greatest advantages of using properties files as follows:-

(1) Centralized updates: If the application uses a message in several JSP pages, with properties files you can easily update a message with a single change. This capability is consistent with the Struts philosophy of making as many changes in the configuration files, not in the Java or JSP code.

(2) Internationalization (I18N): If you use messages pervasively in your JSP pages, you can internationalize your application by having multiple properties files corresponding to the locale (as with standard I18N in Java). Simply create a file for each language that requires support. For instance, to support English, Japanese, and Spanish (Mexico dialect), you would create the following message resources properties files, respectively

MessageResouces.properties
MessageResouces_ja.properties
MessageResouces_es_mx.properties

(In the chapter on internationalization, we cover I18N in more detail)

Question 13.

What is the Difference between DispatchAction and LookupDispatchAction in Struts Framework?

Question 14.

What do the Validate () and reset () methods do?

Answer:

validate() method is used to validate properties once they have been populated whereas the reset() method is used to reset all of the ActionForm’s data members before the new request values are set.

Question 15.

What configuration files are used in Struts?

Answer:

There are two configuration files used in STRUTS between the Controller and Model like  ApplicationResources.properties and struts-config.xml

Ejb 3 interview questions – Ejb Interview Questions in Java

Ejb 3 interview questions: We have compiled most frequently asked Java J2EE Interview Questions which will help you with different expertise levels.

Java J2EE Interview Questions on Ejb

Question 1.
What do you understand by EJB? Elaborate.
Answer:
Enterprise JavaBeans (EJB) is a server-side component framework that simplifies the process of building enterprise-class distributed component applications in Java. By using EJB, l» you can write scalable, reliable, and secure applications without writing your own complex distributed component framework. EJB is about rapid application development for the server-side; you can quickly and easily construct server-side components in Java by leveraging a prewritten distributed infrastructure provided by the industry. EJB is designed to support. application portability and reusability across any vendor’s enterprise middleware services.

In short, EJB is a standard for developing and deploying server-side distributed components in Java. It defines an agreement (contract) between components and application servers that enables any component to run in any compliant application server. The three main advantages of EJB are:-

  1. It is a ubiquitous industry standard;
  2. Portability is possible; and,
  3. Rapid application development.

Question 2.
Why has EJB supported only Java thus far?
Answer:
The EJB framework has supported only Java thus far, unlike the .NET framework that supports multiple languages. The reason for this is not far to seek. Java is one of the best-suited languages for building distributed components for the following reasons:-

(1) Interface/implementation separation: We need a language that supports a clean separation between the interface and implementation mainly to keep the component upgrades and maintenance to a minimum. Java supports this separation at a syntactic level through the interface and class keywords.

(2) Safe and secure: The Java architecture is much safer than traditional programming languages. In Java, if a thread dies, the application stays up. Pointers are not an issue since the language never exposes them to the programmer, Memory leaks occur much less often. Java also has a rich library set, so that Java is not just syntax of language critical applications.

(3) Cross-platform: Java runs on any platform. There is a Java Virtual Machine (JVM) for all platforms. Vendors provide support for their application servers across all the platforms most of the time. This means that EJB applications could be deployed on all these platforms. This is valuable for customers who have invested in a variety of hardware platforms, such as Intel/AMD X32-X64, SPARC, and mainframes, as well as operating systems including various flavors of UNIX, Windows, and so on, in there -i data centers.

Question 3.
What kind of problems is EJB suitable for?
Answer:
Specifically, EJB is used to help write logic that solves business problems. Typically,
EJB components (enterprise beans) can perform any of the following tasks:-

(1) Perform business logic: Examples include computing taxes on a shopping cart, ensuring that the manager has authority to approve the purchase order, or sending an order confirmation e-mail using the JavaMail API.

(2) Access a database: Examples include submitting an order for books, transferring money between two bank accounts, or calling a stored procedure to retrieve a helpdesk ticket in a customer service application. Enterprise beans can achieve database access using. many techniques, one of which is Java Database Connectivity (JDBC) API.

(3) Integrate with other systems: Examples include calling a highly transactional CICS legacy system written in C that computes the risk exposure for a new insurance customer, using a legacy VSAM (Virtual Storage Access Method) data store, or accessing SAP R/ 3. Enterprise beans can be integrated with other applications in multiple ways, one of which is the Java EE Connector Architecture.

Question 4.
Give three examples of EJB clients.
Answer:

  1. Application clients: Application clients execute on a user’s desktop either within an Internet browser environment as an applet or alone. They connect through the network to EJB components that live on a server.
  2. Dynamically generated Web pages
  3. Web service clients

Question 5.
How is distributed computing said to be the foundation of EJB? Elaborate.
Answer:
EJB enables the development and deployment of distributed components. A distributed component also referred to as a distributed object or remote object is callable from a remote system, i.e. not only it can be called from an in-process client but also from an out-of-process client that\might be located on a different system of the network. A remote invocation of a method on a distributed object follows a common process that is similar across all distributed component technologies. The main steps involved in this remote invocation process are:-
(1) The client calls a stub, which is a client-side proxy object. This stub is responsible for masking network communications from the client.

(2) The stub calls over the network to a skeleton, which is a server-side proxy object. The skeleton masks network communications from the distributed object.

(3) The skeleton delegates the call to the appropriate implementation object. This object serves the call and does the work, and returns control to the skeleton, which returns it to the stub, which finally returns control to the client.

Figure 7 depicts the method of invocation on a remote object. The key point here is that both the stub and the server-side implementation object implement the same interface (called the remote interface).

EJB Interview Questions in Java chapter 7 img 1

Question 6.
Enumerate the EJB middleware services.
Answer:
EJB performs the middleware services in two ways, viz. implicitly and explicitly. We shall not go into the details of these but just enumerate the basic EJB middleware services as:-

  • Transaction management
  • Persistence
  • Messaging
  • Security
  • Clustering

Question 7.
Explain the role-based EJB application life cycle.
Answer:
An EJB application life cycle involves three phases:-

  • Development
  • Deployment
  • Administration

Depending upon the size and scale of the application, the activities related to each of these phases/roles can range from simple to complex. EJB role-based development is elaborated in Figure 8.

EJB Interview Questions in Java chapter 7 img 2

We now briefly touch upon the responsibilities handled by these roles. The bean provider supplies business components, or enterprise answer: The application assembler is the overall application architect. After the application assembler builds the application, the application must be deployed (and go into production) in a running operational environment. This is the responsibility of an EJB deployer. Once the deployment goes live, the ‘system administrator’ takes over to oversee the stability of the operational solution.

Question 8.
Elucidate an EJB container.
Answer:
An EJB container is a piece of software that implements the EJB specification. The reason for being called a container is that it provides an environment within which EJB components live and breathe. In other words, it provides containment to the EJB components.

An EJB container is responsible for managing your enterprise bean. The most important responsibility of the container is to provide a secure, transactional, distributed environment in which enterprise beans can execute. Enumerated in the following list are just a few of the many services that are made available by the bean container:-

  • Transaction management
  • Security
  • Resource and life cycle management
  • Remote accessibility
  • Support for concurrent requests
  • Clustering and load-balancing

Question 9.
What do you mean by isolation levels? Enumerate the various levels of isolation.
Answer:
Isolation level can be defined as the degree to which operations on data by a certain transaction are affected by concurrent transactions, i.e. other transactions running at the same time. It also implies the degree to which operations on data by a transaction can affect data in concurrent transactions.

The various levels of isolations are enumerated as under:-

(1) Dirty Reads: A dirty read will occur when the first transaction reads uncommitted changes made by a second transaction. If the second transaction is rolled back, the data read by the first transaction would be invalid because the rollback reverses the changes. The first transaction won’t be aware that the data it has read has become invalid.

(2) Repeatable Reads: A repeatable read occurs when the data is guaranteed to look the same if read again during the same transaction. Repeatable reads can be guaranteed in one of two ways – either the data read is locked against changes or the data read is a snapshot that doesn’t reflect changes. If the data is locked, then it cannot be changed by any other transaction until the current transaction ends. If the data is a snapshot, then other transactions can change the data, but these changes won’t be seen by this transaction if the read is repeated.

(3) Phantom Reads: Phantom reads occur when new records inserted into the database are detectable by transactions that started prior to the insert. Queries will include records added by other transactions after their transaction has started.

Question 10.
What do you mean by Heuristic decisions? Elaborate in brief.
Answer:
Transactions are usually controlled by a transaction manager across multiple databases and servers. The transaction manager controls the transaction, based on the results of a poll against the resources (databases and other servers), it decides whether all the updates should be committed or rolled back.

A heuristic decision is when one of the resources makes a decision to commit or rollback by itself, without permission from the transaction manager. Once a heuristic decision has been made, the atomicity of the transaction is lost and possible data integrity errors can occur.

Question 11.
Enumerate and explain the various transaction types in EJB.
Answer:
The various transaction attributes/types are enumerated as under:-

(1) Not Supported: This attribute means that when a method on a bean with this transaction attribute is called, the transaction gets suspended until the method is completed, this means that the transaction scope is not propagated to the Not Supported bean or any of the methods calls it makes. Once the method in the Not Supported bean is done, the original transaction resumes its execution.

(2) Supports: Invoking a bean with this attribute will include it in the current transaction scope, i.e. if the bean or client that invokes the Supports bean is part of a transaction scope, the Supports bean, and all beans accessed by that bean become part of the original transaction. However, the Supports bean doesn’t have to be part of a transaction and can interact with clients and beans that are not included in a transaction scope.

(3) Required: When a bean’s transaction attribute is set as Required, it means that the bean method must be invoked within the scope of a transaction. If the calling client or bean is part of a transaction, the Required bean is automatically included in its original transaction scope. However, if the calling client or bean is not involved in a transaction, the Required bean starts its own new transaction. The new transaction’s scope covers only the Required bean and all beans accessed by that bean. Once the method invoked on the Required bean is done, the new transaction’s scope ends.

(4) Requires New: When a bean’s transaction attribute is set as Requires New, it means that a new transaction is always started. Regardless of whether the calling, client, or bean is part of a transaction, a method with the Requires New attribute begins a new transaction when invoked. If the calling client is already involved in a transaction, that transaction is suspended until the Requires New bean’s method call returns. The new transaction’s scope only covers the Requires New bean and all beans accessed by that bean. Once the method invoked on the Requires New bean is done, the new transaction’s scope ends and the original transaction resumes.

(5) Mandatory: When a bean’s transaction attribute is set to Mandatory, it means that the bean method must always be made part of the transaction scope of the calling client. If the calling client or bean is not part of a transaction, the invocation will fail, throwing a javax. transaction.TransactionRequiredException.

(6) Never (EJB 1.1 only): When a bean’s transaction attribute is set to Never, it means that the bean method must never be invoked within the scope of a transaction. If the calling client or bean is part of a transaction, the Never bean will throw a RemotcException. If, however, the calling client or bean is not involved in a transaction, the Never bean will execute normally without a transaction.

(7) Bean Managed (EJB 1.0 only): When a bean’s transaction attribute is set to Bean Managed, it means that the bean or method doesn’t have its transactional context implicitly managed by the EJB server. Instead, the developer can use the Java Transaction API (JPA) to explicitly manage transactions.

Question 12.
What do you mean by Re-entrant? Elaborate in brief.
Answer:
The re-entrant element in a deployment descriptor of an EJB declares that the bean either allows loopbacks (re-entrant invocations) or not. This element can have one of the two values – True or False. True implies that the bean allows loopbacks; False implies that the bean throws an exception in case a loopback occurs. Beans are not re-entrant by default. When a bean is declared as re-entrant/it means that a method that is downstream in the sequence of method calls will call back the bean. This is not advisable.

Question 13.
How can you commit transactions over multiple databases?
Answer:
A protocol called a 2-phase commit is used. This will commit the transaction only after updates have gone through on all the different database instances;

Question 14.
Elucidate the different types of beans.
Answer:
Enterprise JavaBeans are categorized into various types. Depending on the design requirements, you can use the suitable bean type:-

(1) Session beans: Session beans model business processes. They are like verbs because they perform actions. The action could be anything such as adding numbers, accessing a database, calling a legacy system, or calling another enterprise answer: Examples include a pricing engine, a workflow engine, a catalog service, a credit card authorization service, or a stock-trading service. Session beans are further divided into two categories – stateful session beans and stateless session answers: As their names suggest, stateful session hearts maintain state, encapsulated within the bean instance, across multiple; client requests, whereas stateless session beans are not tasked with retaining the state across multiple client requests.

(2) Message-driven beans (MDBs): Message-driven beans are similar to session beans in that they perform actions. The difference is that you can call message-driven beans only implicitly by sending messages to those beans, i.e. there is no direct way of invoking a method on the message-driven bean. Examples of MDBS include beans that, receive’, stock trade messages such as trade acknowledgment messages, credit cm! authorization messages, or messages within a given workflow or a business process where interactions are loosely coupled. These MDBs can, in turn, call the invoked methods directly on other EJBs or indirectly by sending a message to be received by another MDB.

(3) Entity beans: Entity beans model business data. They are like nouns because they are data objects, that is, Java objects that cache database information. Examples include a product, an order, an employee, a credit card, or a stock.

Note: Session beans can harness entity beans to accomplish business transactions.

Question 15.
Illustrate Lifecycle Diagrams of Session Beans.
Answer:

EJB Interview Questions in Java chapter 7 img 3

Question 16.
What does JNDI stand for?
Answer:
JNDI stands for Java Naming and Directory Interface.

Question 17.
What does POJO stand for?
Answer:
POJO stands for Plain Old Java Object. As a matter of fact, EJB 3 .0 entities are, in fact, POJOs. ‘

Question 18.
What does JAAS stand for?
Answer:
JAAS stands for Java Authentication and Authorization Service.

Question 19.
Elucidate JAAS.
Answer:
JAAS is a portable interface that enables you to authenticate and authorize users in Java. In a nutshell, it allows you to log in to a system without knowing about the underlying security system being used. Behind the scenes in JAAS, the implementation (such as an application server) then determines if your credentials are authentic. Moreover, JAAS enables you to write your own customized authentication modules that can then be plugged in without the need to change client code.

Question 20.
What would you do to ensure stateful bean recovery in case of its failure? Can a stateless bean also die?
Answer:
Bean failure is an important factor to consider. Since a stateful session bean caches a client conversation in memory, a bean failure may entail losing your conversation. This was not a problem with statelessness – there was no conversation to be lost.

Losing a conversation can have a devastating impact. If you have large conversations that span time, you have lost important work. Here are some of the guidelines you can use while designing your stateful beans to enable them to handle stateful recovery:-

  1. Keep your conversations short;
  2. If the performance is feasible, consider checkpointing stateful conversations yourself to minimize the impact of bean failure (such as by using entities);
  3. Write smart client code that anticipates a bean failure and reestablishes the conversational state with afresh stateful session bean.

Question 21.
What is an entity? Elaborate.
Answer:
In multi-tier enterprise applications, you will find typically two different kinds of objects:-

(1) Application logic components: These components provide methods that perform common tasks which might include the following:

  • Computing the price of an order
  • Billing a customer’s credit card
  • Computing the inverse of a matrix

Session beans model these application logic components very well.

(2) Persistent data objects: These are objects that can be rendered into persistent storage by a persistent mechanism. These kinds of objects represent ‘data’ – simple/complex information that you would like saved. Examples in this case include:

  • Bank account information, such as account numbers and balance O Human resources data, such as names, departments, and salaries of employees
  • Lead-tracking information, such as names, addresses, and phone numbers of prospective customers that you want to keep track of overtime

You may note that these objects represent people, places, and things (they are nouns). They are well suited to handling long-lived business data. Such persistent objects are called ‘entities’ in the new Java specification. These entities are plain old Java objects (POJOs) that are persisted in durable storage such as a database or legacy system. As elaborated above, entities store data as fields such as bank account numbers and bank account balances. They also have methods associated with them such as get account number( ) and get balance( ).

Question 22.
Distinguish between entities and session beans.
Answer:
The big differences between entities and session beans are that:-

  • Entities have a client-visible, persistent ‘identity (the primary key) that is distinct from their object reference;
  • Entities have a persistent client-visible state;
  • Entities are not remotely accessible;
  • An entity’s lifetime may be completely independent of an application’s lifetime.

In fact, entities are in-memory Java representations of persistent data that:

  1. Is loaded from storage and has its field populated with the stored data;
  2. Can be modified in-memory to change the values of data;
  3. Can be saved back, thus updating the database data,

Question 23.
Elucidate the Entity Life-Cycle.
Answer:

EJB Interview Questions in Java chapter 7 img 4

The life of an entity instance has two main aspects: its relationship to a specific persistence context and the synchronization of its state with the database. The EntityManagex (the Entity Manager is the interface that lets you access the entities in your application’s persistence context) distinguishes between four states in the life cycle of an entity (Figure 10 shows these four states and the transitions between them as EntityManager operations are called):-

1. new: The entity instance was created in memory but is not yet associated with either a
persistent identity in the database or a persistence context. Changes in the entity state are not synchronized with, the database at this stage.

2. managed: The entity has a persistent identity in the database and is currently associated with a persistent context. Changes to the identity will be synchronized with the database when transactions are committed or when synchronization is explicitly triggered using the flush( ) operation.

3. detached: The identity does have a persistent identity but is not or is no longer associated
with the persistence context.

4. removed: The identity is currently associated with a persistence context but has been scheduled for removal from the database.

Question 24.
What are Java RMI-IIOP and JNDI in the context of EJB?
Answer:
EJB depends upon Java RMI-IIOP and JNDI. While RMI-IIOP is the networking protocol used in EJB and is a must for interoperability with non-EJB applications such as legacy applications written in C++ or COBOL, JNDI is how beans (and their clients) lookup other beans and external resources by name when dependency injection is not available or is insufficient.

Question 25.
Elucidate Java RMI-IIOP.
Answer:
Java RMI (which stands for Java Remote Method Invocation) is a mechanism for performing simple but powerful networking. Using RMI, you can write distributed objects in Java, enabling objects to communicate in memory, across Java virtual Machines and physical devices. Java RMI-IIOP (which stands for Java RMI over the Internet Inter-ORB Protocol) is J2EE’s de facto mechanism for providing networking services relying on the CORBA network protocol IIOP. The main advantage of HOP over plain RMI’s native transport protocol JRMP (Java Remote Method Protocol) is that HOP lets your code interoperate remotely with any application on any platform that uses CORBA (Common Request Broker Architecture). It is also more mature than JRMP.

Question 26.
Elucidate RPC and RMI. How does RMI score over RPC?
Answer:
A Remote Procedure Call (RPC) is a procedural invocation from a process on one machine to a process on another machine. RPCs enable traditional procedures to reside on multiple machines yet still remain in communication. They provide a simple way to perform cross-process or cross-machine networking.

A Remote Method Invocation (RMI) in Java takes the RPC concept one step further and allows for distributed ‘object’ communications. RMI enables you to invoke not procedures, but methods, on objects remotely. You can build your networked code as full objects. This yields the benefits of object-oriented programmings, such as inheritance, encapsulation, and polymorphism.

Question 27.
Elucidate JNDI.
Answer:
The Java’Naming and Directory Interface (JNDI) is a Java API that provides a standard interface for locating users, machines, networks, objects, and services by name, e.g. you can use JNDI to locate a printer on your corporate intranet. You can also use it to locate a Java object or a database. JNDI is used in EJB, RMI-IIOP, JDBC, and more. It is the standard Java way of looking up things by name over the network and is also used to manage an enterprise bean’s environment.

Question 28.
What do you understand by a naming service? Explain giving a suitable example.
Answer:
To understand JNDI, you must first get familiar with a naming service. A naming service is an entity that performs the following tasks:-

(1) It associates names with objects: We call this ‘binding’ names to objects. This is similar to • a telephone company’s associating a person’s name with a specific residence’s telephone number.

(2) It provides a facility to find an object based on a name: We call this looking up an object, or ‘resolving’ a name. This is similar to a telephone operator finding a person’s telephone number based on that person’s name.
Naming services are everywhere in computing. When you want to locate a machine on a network, the Domain Name System (DNS) is used to translate a machine name to an IP ^Internet Protocol) address.

Question 29.
Explain the underlying need for using JNDI.
Answer:
JNDI is a system for Java-based clients to interact with naming and directory systems. JNDI is a ‘bridge’ over naming and directory services, a beast that provides one common interface to disparate directories. All directory operations are done through the JNDI interface, providing a common framework. The following surveys the advantages that JNDI has to offer:-

  • You need to learn only a single API to access all sorts of directory service information such as security credentials, phone numbers, electronic and postal mail addresses, application preferences, network addresses, machine configurations, and more.
  • JNDI insulates the application from protocol and implementation details.
  • You can use JNDI to read and write whole Java objects from directories.
  • You can link different types of directories, such as an LDAP directory with an NDS directory, and have the combination appear to be one large, federated directory. The federated directory appears to the client to be one contiguous directory.

In J2EE, you can use JNDI for many purposes inclusive of the following:-

  • Using JNDI to acquire a reference to the Java Transaction API (JTA) User-Transaction interface;
  • Using JNDI to connect to resource factories, such as JDBC drivers or Java Message Service (JMS) drivers;
  • Using JNDI for clients and for beans to look up other beans.

Question 30.
List at least four JNDI operations.
Answer:
After acquiring the initial context, you could begin to execute JNDI operations such as reading or writing data to and from the JNDI tree by using the other API calls available in JNDI. Here is a brief list of available operations that you can call on the context (although only four operations have been asked for, I am giving the complete list; you can choose any four):-

1. list( ) retrieves a list of bindings available in the current context;

2. lookup( ) resolves a name binding in the context, meaning that the operation returns the object bound to a given name in the context;

3. rename( ) gives a context a new name, such as renaming c:\temp to c:\tmp;

4. create subcontexts( ) creates a subcontext from the current context, such as creating c:\foo\bar from the folder c:\foo;

5. destroys context( ) destroys a subcontext from the current context, such as destroying c:foo\bar
from the folder c:\foo;

6. bind( ) creates a new name binding in the current context;

7. rebind( ) is the same operation as bind( ) except that it forces a bind even if there is already something in the JNDI tree with the same name.

Question 31.
How are annotations useful for EJB?
Answer:
For EJBs, annotations are an alternative to the sometimes tedious and error-prone task of specifying the required metadata in XML descriptor files. The most prominent example of this technique is the popular Xdoclet tool that can, for example, be used to generate EJB deployment descriptor files in XML from EJB-specific source code comments provided by developers. The main point to remember about the Javadoc/Xdoclet approach is that the metadata is placed in comments. This means that it is not processed by the Java compiler.

Question 32.
Outline the pros and cons of Java annotations.
Answer:
The metadata facility in Java defines an annotation language that is part of the language itself. This has the following advantages when compared with the Xdoclet approach:-

1. Ease of use: Annotations are checked and compiled by the Java language compiler, so no external tool is required.

2. Portability: Because the metadata facility is standardized, annotations are as portable as the rest of the code.

3. Type Checking: Annotations are instances of ‘annotation types’, which are compiled in their own class files.

4. Runtime Reflection: Annotations on a class can be kept in a class file and retained for runtime access.
However, the Java annotation facility in its current form also has its shortcomings

5. Unlike interface classes and exceptions, annotation types cannot form an inheritance hierarchy.

6. Annotation member types are restricted to primitive types, String, Class, enum types, annotation types, and arrays of the preceding types.

7. To annotate ‘existing’ code, you must have access to the source code.

8. Many developers have expressed their dislike of a syntax that leads to source code cluttered with @-signs. Of course, it is a matter of taste.

Question 33.
The above problem mentioned the more general criticism. What about the pros and cons of annotations with regard to EJBs?
Answer:
From the EJBs point of view, the following are the pros of annotations:-

  • Keeping the code and the metadata that describes it in sync is much easier with annotations directly on the source code;
  • Compile-time checking on typed source code annotations helps you catch errors earlier than the XML compiler because it cannot detect semantic mismatches with the Java code. This must be checked by additional verifiers at or before deployment time.

As for the cons, the one main argument against using annotations for EJBs is the following:-
To work with the metadata for beans that you didn’t write yourself, you would still need access to the source code. Adding metadata to beans that come in an EJB-jar file without code is not going to work well unless you are allowed to disassemble the code, which is usually not much fun. Fortunately, the EJB specification defines how annotations and XML descriptors can be ‘combined’: the specification requires that containers give descriptor files precedence over source code annotations.

Thus, you can always overrule and redefine the metadata that comes embedded in a far file. In a process that requires different individuals to incrementally modify metadata, you should still consider using external XML descriptor files rather than annotations embedded in the source code.

SQL Server Interview Questions on Replication

We have compiled most frequently asked SQL Server Interview Questions which will help you with different expertise levels.

SQL Server Interview Questions on Replication

SQL server replication interview questions

Question 1.
What’s the best way to update data between SQL Servers?
Answer:
By using Replication we can solve this problem. Many of the developers end up saying DTS, BCP, or distributed transaction management. But this is one of the most reliable ways to maintain consistency between databases.

Question 2.
What are the scenarios you will need multiple databases with schema?
Answer:
Following are the situations you can end up into multi-databases architecture:-

24×7 Hours uptime systems for online systems
This can be one of the major requirements for duplicating SQL Servers across networks. For instance, you have a system that is supposed to be 24 hours online. This system is hosted in a central database which is far away in terms of Geographic’s. As said first that this system should be 24 hours online, in case of any break over from the central server we hosted one more server which is inside the premises. So the application detects that it can not connect to the online server so it connects to the premises server and continues working. Later in the evening using replication all the data from the local SQL Server is sent to the central server.

License problems

SQL Server per user usage has a financial impact. So many of the companies decide to use MSDE which is free so that they do not have to pay for the client licenses. Later every evening or in some specific interval this all data is uploaded to the central server using replication.

Note MSDE supports replication.

Geographical Constraints

It is if the central server is far away and speed is one of the deciding criteria.

Reporting Server

In big multinational sub-companies are geographically far away and the management wants to host a central reporting server for the sales, which they want to use for decision making and marketing strategy. So here the transactional SQL Server’s entire database is scattered across the sub-companies and then weekly or monthly we can push all data to the central reporting server.

SQL Server Interview Questions on Replication chapter 10 img 1

You can see from the above figure how data is consolidated into a central server that is hosted in India using replication.

Question 3.
(DB)How will you plan your replication?
Answer:
Following are some important questions to be asked before going for replication.

Data planning

It’s not necessary that you will need to replicate the complete database. For example, you have a Sales database that has Customer, Sales, Event logs, and History tables. You have a requirement to host a centralized reporting server which will be used by top management to know “Sales by Customer”. To achieve this you do not need the whole database on reporting server, from the above you will only need “Sales” and “Customer” tables.

Frequency planning

As defined in the top example let’s say management wants only “Sales by Customer weekly”, so you do not need to update every day, rather you can plan weekly. But if the top management is looking for “Sales by Customer per day” then probably your frequency of updates would be every night.

The schema should not have a volatile “baseline”

Note I like the word “baseline” it really adds weight while speaking as a project manager. It’s mainly used to control change management in projects. You can say “Baseline” is a process by which you can define a logical commit to a document. For example, you are coding a project and you have planned different versions for the project. So after every version, you do a baseline and create a setup and deploy it to the client-side. Any changes after this will be a new version.

One of the primary requirements of replication is that the schemas which should be replicated across should be consistent. If you are keeping on changing the schema of the server then replication will have huge difficulty in synchronizing. So if you are going to have huge and continuous changes in the database schema rethink over replication option. Or else proper project management will help you solve this.

Question 4.
What arc publisher, distributor, and subscriber in “Replication”?
Answer:
The publisher is the one who owns the database and is the main source of data. Publisher identifies what data should be distributed across.
The distributor is a bridge between publisher and subscriber. The distributor gathers all the published data and holds it until it sends it across to ail subscriber. So as it’s a bridge that sits in between publisher and subscriber, it supports multiple publishers and subscriber concepts.
Subscriber is the end source or the final destination to which data has to be transmitted.

SQL Server Interview Questions on Replication chapter 10 img 2

Question 5.
What is “Push” and “Pull” subscription?
Answer:
Subscription can be configured in two ways:-

  • Push subscription

In push subscription, the publisher has full rights when updating data to subscribers. Subscriber completely plays a passive role in this scenario. This model is needed when we want full control of data in hands of the publisher.

  • Pull subscription

In pull subscription the subscriber requests for new or changed data. Subscriber decides when to update himself. This model is needed when we want the control to be in the hands of subscribers rather than publishers.

Question 6.
(DB)Can publication support push and pull at one time?
Answer:
A publication mechanism can have both. But a subscriber can have only one model for one publication. In short a subscriber can either be in push mode or pull mode for a publication, but not both.

Question 7.
What are different models/types of replication?
Answer:

  • Snapshot replication
  • Merge replication
  • Transactional replication
Note  Below I will go through each of them in a very detailed way.

Question 8.
What is Snapshot replication?
Answer:
A complete picture of data to be replicated is taken at the source. Depending on the schedule defined when the replication should happen, destination data is completely replaced by this. So over a period of time changes are accumulated at the publisher end and then depending on the schedule it’s sent to the destination.

Note In a snapshot you still also be sending data that has not changed.

Question 9.
What are the advantages and disadvantages of using Snapshot replication?
Answer:
Advantages:

  • Simple to set up. If the database is small or you only want to replicate master data (State code, Pin code, etc) it’s the best approach, as these values do not change heavily.
  • If you want to keep a tight control over when to schedule the data this is the best approach. For example, you will like to replicate when the network traffic is low (probably during Saturday and Sunday).

Disadvantages:

Note  This is probably the least used approach. So definitely the interviewer is expecting the 
         disadvantages points to be clearer, rather than advantages.
  • As data start growing the time taken to complete the replication will go on increasing.

Question 10.
What type of data will qualify for “Snapshot replication”?
Answer:

  • Read-only data are the best candidates for snapshot replication.
  • Master tables like zip code, pin code, etc are some valid data for snapshot replication.

Question 11.
What’s the actual location where the distributor runs?
Answer:
You can configure where the distributor will run from SQL Server. But normally if it’s a pull subscription it runs at the subscriber end and for push subscription, it runs on the publisher side.

Question 12.
Can you explain in detail how exactly “Snapshot Replication” works?
Answer:
Following are the basic steps for “Snapshot Replication” to work:-

Note There are two important components “Snapshot Agent “and “Distribution Agent” which we will define first. Snapshot agent creates an image of the complete published data and copies it to the distributor. The distribution Agent sends the copied image and replaces the data on the subscriber side.

  • Snapshot agent places a shared lock on the data to be published.
  • The whole snapshot is then copied to the distributor end. There are three files that are created one for database schema, BCP files, and the index data.
  • Finally, the snapshot agent releases a lock over the published data.
  • The distribution agent then replaces the subscriber data using files created by the snapshot agent.

SQL Server Interview Questions on Replication chapter 10 img 3

Question 13.
What is merge replication?
Answer:
If you are looking forward to managing changes on multiple servers which need to be consolidated merge replication is the best design.

Question 14.
How does merge replication works?
Answer:
The merge Agent component is one of the important components which makes merge replication possible. It consolidates all data from subscribers and applies them to publishers. Merge agent first copies all data from publishers to the subscribers and then replicates them vice-versa so that all stakeholders have consistent data.

SQL Server Interview Questions on Replication chapter 10 img 4

Merge agent stands in between subscriber and publisher. Any conflicts are resolved through a merge agent in turn which uses conflict resolution. Depending on how you have configured the conflict resolution the conflicts are resolved by the merge agent.

Question 15.
What are the advantages and disadvantages of Merge replication?
Answer:

Advantages:

  • This is the only way you can manage consolidating multiple server data.

Disadvantage:

  • It takes a lot of time to replicate and synchronize both ends.
  • There is low consistency as a lot of parties have to be synchronized.
  • There can be conflicts while merging replication if the same rows are affected in more than one subscriber and publisher. Definitely, there is conflict resolution in place but that adds complication.

Question 16.
What is conflict resolution in Merge replication?
Answer:
There can be practical situations where the same row is affected by one or many publishers and subscribers. During such critical times, the Merge agent will look at what conflict resolution is defined and make changed accordingly.

SQL Server uniquely identifies a column using a globally unique identifier for each row in a published table. If the table already has a unique identifier column, SQL Server will automatically use that column. Else it will add a rowguid column to the table and create an index based on the column.

Triggers will be created on the published tables at both the Publisher and the Subscribers. These are us^d to track data changes based on a row or column changes.

Question 17.
What is a transactional replication?
Answer:
Transactional replication as compared to snapshot replication does not replicate full data, but only replicates when anything changes or something new is added to the database. So whenever on the publisher side we have INSERT, UPDATE and DELETE operations, these changes are tracked and only these changes are sent to the subscriber end. Transactional Replication is one of the most preferred replication methodologies as they send the least amount of data across the network.
Can you explain in detail how transactional replication works?

  • Any change made to the publisher’s database is logged in to a log file.
  • Later log reader agent reads the changes and sends it to the distribution agent.
  • The distribution agent sends the data across to the subscribers.

SQL Server Interview Questions on Replication chapter 10 img 5

Question 18.
What are data type concerns during replications?
Answer:

  • If it’s a transactional replication you have to include a “Timestamp” column.
  • If it merges replication you will need a “unique identifier” column. If you do not have one replication creates one.

Note As this is an interview question book we will try to limit it only to a theoretical basis. The best way is to practically do one sample of replication with a sample project. But just for your knowledge, I will show some important screens of replication vizard.

  • In the “SQL Server Management Studio,” you can see the publication folder. When you right-click on it you can see the “New Publication” menu.

SQL Server Interview Questions on Replication chapter 10 img 6

This wizard will be used to specify the “Distribution”.

SQL Server Interview Questions on Replication chapter 10 img 8

Garbage collection in java interview questions – Garbage Collector Interview Questions in Java

Garbage collection in java interview questions: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Garbage Collector Interview Questions in Java

Garbage collection interview questions

Question 1.
What do you know about the garbage collector?
Answer: In Java, memory management is done automatically by JVM. A programmer is free of the responsibility of handling memory. A garbage collector is a part of JVM responsible for removing objects from the heap, which is no longer in use. The garbage collector typically runs in a background thread, periodically scanning the heap, identifying garbage objects, and releasing the memory they occupy so that the memory is available for future objects.

Question 2.
What is Garbage Collection and how to call it explicitly?
Answer:
When an object is no longer referred to by any variable, java automatically reclaims the memory used by that object. This is known as garbage collection. System.gc( ) method may be used to call it explicitly.

Question 3.
What is finalized ( ) method?
Answer:
finalize ( ) methods are used just before an object is destroyed and can be called just prior to garbage collection.

Question 4.
What is final, finalize( ), and finally?
Answer:
final: final keyword can be used for class, method, and variables.
A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods.
A final method can’t be overridden A final variable can’t change from its initialized value.
finalize( ): finalize( ) method is used just before an object is destroyed and can be called just prior to garbage collection.
finally: finally, a key word used in exception handling creates a block of code that will be executed after a try/catch block has been completed and before the code following the try/catch block. The final block will execute whether or not an exception is thrown.
For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This final keyword is designed to address this contingency.

Question 5.
Explain the keywords – native, transient, volatile, finally.
Answer:
native: to use methods written in another language.
transient: if u declare the state of class as transient then it’s not saved in the persistent area.
volatile: this is not optimized at the time of optimization because its value may be changed implicitly or explicitly.
finally: finally is used to do work prior to closing the program because of exceptions. It’s always called by compiler either exception generated or not.

Question 6.
What is phantom memory?
Answer:
Phantom memory is a false memory. Memory that does not exist in reality.

Question 7.
What is garbage collection?
Answer:
If no reference to an object, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. This is known as garbage collection.

Question 8.
Does garbage collection guarantee that a program will not run out of memory?
Answer:
Garbage collection does not guarantee that a program will not run out of memory. As garbage collection is JVM dependent then It is possible for programs to use memory resources faster than they are garbage collected. Moreover, garbage collection cannot be enforced, it is just suggested. Java guarantees that the finalize method will be run before an object is a garbage collected, it is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

The garbage collection is uncontrolled, which means you cannot predict when it will happen, you thus cannot predict exactly when the to finalize method will run. Once a variable is no longer referenced by anything it is available for garbage collection. You can suggest garbage collection with System.gc( ), but this does not guarantee when it will happen.

Question 9.
Can an object’s finalize( ) method be invoked while it is reachable?
Answer:
All objects finalize( ) method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalized ( ) method may be invoked by other objects.

Question 10.
What are the disadvantages of reference counting in garbage collection?
Answer:
An advantage of this scheme is that it can run in small chunks of time closely interwoven with the execution of the program. This characteristic makes it particularly suitable for real-time environments where the program can’t be interrupted for very long. A disadvantage of reference counting is that it does not detect cycles. A cycle is two or more objects that refer to one another, for example, a parent object that has a reference to its child object, which has a reference back to its parent.

These objects will never have a reference count of zero even though they may be unreachable by the roots of the executing program. Another disadvantage is the overhead of incrementing and decrementing the reference count each time. Because of these disadvantages, reference counting currently is out of favor.

Question 11.
Is it advisable to depend on finalizing for all cleanups?
Answer:
The purpose of finalization is to give an opportunity to an unreachable object to perform any clean-up before the object is garbage collected, and it is advisable.

Question 12.
Describe the Garbage Collection process in Java?
Answer:
The JVM spec mandates automatic garbage collection outside of the programmer’s control. The System.gc( ) or Runtime.gc( ) is merely a suggestion to the JVM to run the GC process but is NOT guaranteed.

Question 13.
When is an object subject to garbage collection?
Answer:
An object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Question 14.
What is the purpose of garbage collection?
Answer:
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

Question 15.
What class of exceptions are generated by the Java run-time system?
Answer:
The Java runtime system generates RuntimeException and Error exceptions.

Question 16.
If an object is a garbage collected, can it become reachable again?
Answer:
Once an object is a garbage collected, it ceases to exist. It can no longer become reachable again.

Question 17.
How does garbage collection work?
Answer:
There are several basic strategies for garbage collection: reference counting, mark-sweep, mark-compact, and copying. In addition, some algorithms can do their job incrementally (the entire heap need not be collected at once, resulting in shorter collection pauses), and some can run while the user program runs (concurrent collectors). Others must perform an entire collection at once while the user program is suspended (so-called stop-the-world collectors). Finally, there are hybrid collectors, such as the generational collector employed by the 1.2 and later JDKs, that use different collection algorithms on different areas of the heap.

Question 18.
How can you free memory?
Answer:
With the help of finalize( ) method. If a programmer really wants to explicitly request a garbage collection at some point, System.gc( ) or Runtime.gc( ) can be invoked, which will fire off a garbage collection at that time.

Question 19.
What is the purpose of finalization?
Answer:
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Question 20.
Explain garbage collection?
Or
How you can force the garbage collection?
Or
What is the purpose of garbage collection in Java, and when is it used?
Or
What is Garbage Collection and how to call it explicitly?
Or
Explain the Garbage collection mechanism in Java?
Answer:
Garbage collection is one of the most important features of Java. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.

Every class inherits finalize( )  method from java. lang. Object, the finalize( ) method is called by the garbage collector when it determines no more references to the object exists. In Java, it is a good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc( ) and Runtime.gc( ), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will be garbage collected. Garbage collection is an automatic process and can’t be forced. There is no guarantee that Garbage collection will start immediately upon the request of System.gc( ).

Question 21.
What kind of thread is the Garbage collector thread?
Answer:
It is a daemon thread.

Question 22.
What is gc( )?
Answer:
gcO is a daemon thread.gc( ) method is defined in System class that is used to send requests to JVM to perform garbage collection.

Question 23.
Can an unreferenced objects be referenced again?
Answer:
Yes.

Question 24.
How will you invoke any external process in Java?
Answer:
By Runtime.getRuntime().exec(?) method.

Question 25.
Does Java have destructors?
Answer:
The garbage collector does the job working in the background. Java does not have destructors, but it has finalizers that do a similar job.
The syntax is:
public void finalize( ){
}
if an object has a finalizer, the method is invoked before the system garbage collects the object.

Question 26.
What is the difference between Serial and Throughput Garbage collectors?
Answer:
The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).

Crystal reports interview questions – Reports Interview Questions in .NET

Crystal reports interview questions: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Reports

Note: We can not visualize a project with out reports and yes we can not visualize a .NET interview which 
does not have a reporting question. So here we have a complete Chapter which will cover two basic reporting 
tools one is crystal and the other is reporting services.

Question 1.
How do we access crystal reports in .NET?
Answer:
Crystal reports come with the Visual Studio setup itself. Right-click the Solution Explorer -> Add New Item and you can see a Crystal Report template as shown in Figure 16.1. You can add a ‘.rpt’ file using this template.

Reports Interview Questions in .NET chapter 16 img 1

Question 2.
What are the various components in crystal reports?
Answer:
There are four major components in crystal reports Report designer, Reports engine, Report viewer, and object models.
Report designer gives a graphical interface to create and modify reports. To view the designer add a new crystal report file and double click on it you should see the report designer as shown in Figure 16.2.

Reports Interview Questions in .NET chapter 16 img 2

The reports engine does the formatting and conversion part of crystal reports. It helps convert the contents of reports in Word, Excel, PDF (Portable Document Format), HTML (HyperText Markup Language), and other formats. Report viewers are controls that you can see on the Visual Studio toolbox; you can drag and drop those controls on an ASPX page or windows application to view reports made using crystal. Object models help us manage crystal reports objects during design time and runtime.

Reports Interview Questions in .NET chapter 16 img 3

Question 3.
What basic steps are needed to display a simple report in crystal?
Answer:
To understand this sample let display a simple report using crystal.
Step1: Create a Web application project.
Step2: Add New Item and select Crystal Report from the template. This adds a new rpt file in your Solution Explorer.
Step3: Double click on the rpt file click on Crystal Reports -> Field Explorer as shown in Figure 16.3. You

Reports Interview Questions in .NET chapter 16 img 4

Step 4 -> Right click on ‘Database Fields’ on the Field Explorer -> then click on Database Expert -> Expand Create New Connection -> Expand OLE DB ADO (Object Linking and Embedding, Database, Active Data Objects) -> Select Microsoft OLE DB provider for SQL (Structured Query Language) Server (this depends on what kind of data you want to connect) -> Give the Server Credentials a Click Finish and Done.

Step5: Right-click on ‘Database Fields’ on the Field Explorer -> then click on Database Expert -> Expand the Server, database and select table which you want to add to the report. Figure 16.4 shows the right pane showing the table added using Database Expert.

Step 6 -> Expand Database fields -> select Table (in this case it is ‘FactCurrencyRate’ Table). Now you can drag and drop the fields on the report as shown in Figure 16.5.

Reports Interview Questions in .NET chapter 16 img 5

Step 7 -> We now need to display the report on the ASPX page. For that, we need the ‘CrystalReportViewer’ control (See Figure 16.6). To expand the crystal reports section of the toolbar and drag the component on the ASPX page.

Reports Interview Questions in .NET chapter 16 img 6

Step 8: Now we need to go to code behind and specify the report source. That’s it now compile and run the project you can see your report live in action (See Figure 16.7).

Reports Interview Questions in .NET chapter 16 img 7

Question 4.
Can crystal reports be published as a Web service?
Answer:
Right-click on the ‘rpt’ file and click ‘Publish as Web service’ as shown in Figure 16.8.

Reports Interview Questions in .NET chapter 16 img 8

Question 5.
How do we invoke the crystal report Web service?
Answer:
We can consume the Web service as a normal Web service in . NET. The easiest way is by using the ‘ReportViewerControl’ and specifying the ASMX URL (Uniform Resource Locator) in the report source property.

Question 6.
How do we add formulas using crystal reports?
Answer:
To add any formula in the crystal report is a three-step procedure. Figure 16.9 shows the three steps in a pictorial format.
Step 1 -> Go to Field Explorer and right-click and click the ‘Formula Fields’. Click ‘New…” option.
Step 2 -> The ‘Formula Name’ dialog box appears. Give and name to the formula in the ‘Name’ textbox and click on ‘Use Editor’.
Step 3 -> You will be presented with Ul which has all the formulas and functions.

Reports Interview Questions in .NET chapter 16 img 9

Question 7.
How do we pass parameters to crystal reports?
Answer:
Sometimes we want to accept input parameters and the report works according to the parameter. To add an input parameter go to Field Explorer, go to Parameter Fields, right-click Create Parameter and you should be popped with a ‘Create Parameter Field’ dialog box as shown in Figure 16.9. Give a name to the parameter value, type and that’s it you are in action.

Reports Interview Questions in .NET chapter 16 img 10

Question 8.
How do we export from crystal reports?
Answer:
There is two way of using the Export Options: one is when we display a report using Crystal Report Viewer you can see an export icon as shown in Figure 16.11 below. You can select the options given in the ‘Format:’ drop-down list in which format you want to export.

Reports Interview Questions in .NET chapter 16 img 11

The second option is through coding. Below is a sample code snippet that shows how we can export a report. Create an object of the crystal report and call the ‘ExportToDisk’ method specifying in which format you want to export.

Dim Report as New CrystalReportlReport.
ExportToDisk (CrystalDecisions.Shared.ExportFormatType. WordForWindows, "c: \my.doc")

Question 9.
How do we print to the printer using crystal?
Answer:
In print we have two ways by which we can print one is when you display the report using Crystal Report Viewer you have a Print option and the second is by code. Below is a sample code snippet that shows how we have created an object called a report from the rpt file, specified the printer name, paper size, and then called the ‘ PrintToPrinter’ method.

Report.PrintOptions.PrinterName = "MyPrinter"
Report.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperA4 Report.PrintOptions.PaperOrientation =
CrystalDecisions.Shared.PaperOrientation.Landscape Report.PrintToPrinter(1, True, 1, 3)

Question 10.
How do we generate cross-tab reports?
Answer:
When we go for creating a new report you can see the cross-tab option in the ‘Choose, an Expert Section.

Reports Interview Questions in .NET chapter 16 img 12

Question 11.
How can we do grouping in crystal?
Answer:
For grouping in crystal, you need to use the Group Expert Wizard.

Question 12.
Can you explain three-pass reporting which crystal report uses?

Reports Interview Questions in .NET chapter 16 img 13

Crystal report uses the three-pass method for parsing reports. Before we understand what does it means let’s define what is a pass? Pass is a process used by crystal reports to read and manipulate data as per the report format. Figure 16.13 shows how the parsing happens. Let’s understand the same step-by-step. In Pre-Pass1 crystal report engine evaluates constants like x = 1 and pie = 3.14 for a report. Pass 1 does two important things get data from the database and sort records with given conditions. Once this is done it’s saved in memory and given to pre-pass2 for further parsing and manipulation. Pre-pass2 is all about grouping and sorting the records according to conditions specified in the crystal report. Pass 2 formats a report, applies conditions,s and groups them. Pass 3 is the final tunnel it just counts the pages and generates reports.

Question 13.
Can you explain reporting services architecture?
Answer:
Reporting services are mainly used to generate reports. Below are the main components of reporting services as shown in Figure 16.14. Reporting services have four major components Client, Web services, report server/manager, and reporting services database. Let’s understand all the major components and the sub-components of the same.

Client: These are the consumers of reporting services functionality. It can be the report manager or report server (we will discuss report server and manager in more detail further) or ASPX and Windows application.

Reports Interview Questions in .NET chapter 16 img 14

Reporting Web service: Microsoft chose XML to expose the functionality of reporting services. So all the functionality is exposed through Web services. One of the most important gains for a Web service is that it can be platform-independent.

Report server/manager: Report server and manager form the core engine of reporting services. There are two important systems one is a ‘Report processor’ and the other is a ‘Scheduling and Delivery Processor’. Reporting processor is the main driver to deliver reports. They take request from the end-user and process the report and send it to the end client. Figure 16.15 shows how the flow moves. We have seven basic steps which can help us understand in more detail how the report processor works.

Step 1 -> Any client like ASPX or Windows application will request to the Web service for reports.
Step 2 and 3 -> Web service will forward the request to the report processor and get the report definition from the report server DB.
Step 4 -> Reporting services uses the security extensions to authenticate the end-user.
Step 5 -> Data processing extension calls queries the application database to get data. With data processing extension we can connect to standard data sources like SQL Server, ODBC (Open Database Connectivity), Oracle, etc. You can also extend the data processing extension to adapt it to some custom data processing extensions.
Step 6 -> Rendering extension then renders the report applies format and sends the same to the end client. Using rendering extension you can deliver reports in Excel, PDF, HTML, CSV (Comma Separated Values), and XML. You can also extend the rendering extension to deliver in custom formats.

Reports Interview Questions in .NET chapter 16 img 15

The second system is ‘Scheduling and Delivery Processor. Delivery extensions make reports with the specified format and send the same to an output target like file, e-mail, FTP (File Transfer Protocol), etc. Scheduling and delivery processor does two important steps schedules reports and delivers them the same to an output like FTP,
Email etc. Schedule and delivery processor using the delivery extension to deliver reports to the defined output. So users can subscribe to the reports and depending on these subscriptions the delivery is done by schedule and delivery processor. There are two steps in this one is the subscription process and the other is the delivery process. Let’s first try to understand the subscription process. There are three steps basically as illustrated in Figure 16.16.

Reports Interview Questions in .NET chapter 16 img 16

Step 1 -> First is the request for a subscription to the report.
Step 2 -> This subscription is then stored in the report server DB.
Step 3 -> A new SQL Server agent is created for this subscription. So we have completed the subscription process.
Now that the subscription is created let’s see how the delivery process works. Here are five basic steps in the delivery process as shown in Figure 16.17.

Reports Interview Questions in .NET chapter 16 img 17

Step 1 -> When the event occurs SQL Server agent makes an entry in the report server DB.
Steps 2 and 3 -> RS windows service keeps polling SQL Server for any events. If an event has occurred it gets the event from the database and sends a message to the ‘Scheduling and Delivery Processor.
Step 4 -> The report is then processed by the report processor and sent to the delivery extension.
Step 5 -> who finally delivers it on an output which can be an e-mail address, folder, FTP, or any other kind of output.

 

Reporting Services Database: When you install reporting services you will see two databases ‘ReportServer’ and ‘ReportServerTempDB’ as shown in Figure 16.18. ‘ReportServer’ database contains report definitions, schedules, subscriptions, security details, and snapshots. ‘ReportServerTempDB’ store’s temporary information like session state about reports which is needed in-between HTTP requests and report cache information. Please note snapshots are stored in the report server and not in tempDB.

Reports Interview Questions in .NET chapter 16 img 18

Question 14.
We have two IIS applications ‘Reports’ and ‘Reportserver’ what do they do?
Answer:
When you install reporting services there are two virtual directories created as shown in Figure 16.19.

Reports Interview Questions in .NET chapter 16 img 19

The ‘Reports’ virtual directory is like an admin. If you browse to HTTP: //your name/reports/home.aspx page you can view, edit properties, and display reports. We have Figure 16.20.
1 ->We can browse reports and see the output of reports.
2 -> We can upload an RDL (Report Definition Language) file directly in the report’s database.
3 -> Using the Report Builder link we build new reports.
4 -> Using the properties we can do role assignments.
5 -> Using the subscription link we can add new outputs (FTP, Folder, etc.,) to subscribe to the reports.
6 -> Site settings help us to decide how many numbers of snapshots we want in the history, report time out the execution, report execution logging, scheduling, manage jobs, and security settings.

Reports Interview Questions in .NET chapter 16 img 20

The second virtual directory is the ‘ReportServer’ this helps us to use browse reports and use the same in ASP.NET code using URL methodology, try browsing to HTTP: //vourpcname/report server/ you can easily figure out what this virtual directory is all about.

Question 15.
Can you explain Report Definition Language (RDL) file in reporting services?
Answer:
RDL is an XML description of a report in reporting services. So basically the RDL file has the XML grammar which describes a reporting services report. Figure 16.21 shows a simple snippet of an RDL file.

Reports Interview Questions in .NET chapter 16 img 21

Question 16.
What is the basic process of making a report in reporting services?
Answer:
Here are the basic steps which will help you in creating reports in reporting services:

  • Open Visual Studio 2005 -> File -> New Project -> Select ‘Business Intelligence Reports’ -> Select Report Server project.
  • When the project is created in the Solution Explorer you will see two folders ‘Shared Data resources’ (we will come to data sources in the coming questions) and ‘Reports’. Right-click the ‘Reports’ folder and click add new reports.
  • You need to give credentials in the Wizard. Once done it pops up a query builder. Specify the report query in the query builder and go next.
  • Wizard then helps you to select the report type and some other features. Next, you should see an RDL file in your ‘Reports’ folder.
  • Click on the View menu and select toolbox and you should be able to design the report.
  • Till now we are only in the design mode of report. As said previously all reports meta-data are stored in SQL Server database ‘ReportServer’. In order that the report’s meta-data to get saved in the database, we need to publish the report.
  • To publish the report we need to specify the IIS report path. So right-click on the report project, select properties, and specify the ‘TargetServerURL’ property.

Reports Interview Questions in .NET chapter 16 img 22

  • Once we have specified the ‘ TargetserverURL’ property we need to deploy the project. So right-click on the project and click ‘Deploy’.
  • You can now view your report using HTTP: //localhost/Reports/Pages/Folder.aspx URL.

Question 17.
How can we consume reports in ASP.NET?
Answer:
There are three famous ways of calling reporting services report in ASP.NET:

  • Using URL way to access reports.
  • Using reporting Web service to programmatically access reports.
  • Using Report Viewer control,

URL way
This is the most basic way of accessing reports. We specify the URL as shown below which then displays the report on the browser. Figure 16.24 shows a basic format of how to display a report using the URL methodology.
1 -> This is the IIS (Internet Information Services) report application.
2 -> This is the project name or the project folder in which the report resides.
3 -> This is the report name.
4 -> This is the command to the reporting service of what to do. In this case we are saying render the report.

Reports Interview Questions in .NET chapter 16 img 23

If we want to get the report in PDF format we need to use the ‘Format’ parameter as shown In Figure 16.25.

Reports Interview Questions in .NET chapter 16 img 24

If we want to pass parameters to the report we can do something as shown in the figure ‘Pass parameters to the report’. In this scenario, we have passed the ‘Category’ parameter as shown in Figure

Reports Interview Questions in .NET chapter 16 img 25

Consuming reporting services Web service: if you look at the architecture of reporting service all reports are exposed through XML, i.e., Web services. You can see the Web service using this URL HTTP: //localhost/ReportServer/ReportService2005.asmx. In localhost, you need to put the server name or IP (Internet Protocol) address. So below are the steps to display reports using Web service.
Step 1 -> First add the Web service using HTTP: //localhost/ReportServer/ReportService2005.asmx in vourASP.NET project.
Step 2 -> We need to consume the Web service and use it. Figure 16.27 shows how the reporting service object is used.
1 -> You can see the Web service references to ‘ReportServicei005.asmx’.
2 -> We have named the Web service ‘Localhost’, so you can see we have imported the Web service.
3 -> We need to create an object of the ‘ReportingService2005’ class.
4 -> We need to set the credentials of the reporting object.
5 -> In this we will display which reports are present in the reporting server database. So we use the ‘ Listchildren’ method to get the reports from the Web service and then loop to display the same.
6 -> This sample code should display the reports present in the reporting service.

Reports Interview Questions in .NET chapter 16 img 26

The above example as shown in Figure 16.27 is a sample of how to use the reporting Web service. If you want to get how many input parameters the report has we need to use the ‘GetReportParameters’ method, if we want to display the report we use the ‘Render’ function. There are many other functions and methods which we have not discussed to keep the Chapter simple and to the point. Please experiment around the reporting Web service object for new methods and functions.

Reportviewer control: ASP.NET 2.0 comes with crystal report viewer control. You can drag and drop the control on the ASPX page and set the properties. Figure 16.28 shows how the ‘ReportViewer’ ^ Control looks like and how we can set the properties to view the report.

Reports Interview Questions in .NET chapter 16 img 27

Question 18.
Can you explain the difference between private and shared data sources?
Answer:
The private data source is used by a single report only while shared data sources are shared between reports. As a practice, it is good to have a shared data source so if you want to change anything you need to change only on one data source.

Question 19.
How do reports caching in reporting services work?
Answer:
As said previously reporting services has two main databases ‘ReportServer’ and ‘ReportServerTempDB’. Figure 16.29 shows how caching works in reporting services. The client first sends a request to the reporting service for the report. Reporting processor gets data from the database and the report format from the ‘report server database. Both these elements are then used to create an ‘Intermediate report format’. This intermediate format is saved in ‘ReportServerTempDB’. This intermediate format is for a particular user and for a session. So if the user generates the same report he will get a cached version. If the report is having parameters then there are different cached versions of the report for every parameter combination. Cached versions expire after a particular schedule when reports are modified, deleted, or redeployed.

Reports Interview Questions in .NET chapter 16 img 28

IN order to set the caching properties browse to a particular report using HTTP://localhost/reports/aclick on properties→ and go to the execution tab. Figure 16.30 ‘caching options’ shows different conditions on which you can define caching strategy.

Reports Interview Questions in .NET chapter 16 img 29

Question 20.
What are the major differences between Crystal and SQL reporting services?
Answer:
Ease of hosting reports: Using the URL technology in RS (Reporting Services) we can host reports more easily than in crystal report where we need to make a Ul for the same.

Supporting platforms: Crystal can run on Windows, IBM (International Business Machines), and sun while RS (Reporting Services) can run only on Windows environments.

Client tools: In reporting services we have Business Intelligence (Bl) and development studio while in crystal its Report designer.

Caching: This is achieved in crystal by using cache server while in reporting services it’s stored as snapshots in the Report server database.

Export formats: in crystal, we have HTML, PDF, Excel, XML, Word, PDF, RTF (Rich Text Format), CSV, text files while in SQL Server 2005 we have all the formats above it also gives the capability to extend custom reporting formats.

Data sources: Crystal support more data sources while RS only supports Microsoft and oracle data sources. Crystal supports ADO (Active Data Objects), COM, Database excels Access, Exchange, NT, Xbase, JDBC (Java Database Connectivity), File system, and Paradox. RS supports only SQL Server, Oracle, ODBC (Open Database Connectivity), OLEDB and you can also extend additional data sources which do not exist in crystal reports.

Version issues: One of the main issues faced in the crystal is it has different versions which make it difficult to use, while RS comes with SQL Server minimizing the version issue.

Web server support: Crystal can run on IIS 5/6, Apache, Lotus, etc., while RS works only with IIS 5.0 and above.

Note: We have also shipped a PDF ‘SQLvsCrystaL WP.pdf’ which has been published by 
HTTP: // www.aiobaiknowiedae.com/. This PDF has very precise and detailed differences between 
crystal reports and SQL reporting services.