C# INTERVIEW QUESTION TIPS PART 3

5. Run-time Type Information

5.1 How can I check the type of an object at runtime?

You can use the is keyword. For example:
using System;

class CApp
{
public static void Main()
{
string s = "fred";
long i = 10;

Console.WriteLine( "{0} is {1}an integer", s, (IsInteger(s) ? "" : "not ") );
Console.WriteLine( "{0} is {1}an integer", i, (IsInteger(i) ? "" : "not ") );
}
static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer
5.2 Can I get the name of a type at runtime?
Yes, use the GetType method of the object class (which all types inherit from). For example:
using System;

class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();

DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object obj )
{
Console.WriteLine( "Type name = {0}, full type name = {1}", obj.GetType(), obj.GetType().FullName );
}
}
}
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

6. Miscellaneous

6.1 How do I do a case-insensitive string comparison?

Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not.
"fred" == "Fred" // false
System.String.Compare( "fred", "Fred", true ) // true

6.2 Does C# support a variable number of arguments?

Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().

6.3 How can I process command-line arguments?

Like this:
using System;

class CApp
{
public static void Main( string[] args )
{
Console.WriteLine( "You passed the following arguments:" );
foreach( string arg in args )
Console.WriteLine( arg );
}
}

6.4 Does C# do array bounds checking?

Yes. An IndexOutOfRange exception is used to signal an error.

6.5 How can I make sure my C# classes will interoperate with other .NET languages?

Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.

6.6 How do I use the 'using' keyword with multiple objects?

You can nest using statements, like this:
using( obj1 )
{
using( obj2 )
{
...
}
}
However consider using this more aesthetically pleasing (but functionally identical) formatting:
using( obj1 )
using( obj2 )
{
...
}
6.7 What is the difference between == and object.Equals?

For value types, == and Equals() usually compare two objects by value. For example:
int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will display:
True
True
However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:
StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True
s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).
Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one you'll inherit by default if you write a class) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.
Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.
6.8 How do I enforce const correctness in C#?
You can't - at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there's no way to specify that a method should not modify an argument passed in to it. And there's no way to specify that a method does not modify the object on which it is acting.
To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.
There are of course ways of addressing this issue. For example, see Brad Abram's post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.

7. C# 2.0

7.1 What are the new features in C# 2.0?

Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features.
Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
Thread t = new Thread(ThreadFunc);
instead of this:
Thread t = new Thread( new ThreadStart(ThreadFunc) );
Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.
Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable, where T is a value type. As suggested by the name, this allows values of the type to be 'null', or 'undefined'.

Read More ->>

C# INTERVIEW QUESTION TIPS PART 2

3. Classes and Structs

3.1 Structs are largely redundant in C++. Why does C# have them?

In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.

3.2 Does C# support multiple inheritance (MI)?

No, though it does support implementation of multiple interfaces on a single class or struct.

3.3 Is a C# interface the same as a C++ abstract class?

No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members - it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.

3.4 Are C# constructors the same as C++ constructors?

Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:
class Person
{
public Person( string name, int age ) { ... }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( "", 0 ) {}
}
Another difference is that virtual method calls within a constructor are routed to the most derived implementation - see Can I Call a virtual method from a constructor.
Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.)
Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.
Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson's article.

3.5 Are C# destructors the same as C++ destructors?

No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed 'non-deterministic finalization', and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the 'using' construct to make this easier.

3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?

Presumably they wanted C++ programmers to feel at home. I think they made a mistake.

3.7 Are all methods virtual in C#?

No. Like C++, methods are non-virtual by default, but can be marked as virtual.

3.8 How do I declare a pure virtual function in C#?

Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).

3.9 Can I call a virtual method from a constructor/destructor?

Yes, but it's generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.
C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)
The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

3.10 Should I make my destructor virtual?

A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.

4. Exceptions

4.1 Can I use exceptions in C#?

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.

4.2 What types of object can I throw as exceptions?

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.

4.3 Can I define my own exceptions?

Yes, just derive your exception class from System.Exception.
Note that if you want your exception to cross remoting boundaries you'll need to do some extra work - see http://www.thinktecture.com/Resources/RemotingFAQ/CustomExceptions.html for details.

4.4 Does the System.Exception class have any cool features?

Yes - the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
using System;

class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine( "System.Exception stack trace = \n{0}", e.StackTrace );
}
}

static void f()
{
throw new Exception( "f went pear-shaped" );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()
Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn't quite what you expect.

4.5 When should I throw an exception?

This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an 'unexpected' error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.

4.6 Does C# have a 'throws' clause?

No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.

Read More ->>

C# INTERVIEW QUESTION TIPS PART 1

1.1 What is C#?

C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. Microsoft describe C# as follows:

"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced 'C sharp') is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."
You can get the ECMA C# spec in PDF form here, or use Jon Jagger's html version
.
1.2 How do I develop C# apps?

The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.
1.3 Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
• Stick with standard C++. Don't use .NET at all.
• Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.
• Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code - simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.

1.4 Does C# have its own class library?

Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

2. Types

2.1 What standard types does C# use?

C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don't assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ - this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.
2.2 Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called 'boxing'. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.

2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?

Yes. For example:
class CApplication
{
public static void Main()
{
int x = 25;
string s = "fred";

DisplayMe( x );
DisplayMe( s );
}

static void DisplayMe( object o )
{
System.Console.WriteLine( "You are {0}", o );
}
}
This would display:
You are 25
You are fred

2.4 What are the fundamental differences between value types and reference types?

C# divides types into two categories - value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward - an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.
The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.
For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heap
but in C# there is no control:
int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!

2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?

It isn't, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process - the object is converted back to a value.
int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 - still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap

2.6 Are C# references the same as C++ references?

Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:
void displayStringLength( string s )
{
Console.WriteLine( "String is length {0}", s.Length );
}
The problem with this method is that it will throw a NullReferenceException if called like this:
string s = null;
displayStringLength( s );
Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:
void displayStringLength( string s )
{
if( s == null )
Console.WriteLine( "String is null" );
else
Console.WriteLine( "String is length {0}", s.Length );
}

Read More ->>

ORACLE INTERVIEW QUESTION TIPS PART 5

81. How will you monitor the space allocation?

By querying DBA_SEGMENT table/view

82. How will you monitor rollback segment status?

Querying the DBA_ROLLBACK_SEGS view
IN USE - Rollback Segment is on-line.
AVAILABLE - Rollback Segment available but not on-line.
OFF-LINE - Rollback Segment off-line
INVALID - Rollback Segment Dropped.
NEEDS RECOVERY - Contains data but need recovery or corrupted.
PARTLY AVAILABLE - Contains data from an unresolved transaction involving a
distributed database.

83. List the sequence of events when a large transaction that exceeds beyond its optimal value
when an entry wraps and causes the rollback segment to expand into another extend.

Transaction Begins.
An entry is made in the RES header for new transactions entry
Transaction acquires blocks in an extent of RBS
The entry attempts to wrap into second extent. None is available, so that the RBS must extent.
The RBS checks to see if it is part of its OPTIMAL size.
RBS chooses its oldest inactive segment.
Oldest inactive segment is eliminated.
RBS extents
The data dictionary tables for space management are updated.
Transaction Completes.

84. How can we plan storage for very large tables?

Limit the number of extents in the table
Separate table from its indexes.
Allocate sufficient temporary storage.
85. How will you estimate the space required by a non-clustered table?
Calculate the total header size
Calculate the available data space per data block
Calculate the combined column lengths of the average row
Calculate the total average row size.
Calculate the average number rows that can fit in a block
Calculate the number of blocks and bytes required for the table.
After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table.

86. It is possible to use raw devices as data files and what are the advantages over file system files?

Yes.
The advantages over file system files are that I/O will be improved because Oracle is bye-passing the kernel which writing into disk. Disk corruption will be very less.

87. What is a Control file?

Database's overall physical architecture is maintained in a file called control file. It will be used to maintain internal consistency and guide recovery operations. Multiple copies of control files are advisable.

88. How to implement the multiple control files for an existing database?

Shutdown the database
Copy one of the existing control file to new location
Edit Config ora file by adding new control filename
Restart the database.

89. What is redo log file mirroring? How can be achieved?

Process of having a copy of redo log files is called mirroring.
This can be achieved by creating group of log files together, so that LGWR will automatically writes them to all the members of the current on-line redo log group. If any one group fails then database automatically switch over to next group. It degrades performance.

90. What is advantage of having disk shadowing / mirroring?

Shadow set of disks save as a backup in the event of disk failure. In most operating systems if any disk failure occurs it automatically switchover to place of failed disk.
Improved performance because most OS support volume shadowing can direct file I/O request to use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks.

91. What is use of rollback segments in Oracle database?

They allow the database to maintain read consistency between multiple transactions.

92. What is a rollback segment entry?

It is the set of before image data blocks that contain rows that are modified by a transaction.
Each rollback segment entry must be completed within one rollback segment.
A single rollback segment can have multiple rollback segment entries.

93. What is hit ratio?

It is a measure of well the data cache buffer is handling requests for data.
Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.

94. When will be a segment released?

When Segment is dropped.
When Shrink (RBS only)

When truncated (TRUNCATE used with drop storage option)

95. What are disadvantages of having raw devices?

We should depend on export/import utility for backup/recovery (fully reliable)
The tar command cannot be used for physical file backup, instead we can use dd command, which is less flexible and has limited recoveries.

96. List the factors that can affect the accuracy of the estimations?

- The space used transaction entries and deleted records, does not become free immediately after completion due to delayed cleanout.
- Trailing nulls and length bytes are not stored.
- Inserts of, updates to and deletes of rows as well as columns larger than a single data block, can cause fragmentation a chained row pieces.
Database Security & Administration

97. What is user Account in Oracle database?

A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges.

98. How will you enforce security using stored procedures?

Don't grant user access directly to tables within the application.
Instead grant the ability to access the procedures that access the tables.
When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure.

99. What are the dictionary tables used to monitor a database space?

DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.
SQL*Plus Statements

100. What are the types of SQL statement?

Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT.
Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.
Transactional Control: COMMIT & ROLLBACK
Session Control: ALTERSESSION & SET ROLE
System Control: ALTER SYSTEM.

101. What is a transaction?

Transaction is logical unit between two commits and commit and rollback.

102. What is difference between TRUNCATE & DELETE?

TRUNCATE commits after deleting entire table i.e., cannot be rolled back.
Database triggers do not fire on TRUNCATE
DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.

103. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables.
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

104. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

105. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

106. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg.
select empno, ename from emp where.

107. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

108. Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query, including all duplicates.

109. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

110. What is the fastest way of accessing a row in a table?

Using ROWID.
CONSTRAINTS

111. What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

112. What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

113. What is the usage of SAVEPOINTS?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed.

114. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.
115. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

116. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.

For CHAR the maximum length is 255 and 2000 for VARCHAR2.

117. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY?

Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

118. What are the pre-requisites to modify datatype of a column and to add a column with NOT NULL constraint?

- To modify the datatype of a column the column must be empty.
- To add a column with NOT NULL constrain, the table must be empty.

119. Where the integrity constraints are stored in data dictionary?

The integrity constraints are stored in USER_CONSTRAINTS.

120. How will you activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

121. If unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?

It won't, Because SYSDATE format contains time attached with it.

122. What is a database link?

Database link is a named path through which a remote database can be accessed.

123. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value?

Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed.

124. What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continue to generate values after reaching either maximum or minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.
NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value.EW?

- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.

126. Can a view be updated/inserted/deleted? If Yes - under what conditions?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

127. If a view on a single base table is manipulated will the changes be reflected on the base table?

If changes are made to the tables and these tables are the base tables of a view, then the changes will be reference on the view.

Read More ->>

ORACLE INTERVIEW QUESTION TIPS PART 4

Database Logical & Physical Architecture

64. What is Database Buffers?

Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.

65. What is dictionary cache?

Dictionary cache is information about the database objects stored in a data dictionary table.
66. What is meant by recursive hints?

Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of data dictionary cache.

67. What is redo log buffer?

Changes made to the records are written to the on-line redo log files. So that they can be used in roll forward operations during database recoveries. Before writing them into the redo log files, they will first brought to redo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size.

68. How will you swap objects into a different table space for an existing database?

- Export the user
- Perform import using the command imp system/manager file=export.dmp indexfile=newrite.sql. This will create all definitions into newfile.sql.
- Drop necessary objects.
- Run the script newfile.sql after altering the tablespaces.
- Import from the backup for the necessary objects.

69. List the Optional Flexible Architecture (OFA) of Oracle database? How can we organize the tablespaces in Oracle database to have maximum performance?

SYSTEM - Data dictionary tables.
DATA - Standard operational tables.
DATA2- Static tables used for standard operations
INDEXES - Indexes for Standard operational tables.
INDEXES1 - Indexes of static tables used for standard operations.
TOOLS - Tools table.
TOOLS1 - Indexes for tools table.
RBS - Standard Operations Rollback Segments,
RBS1,RBS2 - Additional/Special Rollback segments.
TEMP - Temporary purpose tablespace
TEMP_USER - Temporary tablespace for users.
USERS - User tablespace.

70. How will you force database to use particular rollback segment?

SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

71. What is meant by free extent?

A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free.

72.Which parameter in Storage clause will reduce number of rows per block?

PCTFREE parameter
Row size also reduces no of rows per block.

73. What is the significance of having storage clause?

We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updating, etc.,

74. How does Space allocation table place within a block?

Each block contains entries as follows
Fixed block header
Variable block header
Row Header, row date (multiple rows may exists)
PCTEREE (% of free space for row updating in future)

75. What is the role of PCTFREE parameter is storage clause?

This is used to reserve certain amount of space in a block for expansion of rows.

76. What is the OPTIMAL parameter?

It is used to set the optimal length of a rollback segment.

77. What is the functionality of SYSTEM table space?

To manage the database level transactions such as modifications of the data dictionary table that record information about the free space usage.

78. How will you create multiple rollback segments in a database?

- Create a database, which implicitly creates a SYSTEM rollback segment in a SYSTEM tablespace.
- Create a second rollback segment name R0 in the SYSTEM tablespace.
- Make new rollback segment available (after shutdown, modify init.ora file and start database)
- Create other tablespaces (RBS) for rollback segments.
- Deactivate rollback segment R0 and activate the newly created rollback segments.

79. How the space utilization takes place within rollback segments?

It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is in use then it forced to acquire a new extent (number of extents is based on the optimal size)

80. Why query fails sometimes?

Rollback segment dynamically extent to handle larger transactions entry loads.
A single transaction may wipeout all available free space in the rollback segment tablespace. This prevents other user using rollback segments

Read More ->>

ORACLE INTERVIEW QUESTION TIPS PART 3

Data Base Administration

51. What is a database instance? Explain.

A database instance (Server) is a set of memory structure and background processes that access a set of database files. The processes can be shared by all of the users.
The memory structure that is used to store the most queried data from database. This helps up to improve database performance by decreasing the amount of I/O performed against data file.

52. What is Parallel Server?

Multiple instances accessing the same database (only in multi-CPU environments)

53. What is a schema?

The set of objects owned by user account is called the schema.

54. What is an index? How it is implemented in Oracle database?

An index is a database structure used by the server to have direct access of a row in a table. An index is automatically created when a unique of primary key constraint clause is specified in create table command

55. What are clusters?

Group of tables physically stored together because they share common columns and are often used together is called cluster.

56. What is a cluster key?

The related columns of the tables are called the cluster key. The cluster key is indexed using a cluster index and its value is stored only once for multiple tables in the cluster.

57. What is the basic element of base configuration of an Oracle database?

It consists of
one or more data files.
one or more control files.
two or more redo log files.
The Database contains
multiple users/schemas
one or more rollback segments
one or more tablespaces
Data dictionary tables
User objects (table,indexes,views etc.,)
The server that access the database consists of
SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)
SMON (System MONito)
PMON (Process MONitor)
LGWR (LoG Write)
DBWR (Data Base Write)
ARCH (ARCHiver)
CKPT (Check Point)
RECO
Dispatcher
User Process with associated PGS

58. What is a deadlock? Explain.

Two processes waiting to update the rows of a table, which are locked by other processes then deadlock arises.
In a database environment this will often happen because of not issuing the proper row lock commands. Poor design of front-end application may cause this situation and the performance of server will reduce drastically.
These locks will be released automatically when a commit/rollback operation performed or any one of this processes being killed externally.

Memory Management

59. What is SGA?

The System Global Area in an Oracle database is the area in memory to facilitate the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is database buffers, dictionary cache, redo log buffer and shared pool area.

60. What is a shared pool?

The data dictionary cache is stored in an area in SGA called the shared pool. This will allow sharing of parsed SQL statements among concurrent users.

61. What is mean by Program Global Area (PGA)?

It is area in memory that is used by a single Oracle user process.

62. What is a data segment?

Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored.

63. What are the factors causing the reparsing of SQL statements in SGA?

Due to insufficient shared pool size.
Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE.

Read More ->>

ORACLE INTERVIEW QUESTION TIPS PART 2

28. What is database link?

A database link is a named object that describes a "path" from one database to another.

29. What are the types of database links?

Private database link, public database link & network database link.

30. What is private database link?

Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures.

31. What is public database link?

Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

32. What is network database link?

Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition.

33. What is data block?

Oracle database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.

34. How to define data block size?

A data block size is specified for each Oracle database when the database is created. A database users and allocated free database space in Oracle data blocks. Block size is specified in init.ora file and cannot be changed latter.

35. What is row chaining?

In circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.

36. What is an extent?

An extent is a specific number of contiguous data blocks, obtained in a single allocation and used to store a specific type of information.

37. What is a segment?

A segment is a set of extents allocated for a certain logical structure.

38. What are the different types of segments?

Data segment, index segment, rollback segment and temporary segment.

39. What is a data segment?

Each non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.

40. What is an index segment?

Each index has an index segment that stores all of its data.

41. What is rollback segment?

A database contains one or more rollback segments to temporarily store "undo" information.

42. What are the uses of rollback segment?

To generate read-consistent database information during database recovery and to rollback uncommitted transactions by the users.

43. What is a temporary segment?

Temporary segments are created by Oracle when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use.

44. What is a datafile?

Every Oracle database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.

45. What are the characteristics of data files?

A data file can be associated with only one database. Once created a data file can't change size. One or more data files form a logical unit of database storage called a tablespace.

46. What is a redo log?

The set of redo log files for a database is collectively known as the database redo log.

47. What is the function of redo log?

The primary function of the redo log is to record all changes made to data.

48. What is the use of redo log information?

The information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database's data files.

49. What does a control file contains?

- Database name
- Names and locations of a database's files and redolog files.
- Time stamp of database creation.

50. What is the use of control file?

When an instance of an Oracle database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.

Read More ->>

ORACLE INTERVIEW QUESTION TIPS PART 1

Oracle Concepts and Architecture

Database Structures

1. What are the components of physical database structure of Oracle database?

Oracle database is comprised of three types of files. One or more datafiles, two are more redo log files, and one or more control files.

2. What are the components of logical database structure of Oracle database?

There are tablespaces and database's schema objects.

3. What is a tablespace?

A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

4. What is SYSTEM tablespace and when is it created?

Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

5. Explain the relationship among database, tablespace and data file.

Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace.

6. What is schema?

A schema is collection of database objects of a user.

7. What are Schema Objects?

Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.

8. Can objects of the same schema reside in different table spaces?

Yes.
9. Can a tablespace hold objects from different schemes?

Yes.
10. What is Oracle table?

A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

11. What is an Oracle view?

A view is a virtual table. Every view has a query attached to it. (The query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

12. Do a view contain data?

Views do not contain or store data.

13. Can a view based on another view?

Yes.

14. What are the advantages of views?

- Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.

- Hide data complexity.
- Simplify commands for the user.
- Present the data in a different perspective from that of the base table.
- Store complex queries.

15. What is an Oracle sequence?

A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

16. What is a synonym?

A synonym is an alias for a table, view, sequence or program unit.

17. What are the types of synonyms?

There are two types of synonyms private and public.

18. What is a private synonym?

Only its owner can access a private synonym.

19. What is a public synonym?

Any database user can access a public synonym.

20. What are synonyms used for?

- Mask the real name and owner of an object.
- Provide public access to an object
- Provide location transparency for tables, views or program units of a remote database.
- Simplify the SQL statements for database users.

21. What is an Oracle index?

An index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

22. How are the index updates?

Indexes are automatically maintained and used by Oracle. Changes to table data are automatically incorporated into all relevant indexes.

23. What are clusters?

Clusters are groups of one or more tables physically stores together to share common columns and are often used together.

24. What is cluster key?

The related columns of the tables in a cluster are called the cluster key.

25. What is index cluster?

A cluster with an index on the cluster key.

26. What is hash cluster?

A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.

27. When can hash cluster used?

Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.

Read More ->>

ASP.NET INTERVIEW QUESTION TIPS 3

1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2. What’s the difference between Response.Write() andResponse.Output.Write()?

Response.Output.Write() allows you to write formatted output.

3. What methods are fired during the page load?

Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.

4. When during the page processing cycle is ViewState available?

After the Init() and before the Page_Load(), or OnLoad() for a control.

5. What namespace does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

6. Where do you store the information about the user’s locale?

System.Web.UI.Page.Culture

7. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.

8. What’s a bubbled event?

When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?

Add an OnMouseOver attribute to the button. Example:

btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

10. What data types do the RangeValidator control support?

Integer, String, and Date.

11. Explain the differences between Server-side and Client-side code?

Server-side code executes on the server. Client-side code executes in the client's browser.

12. What type of code (server or client) is found in a Code-Behind class?

The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

13. Should user input data validation occur server-side or client-side? Why?

All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

14. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

Valid answers are:
• A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
• A DataSet is designed to work without any continuing connection to the original data source.
• Data in a DataSet is bulk-loaded, rather than being loaded on demand.
• There's no concept of cursor types in a DataSet.
• DataSets have no current record pointer You can use For Each loops to move through the data.
• You can store many edits in a DataSet, and write them to the original data source in a single operation.
• Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

16. What is the Global.asax used for?

The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

17. What are the Application_Start and Session_Start subroutines used for?

This is where you can set the specific variables for the Application and Session objects.
18. Can you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

19. Whats an assembly?

Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
20. Describe the difference between inline and code behind.
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21. Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

22. Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

The Fill() method.

24. Can you edit data in the Repeater control?

No, it just reads the information from its data source.

25. Which template must you provide, in order to display data in a Repeater control?

ItemTemplate.

26. How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate.

27. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?

You must set the DataSource property and call the DataBind method.

28. What base class do all Web Forms inherit from?

The Page class.

29. Name two properties common in every validation control?

ControlToValidate property and Text property.

30. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

DataTextField property.

31. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator control.

32. How many classes can a single .NET DLL contain?

It can contain many classes.

Read More ->>

ASP INTERVIEW QUESTION TIPS PART 2

Which of the following elements in the Web.Config file allows you to specify the custom settings for a Web application?

1. configSections
2. appSettings
3. customErrors
4. trace

Correct Answer: -> 2
Feedback: -> That’s correct. The appSettings element of the Web.config file is used to define the custom settings for a Web application. For example, you can use the appSettings element to store the connection string in the database that you need to access in the various Web Forms of a Web application.

Which of the following statements about a cookie is true?
1. A cookie is a server-side state management option.
2. A cookie is stored on a Web server.
3. A cookie can be either temporary or persistent.
4. A cookie contains application-specific information.

Correct Answer: -> 3

Feedback: -> That’s correct. A cookie can be either temporary or persistent. A temporary cookie, also known as a session cookie, exists in the memory space of a browser. When the browser is closed, all the session cookies added to the browser are lost. A persistent cookie is saved as a text file in the file system of the client computer.

Which of the following types of deployment projects will you use to deploy an ASP.NET application?

1. A setup project
2. A Web setup project
3. A merge module project.
4. A cab project

Correct Answer: -> 2

Feedback: -> That’s correct. A Web setup project is used to package a Web-based application and create a Windows Installer (.msi) file.

The armed forces of a small nation want to develop an Intranet site to manage the stock of arsenal in their stores as well as at forward positions. The armed forces are concerned about espionage and sabotage. Therefore, security is a very important aspect of the application. In the given scenario, which authentication scheme will be the most appropriate?

1. Basic authentication
2. Integrated Windows authentication
3. Anonymous authentication
4. Passport authentication

Correct Answer: -> 2
Feedback: -> That’s incorrect. As per the scenario, the armed forces are concerned about espionage and sabotage. However, in basic authentication, the password of a user is transmitted over a network in an unencrypted form. This makes the password vulnerable to security breaches. Therefore, basic authentication cannot be used in the given scenario.

How can you bind the value entered in the TextBox control txtCity to the Label control Label1?
1. By setting the DataSource property of the Label1 control to txtCity
2. By setting the DataMember property of the Label1 control to txtCity
3. By setting the Text property of the Label1 control to txtCity.Text
4. By using the DataBindings property of the Label1 control and setting the custom binding _expression to txtCity.Text

Correct Answer: -> 4
Feedback: -> That’s correct. To specify the data binding _expression for the Label1 control, you need to click the DataBindings property to open the Label1 DataBindings dialog box. Then, you need to click the Custom binding _expression radio button and specify the data binding _expression in the text box.

You have created a DataList control and added a Button control to it. You have not set the CommandName property of the Button control. Which of the following events will be generated when a user clicks the Button control?
1. EditCommand
2. UpdateCommand
3. ItemCommand
4. CancelCommand

Correct Answer: -> 3

Feedback: -> That’s correct. The ItemCommand event is generated when you click a Button control with no predefined CommandName.

Which file contains the scripts that define the start and end events of an ASP.NET application and its sessions?
1. AssemblyInfo.cs
2. Global.asax
3. Web.Config
4. WebApplication.vsdisco
Correct Answer: -> 2
Feedback: -> That’s incorrect. The Web.Config file is an XML file that contains configuration data on each unique URL resource used in an ASP.NET Web project.

You have created the errors.html file to display error messages for your ASP.NET application. You want to redirect a client browser to the errors.html file whenever an error occurs in the ASP.NET application. How can this be achieved?
1. By setting the defaultRedirect attribute of the customErrors element to “errors.html”
2. By setting the mode attribute of the customErrors element to “errors.html”
3. By setting the defaultRedirect attribute of the appSettings element to “errors.html”
4. By setting the redirect attribute of the customErrors element to “errors.html”

Correct Answer: -> 1
Feedback: -> That’s correct. The defaultRedirect attribute of the customErrors element is used to specify the URL to which the client browser should be redirected when an error occurs.

Which of the following statements will you use in the Web.Config file to specify that an ASP.NET application should use one of the IIS authentication schemes?

1.
2.
3.
4.
Correct Answer: -> 1

Feedback: -> That’s correct. The Windows authentication mode allows you to specify that ASP.NET application should use one of the IIS authentication schemes.

Which of the following statements about the ViewState property is true?
1. The ViewState property is a server-side state management option.
2. By default, the ViewState property of both Web pages and the controls on the Web pages is disabled.
3. Each Web Form page and the controls on the page have the ViewState property that is inherited from the base Control class.
4. The ViewState property should be enabled when you have a large volume of information to maintain.
Correct Answer: -> 3

Feedback: -> That’s incorrect. The ViewState property is a client-side state management option.

Which control allows you to display banner advertisements on an ASP.NET Web Form?
1. A DataGrid control
2. A Repeater control
3. An XML Web server control
4. An AdRotator control
Correct Answer: -> 4

Feedback: -> That’s correct. An AdRotator control allows you to display banner advertisements on an ASP.NET Web Form.

Which of the following classes provides forward-only access to a stream of XML data and checks whether or not an XML document is well-formed?

1. XmlDocument
2. XmlTextReader
3. XmlTextWriter
4. XPathDocument
Correct Answer: -> 2

Feedback: -> That’s correct. The XmlTextReader class provides forward-only access to a stream of XML data and checks whether or not an XML document is well-formed.

The XML Web server control belongs to which namespace?

1. System.Xml
2. System.Xml.Xsl
3. System.Web.UI.WebControls
4. System.Web.UI

Correct Answer: -> 3
Feedback: -> That’s incorrect. The System.Xml namespace provides a rich set of classes for processing XML data.

Which event is generated when a control triggers the reloading of an ASP.NET Web page?
1. Init
2. Load
3. Control
4. Unload

Correct Answer: -> 3

Feedback: -> That’s incorrect. The Load event is generated when an ASP.NET Web page is loaded into memory.

Which of the following state management options can be used to submit information to another page by using a URL?
1. The Viewstate property
2. Hidden fields
3. Cookies
4. Query strings

Correct Answer: -> 4

Feedback: -> That’s correct. Query strings are used if you need to submit information another page by using a URL

Read More ->>

ASP INTERVIEW QUESTION TIPS PART 1

The Control class belongs to which namespace?

1. System.Web.UI
2. System.Web.UI.WebControls
3. System.Web
4. System
Correct Answer: -> 1

Feedback: -> That’s correct. The Control class is the base class for all the server controls that are used for building the user interface. It resides in the System.Web.UI namespace, which contains the base classes used to build the user interface of an ASP.NET page.

Which of the following state management options can be used to automatically save the value of each control before rendering the page?

1. The ViewState property
2. Hidden fields
3. Cookies
4. Query strings

Your Answer: -> 1

Feedback: -> That’s correct. Each Web Form page and the controls on the page have the ViewState property that is inherited from the base Control class. The ASP.NET framework uses the ViewState property to automatically save control-specific and page-specific values.

Which class supports page-level tracing in an ASP.NET application?
1. TraceContext
2. Trace
3. HttpHandlerConfigHandler
4. HttpModulesConfigHandler
Your Answer: -> 1
Feedback: -> That’s correct. The TraceContext class supports the trace functionality for ASP.NET pages.

Which attribute of the forms element is used in the Web.Config file to specify the page to which a user request is to be redirected for logon?
1. name
2. loginUrl
3. protection
4. timeout
Correct Answer: -> 2
Feedback: -> That’s correct. The loginUrl attribute of the forms element is used to specify the page to which the user request is to be redirected for logon when no valid authentication cookie is found.

Which of the following objects is used to store and retrieve information that can be shared among all the users of an application?
1. Request
2.. Application
3. Response
4. Server
Correct Answer: -> 2
Feedback: -> That’s correct. The Application object is used to store and retrieve the information that can be shared among all the users of an application. For example, you can use an Application object to create a chat page.

You have created the login.aspx Web Form for accepting the user name and password. To successfully log on, a user must specify “appuser” as the user name and “paradise” as the password. Which of the following statements will you use in the Web.Config file to be able to perform the specified task?


1.







2.







3.





4.






Correct Answer: -> 2

Feedback: -> That’s incorrect. Web.Config is an XML-based file. Therefore, it must conform to the rules for well-formed XML documents. In the code, the tags are not closed properly. Therefore, the code will result in an error.

Which of the following attributes of the trace element is used to specify whether or not trace information will be displayed for each Web Form?
1. enabled
2. requestLimit
3. pageOutput
4. traceMode
Correct Answer: -> 3

Feedback: -> That’s incorrect. The enabled attribute is used to enable the trace feature for an ASP.NET application.


Which of the following is the correct definition of impersonation?

1. Impersonation refers to the process of verifying whether a user has permissions to access an application.
2. Impersonation refers to the process of restricting the access of an authenticated user to parts of the application or Web site for which a user is already authenticated.
3. Impersonation refers to an ASP.NET application using the identity of a client.
4. Impersonation refers to the practice of providing content and other facilities, such as the background color of the Web Form, to users based on their preferences.

Correct Answer: -> 3
Feedback: -> That’s incorrect. Authentication refers to the process of verifying whether a user has permissions to access an application.

Which of the following templates refers to the collection of elements and controls that are rendered once for each row in a data source?

1. SelectedItemTemplate
2. ItemTemplate
3. EditItemTemplate
4. AlternatingItemTemplate

Correct Answer: -> 2
Feedback: -> That’s incorrect. SelectedItemTemplate refers to the collection of elements and controls that are rendered when an item is selected in the server control.

Read More ->>

Java Experienced interview questions Tips

Java Experienced interview questions

1. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. For example, a thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

2. What are different ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, blocking on I/O, unsuccessfully attempting to acquire an object’s lock, or invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
3. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
4. What’s new with the stop(), suspend() and resume() methods in new JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
5. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.
6. What method is used to specify a container’s layout?
The setLayout() method is used to specify a container’s layout. For example, setLayout(new FlowLayout()); will be set the layout as FlowLayout.
7. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
8. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
9. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects. One example of class in Collections API is Vector and Set and List are examples of interfaces in Collections API.
10. What is the List interface?
The List interface provides support for ordered collections of objects. It may or may not allow duplicate elements but the elements must be ordered.
11. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
12. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects. The main visible advantage of this class is programmer needn’t to worry about the number of elements in the Vector.
13. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
14. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
15. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
16. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits, ASCII require 7 bits (although the ASCII character set uses only 7 bits, it is usually represented as 8 bits), UTF-8 represents characters using 8, 16, and 18 bit patterns, UTF-16 uses 16-bit and larger bit patterns
17. What is the difference between yielding and sleeping?
Yielding means a thread returning to a ready state either from waiting, running or after creation, where as sleeping refers a thread going to a waiting state from running state. With reference to Java, when a task invokes its yield() method, it returns to the ready state and when a task invokes its sleep() method, it returns to the waiting state
18. What are wrapper classes?
Wrapper classes are classes that allow primitive types to be accessed as objects. For example, Integer, Double. These classes contain many methods which can be used to manipulate basic data types
19. Does garbage collection guarantee that a program will not run out of memory?
No, it doesn’t. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection. The main purpose of Garbage Collector is recover the memory from the objects which are no longer required when more memory is needed.
20. Name Component subclasses that support painting?
The following classes support painting: Canvas, Frame, Panel, and Applet.
21. What is a native method? A native method is a method that is implemented in a language other than Java. For example, one method may be written in C and can be called in Java.
22. How can you write a loop indefinitely?
for(;;) //for loop
while(true); //always true
23. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
24. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing a opened file, closing a opened database Connection.
25. What invokes a thread’s run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
26. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
27. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
28. What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
29. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
30. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
31. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. For example,
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or not
}
32. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
33. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.

Read More ->>

J2EE interview questions Tips

1. What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:
o Client-tier components run on the client machine.
o Web-tier components run on the J2EE server.
o Business-tier components run on the J2EE server.
o Enterprise information system (EIS)-tier software runs on the EIS server.
2. What is J2EE?
- J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
3. What are the components of J2EE application?
- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
1. Application clients and applets are client components.
2. Java Servlet and JavaServer Pages technology components are web components.
3. Enterprise JavaBeans components (enterprise beans) are business components.
4. Resource adapter components provided by EIS and tool vendors.
4. What do Enterprise JavaBeans components contain?
- Enterprise JavaBeans components contains Business code, which is logic
that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.
5. Is J2EE application only a web-based?
- No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
6. Are JavaBeans J2EE components?
- No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
7. Is HTML page a web component?
- No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
8. What can be considered as a web component?
- J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
9. What is the container?
- Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
10. What are container services?
- A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
11. What is the web container?
- Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.
12. What is Enterprise JavaBeans (EJB) container?
- It manages the execution of enterprise beans for J2EE applications.
Enterprise beans and their container run on the J2EE server.
13. What is Applet container?
- IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
14. How do we package J2EE components?
- J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.
15. What is a thin client?
- A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
16. What are types of J2EE clients? - Following are the types of J2EE clients:
o Applets
o Application clients
o Java Web Start-enabled rich clients, powered by Java Web Start technology.
o Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
17. What is deployment descriptor?
- A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations
for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.
18. What is the EAR file?
- An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
19. What is JTA and JTS?
- JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
20. What is JAXP?
- JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
21. What is J2EE Connector?
- The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.
22. What is JAAP?
- The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
23. What is Java Naming and Directory Service?
- The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and
directory services such as LDAP, NDS, DNS, and NIS.
24. What is Struts?
- A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
25. How is the MVC design pattern used in Struts framework?
- In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

Read More ->>

Java developer position Interview questions Tips Part - 2

1. What are the implicit objects?
- Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.
2. Is JSP technology extensible?
- Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
3. How can I implement a thread-safe JSP page?
What are the advantages and Disadvantages of using it? - You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe
4. How does JSP handle run-time exceptions?
- You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
5. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
- You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
6. How do I use comments within a JSP page?
- You can use “JSP-style” comments to selectively block out code while debugging or simply to comment your scriptlets. JSP comments are not visible at the client. For example:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:

Of course, you can also use comments supported by your JSP scripting language within your scriptlets. For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>
12. Response has already been commited error. What does it mean?
- This error show only when you try to redirect a page after you already have written something in your page. This happens because HTTP specification force the header to be set up before the lay out of the page can be shown (to make sure of how it should be displayed, content-type="text/html” or “text/xml” or “plain-text” or “image/jpg", etc.) When you try to send a redirect status (Number is line_status_402), your HTTP server cannot send it right now if it hasn’t finished to set up the header. If not starter to set up the header, there are no problems, but if it ’s already begin to set up the header, then your HTTP server expects these headers to be finished setting up and it cannot be the case if the stream of the page is not over… In this last case it’s like you have a file started with some output (like testing your variables.) Before you indicate that the file is over (and before the size of the page can be setted up in the header), you try to send a redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
13. How do I use a scriptlet to initialize a newly instantiated bean?
- A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
14.
15. 16. value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/ >
17. <%-- scriptlets calling bean setter methods go here --%>
18.

19. How can I enable session tracking for JSP pages if the browser has disabled cookies?
- We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
20. hello1.jsp
21. <%@ page session="true" %>
22. <%
23. Integer num = new Integer(100);
24. session.putValue("num",num);
25. String url =response.encodeURL("hello2.jsp");
26. %>
27. '>hello2.jsp
28. hello2.jsp
29. <%@ page session="true" %>
30. <%
31. Integer i= (Integer )session.getValue("num");
32. out.println("Num value in session is "+i.intValue());
33. How can I declare methods within my JSP page? - You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare. For example:
34. <%!
35. public String whereFrom(HttpServletRequest req) {
36. HttpSession ses = req.getSession();
37. ...
38. return req.getRemoteHost();
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from ");
43. %>
44. <%= whereFrom(request) %>
45. Another Example
46. file1.jsp:
47. <%@page contentType="text/html"%>
48. <%!
49. public void test(JspWriter writer) throws IOException{
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
54. <%@include file="file1.jsp"%>
55.
56.
57. <%test(out);% >
58.
59.
60. Is there a way I can set the inactivity lease period on a per-session basis?
- Typically, a default inactivity lease period for all sessions is set within your JSP engine admin screen or associated properties file. However, if your JSP engine supports the Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been created. For example:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
64. How can I set a cookie and delete a cookie from within a JSP page?
- A cookie, mycookie, can be deleted using the following scriptlet:
65. <%
66. //creating a cookie
67. Cookie mycookie = new Cookie("aName","aValue");
68. response.addCookie(mycookie);
69. //delete a cookie
70. Cookie killMyCookie = new Cookie("mycookie", null);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
75. How does a servlet communicate with a JSP page?
- The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.
76. public void doPost (HttpServletRequest request, HttpServletResponse response) {
77. try {
78. govi.FormBean f = new govi.FormBean();
79. String id = request.getParameter("id");
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
83. //use the id to compute
84. //additional bean properties like info
85. //maybe perform a db query, etc.
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89. getServletConfig().getServletContext().getRequestDispatcher
90. ("/jsp/Bean1.jsp").forward(request, response);
91. } catch (Exception ex) {
92. . . .
93. }
94. }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"
/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
95. How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the default?
- One should be very careful when having JSP pages extend custom servlet classes as opposed to the default one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine by:
Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass also needs to do the following:
o The service() method has to invoke the _jspService() method
o The init() method has to invoke the jspInit() method
o The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %>
96. How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
- You could make a simple wrapper function, like
97. <%!
98. String blanknull(String s) {
99. return (s == null) ? "" : s;
100. }
101. %>
102. then use it inside your JSP form, like
103. " >
104. How can I get to print the stacktrace for an exception occuring within my JSP page? - By printing out the exception’s stack trace, you can usually diagonse a problem better when debugging JSP pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception and which method called that method. However, you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet demonstrates how you can print a stacktrace from within a JSP error page:
105. <%@ page isErrorPage="true" %>
106. <%
107. out.println(" ");
108. PrintWriter pw = response.getWriter();
109. exception.printStackTrace(pw);
110. out.println(" ");
111. %>
112. How do you pass an InitParameter to a JSP?
- The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The example page below enumerates through all the parameters and prints them to the console.
113. <%@ page import="java.util.*" %>
114. <%!
115. ServletConfig cfg =null;
116. public void jspInit(){
117. ServletConfig cfg=getServletConfig();
118. for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
119. String name=(String)e.nextElement();
120. String value = cfg.getInitParameter(name);
121. System.out.println(name+"="+value);
122. }
123. }
124. %>
125. How can my JSP page communicate with an EJB Session Bean? - The following is a code snippet that demonstrates how a JSP page can interact with an EJB session bean:
126. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
127. <%!
128. //declare a "global" reference to an instance of the home interface of the session bean
129. AccountHome accHome=null;
130. public void jspInit() {
131. //obtain an instance of the home interface
132. InitialContext cntxt = new InitialContext( );
133. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
134. accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
135. }
136. %>
137. <%
138. //instantiate the session bean
139. Account acct = accHome.create();
140. //invoke the remote methods
141. acct.doWhatever(...);
142. // etc etc...
143. %>


Read More ->>