Practice | GeeksforGeeks | A computer science portal for geeks

Popular Company Tags

Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs
show more


Amazon
Microsoft
Oracle
Samsung
Adobe
Synopsys
Infosys
Cisco
Wipro
Ola-Cabs
Morgan-Stanley
Goldman-Sachs


Popular Topic Tags

Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph
show more


Maths
Array
Dynamic-Programming
Greedy-Algorithm
Hashing
Tree
Bit-Algorithm
Matrix
Backtracking
Operating System
Linked-List
Graph

Home
krishnabhatia
Subjective Answers

Home
krishnabhatia
Subjective Answers
 Selection of a victim. Given a set of deadlocked transactions, we must determine which transaction (or transactions) to roll back to break the deadlock. We should roll back those transactions that will incur the minimum cost. Unfortunately, the term minimum cost is not a precise one.
Factors which determine the cost of a rollback
How long the transaction has computed, and how much longer the transaction will compute before it completes its designated task.
How many data items the transaction has used.
How many more data items the transaction needs for it to complete.
How many transactions will be involved in the rollback. 
Cursor stability is a form of degree-two consistency designed for programs that iterate over tuples of a relation by using cursors.
Instead of locking the entire relation, cursor stability ensures that:
The tuple that is currently being processed by the iteration is locked in shared mode.
Any modified tuples are locked in exclusive mode until the transaction commits.
Cursor stability is used in practice on heavily accessed relations as a means of increasing concurrency and improving system performance. Applications that use cursor stability must be coded in a way that ensures database consistency despite the possibility of non-serializable schedules. 
The timestamp ordering protocol operates as follows:
 Suppose that transaction Ti issues read(Q).

If TS(T i) < W-timestamp(Q), then Ti needs to read a value of Q that was already overwritten. Hence, the read operation is rejected, and Ti is rolled back.
If TS(T i)≥W-timestamp(Q), then the read operation is executed, and R-timestamp(Q) is set to the maximum of R-timestamp(Q) and TS(Ti).

If TS(T i) < W-timestamp(Q), then Ti needs to read a value of Q that was already overwritten. Hence, the read operation is rejected, and Ti is rolled back.
If TS(T i)≥W-timestamp(Q), then the read operation is executed, and R-timestamp(Q) is set to the maximum of R-timestamp(Q) and TS(Ti).
 Suppose that transaction Ti issues write(Q).

If TS(Ti) < R-timestamp(Q), then the value of Q that Ti is producing was needed previously, and the system assumed that that value would never be produced. Hence, the system rejects the write operation and rolls Ti back.
If TS(Ti) < W-timestamp(Q), then Ti is attempting to write an obsolete value of Q. Hence, the system rejects this write operation and rolls Ti back.
Otherwise, the system executes the write operation and sets W-timestamp(Q) to TS(Ti).
	  

If TS(Ti) < R-timestamp(Q), then the value of Q that Ti is producing was needed previously, and the system assumed that that value would never be produced. Hence, the system rejects the write operation and rolls Ti back.
If TS(Ti) < W-timestamp(Q), then Ti is attempting to write an obsolete value of Q. Hence, the system rejects this write operation and rolls Ti back.
Otherwise, the system executes the write operation and sets W-timestamp(Q) to TS(Ti).
	  
There are two deadlock prevention schemes using timestamp
 The wait–die scheme is a non-preemptive technique. When transaction Ti requests a data item currently held by Tj, Ti is allowed to wait only if it has a timestamp smaller than that of Tj (that is, Ti is older than Tj). Otherwise, Ti is rolled back (dies)
 The wound–wait scheme is a preemptive technique. It is a counterpart to the wait–die scheme. When transaction Ti requests a data item currently held by Tj, Ti is allowed to wait only if it has a timestamp larger than that of Tj (that is, Ti is younger than Tj).Otherwise, Tj is rolled back(Tj is wounded by Ti). 
A phantom read occurs when, in the course of a transaction, two identical queries are executed, and the collection of rows returned by the second query is different from the first.
This can occur when range locks are not acquired on performing a SELECT.... WHERE operation.
In other words, data getting changed in current transaction by other transactions is called Phantom Reads.
Let us consider a schedule S in which there are two consecutive instructions, I and J, of transactions Ti and Tj, respectively (i != j).If I and J refer to different data items, then we can swap I and J without affecting the results of any instruction in the schedule. However, if I and J refer to the same data item Q, then the order of the two steps may matter.
There are four cases we need to consider (since we are dealing with read and write only)
 I = read(Q), J = read(Q). The order of I and J does not matter, since the same value of Q is read by Ti and Tj, regardless of the order.
 I =read(Q), J =write(Q). If I comes before J, then Ti does not read the value of Q that is written by Tj in instruction J. If J comes before I, then Ti reads the value of Q that is written by Tj. Thus, the order of I and J matters.
 I = write(Q), J = read(Q). The order of I and J matters for reasons similar to those of the previous case.
 I = write(Q), J = write(Q). Since both instructions are write operations, the order of these instructions does not affect either Ti or Tj.However, the value obtained by the next read(Q) instruction of S is affected, since the result of only the latter of the two write instructions is preserved in the database. If there is no other write(Q) instruction after I and J in S, then the order of I and J directly affects the final value of Q in the database state that results from schedule S.
	 
	 
Concurrency gives the following two advantages
 Improved throughput and resource utilization. A transaction consists of many steps. Some involve I/O activity; others involve CPU activity. The CPU and the disks in a computer system can operate in parallel. Therefore, I/O activity can be done in parallel with processing at the CPU. The parallelism of the CPU and the I/O system can, therefore, be exploited to run multiple transactions in parallel. While a read or write on behalf of one transaction is in progress on one disk, another transaction can be running in the CPU, while another disk may be executing a read or write on behalf of a third transaction. All of this increases the throughput of the system—that is, the number of transactions executed in a given amount of time. Correspondingly, the processor and disk utilization also increase, in other words, the processor and disk spend less time idle, or not performing any useful work.
Reduced waiting time. There may be a mix of transactions running on a system, some short and some long. If transactions run serially, a short transaction may have to wait for a preceding long transaction to complete, which can lead to unpredictable delays in running a transaction. If the transactions are operating on different parts of the database, it is better to let them run concurrently, sharing the CPU cycles and disk accesses among them. Concurrent execution reduces the unpredictable delays in running transactions. Moreover, it also reduces the average response time: the average time for a transaction to be completed after it has been submitted.
	 
Data in a database can be stored in:
Volatile storage. Information residing in volatile storage does not usually survive system crashes. Examples of such storage are main memory and cache memory. Access to volatile storage is extremely fast, both because of the speed of the memory access itself, and because it is possible to access any data item in volatile storage directly.
Nonvolatile storage. Information residing in nonvolatile storage survives system crashes. Examples of nonvolatile storage include secondary storage devices such as magnetic disk and flash storage, used for online storage, and tertiary storage devices such as optical media, and magnetic tapes, used for archival storage 
Stable storage. Information residing in stable storage is never lost (theoretically never cannot be guaranteed—for example, it is possible, although extremely unlikely, that a black hole may envelop the earth and permanently destroy all data!). Although stable storage is theoretically impossible to obtain, it can be closely approximated by techniques that make data loss extremely unlikely. To implement stable storage, we replicate the information in several nonvolatile storage media (usually disk) with independent failure modes. Updates must be done with care to ensure that a failure during an update to stable storage does not cause a loss of information. 
Operations performed on a transaction are
read(X), which transfers the data item X from the database to a variable, also called X, in a buffer in main memory belonging to the transaction that executed the read operation.
write(X), which transfers the value in the variable X in the main-memory buffer of the transaction that executed the write to the data item X in the database. 
Queries involving a natural join may be processed in several ways, depending on the availability of indices and the form of physical storage for the relations. 
If the join result is almost as large as the Cartesian product of the two relations, a block nested-loop join strategy may be advantageous.
If indices are available, the indexed nested-loop join can be used.
 If the relations are sorted, a merge join may be desirable.It may be advantageous to sort a relation prior to join computation (so as to allow the use of the merge-join strategy).
 The hash-join algorithm partitions the relations into several pieces, such that each piece of one of the relations fits in memory. The partitioning is carried out with a hash function on the join attributes so that corresponding pairs of partitions can be joined independently. 
 The first action that the system must perform on a query is to translate the query into its internal form, which (for relational database systems) is usually based on the relational algebra. In the process of generating the internal form of the query, the parser checks the syntax of the user’s query, verifies that the relation names appearing in the query are names of relations in the database, and so on. If the query was expressed in terms of a view, the parser replaces all references to the view name with the relational-algebra expression to compute the view. 
Pipelines can be executed in the following two ways
 In a demand-driven pipeline, the system makes repeated requests for tuples from the operation at the top of the pipeline. Each time that an operation receives a request for tuples, it computes the next tuple (or tuples) to be returned and then returns that tuple. If the inputs of the operation are not pipelined, the next tuple(s) to be returned can be computed from the input relations, while the system keeps track of what has been returned so far. If it has some pipelined inputs, the operation also makes requests for tuples from its pipelined inputs. Using the tuples received from its pipelined inputs, the operation computes tuples for its output and passes them up to its parent. 
 In a producer-driven pipeline, operations do not wait for requests to produce tuples but instead generate the tuples eagerly. Each operation in a producer-driven pipeline is modeled as a separate process or thread within the system that takes a stream of tuples from its pipelined inputs and generates a stream of tuples for its output.
 The first step in each case is to partition the two relations by the same hash function, and thereby create the partitions r0,r1,...,rnh and s0,s1,...,snh. Depending on the operation, the system then takes these steps on each partition i =0,1,...,nh
Different set operations
 r ∪ s

 Build an in-memory hash index on ri
. Add the tuples in si to the hash index only if they are not already present.
Add the tuples in the hash index to the result

 Build an in-memory hash index on ri
. Add the tuples in si to the hash index only if they are not already present.
Add the tuples in the hash index to the result
 r ∩ s

Build an in-memory hash index on ri.
For each tuple in si, probe the hash index and output the tuple to the result only if it is already present in the hash index.

Build an in-memory hash index on ri.
For each tuple in si, probe the hash index and output the tuple to the result only if it is already present in the hash index.
 r − s

Build an in-memory hash index on ri.
For each tuple in si, probe the hash index, and if the tuple is present in the hash index, delete it from the hash index.
Add the tuples remaining in the hash index to the result.
	   

Build an in-memory hash index on ri.
For each tuple in si, probe the hash index, and if the tuple is present in the hash index, delete it from the hash index.
Add the tuples remaining in the hash index to the result.
	   
Various ways in which  a selection operation on a relation whose tuples are stored together in one file are:
 A1 (linear search). In a linear search, the system scans each file block and tests all records to see whether they satisfy the selection condition. An initial seek is required to access the first block of the file. 
A2 (primary index, equality on key). For an equality comparison on a key attribute with a primary index, we can use the index to retrieve a single record that satisfies the corresponding equality condition
 A3 (primary index, equality on non-key). We can retrieve multiple records by using a primary index when the selection condition specifies an equality comparison on a non-key attribute, A.
A4 (secondary index, equality). Selections specifying an equality condition can use a secondary index. This strategy can retrieve a single record if the equality condition is on a key; multiple records may be retrieved if the indexing field is not a key 
Bucket overflow occurs because
 Insufficient buckets. The number of buckets, which we denote nB, must be chosen such that nB > nr/fr, where nr denotes the total number of records that will be stored and fr denotes the number of records that will fit in a bucket.This designation, assumes that the total number of records is known when the hash function is chosen. 
 Skew. Some buckets are assigned more records than are others, so a bucket may overflow even when other buckets still have space. This situation is called bucket skew.
Skew can occur for two reasons:

Multiple records may have the same search key.
 The chosen hash function may result in nonuniform distribution of search keys.

Multiple records may have the same search key.
 The chosen hash function may result in nonuniform distribution of search keys.
 Dense index: In a dense index, an index entry appears for every search-key value in the file. In a dense clustering index, the index record contains the search-key value and a pointer to the first data record with that search-key value. The rest of the records with the same search-key value would be stored sequentially after the first record, since, because the index is a clustering one, records are sorted on the same search key. In a dense nonclustering index, the index must store a list of pointers to all records with the same search-key value. 
 Sparse index: In a sparse index, an index entry appears for only some of the search-key values. Sparse indices can be used only if the relation is stored in sorted order of the search key, that is if the index is a clustering index. As is true in dense indices, each index entry contains a search-key value and a pointer to the first data record with that search-key value. To locate a record, we find the index entry with the largest search-key value that is less than or equal to the search-key value for which we are looking. We start at the record pointed to by that index entry, and follow the pointers in the file until we find the desired record.
 
Indexing techniques are evaluated on the basis of
Access types: The types of access that are supported efficiently.Access types can include finding records with a specified attribute value and finding records whose attribute values fall in a specified range.
Access time: The time it takes to find a particular data item, or set of items, using the technique in question.  
 Insertion time: The time it takes to insert a new data item. This value includes the time it takes to find the correct place to insert the new data item, as well as the time it takes to update the index structure. 
 Deletion time: The time it takes to delete a data item. This value includes the time it takes to find the item to be deleted, as well as the time it takes to update the index structure.
Space overhead: The additional space occupied by an index structure. Provided that the amount of additional space is moderate, it is usually worthwhile to sacrifice the space to achieve improved performance.
	 
Different techniques used by BUFFER MANAGER are
 Buffer replacement strategy. When there is no room left in the buffer, a block must be removed from the buffer before a new one can be read in. Most operating systems use a least recently used (LRU) scheme, in which the block that was referenced least recently is written back to disk and is removed from the buffer. This simple approach can be improved on for database application.
Pinned blocks. For the database system to be able to recover from crashes it is necessary to restrict those times when a block may be written back to disk.For instance, most recovery systems require that a block should not be written to disk while an update on the block is in progress. A block that is not allowed to be written back to disk is said to be pinned. Although many operating systems do not support pinned blocks, such a feature is essential for a database system that is resilient to crashes. 
Forced output of blocks.There are situations in which it is necessary to write back the block to disk, even though the buffer space that it occupies is not needed. This write is called the forced output of a block.
Records can be organized in the following ways:
 Heap file organization. Any record can be placed anywhere in the file where there is space for the record. There is no ordering of records. Typically, there is a single file for each relation.
 Sequential file organization. Records are stored in sequential order, according to the value of a “search key” of each record.
Hashing file organization. A hash function is computed on some attribute of each record.The result of the hash function specifiesinwhich block of the file the record should be placed
Mapping cardinalities, or cardinality ratios, express the number of entities to which another entity can be associated via a relationship set.
Mapping cardinalities are most useful in describing binary relationship sets, although they can contribute to the description of relationship sets that involve more than two entity sets.
For a binary relationship set R between entity sets A and B, the mapping cardinality must be 
 One-to-one. An entity in A is associated with at most one entity in B, and an entity in B is associated with at most one entity in A
One-to-many. An entity in A is associated with any number (zero or more) of entities in B. An entity in B, however, can be associated with at most one entity in A
 Many-to-one. An entity in A is associated with at most one entity in B. An entity in B, however, can be associated with any number (zero or more) of entities in A.
 Many-to-many.An entity in A is associated with any number (zero or more) of entities in B, and an entity in B is associated with any number (zero or more) of entities in A. 
The basic data types supported by SQL are:
 char(n): A fixed-length character string with user-specified length n.The full form, character, can be used instead. 
 varchar(n): A variable-length character string with user-specified maximum length n. The full form, character varying, is equivalent.
 int: An integer  (a finite subset of the integers that is machine dependent).The full form, integer, is equivalent.
 smallint: A small integer(a machine-dependent subset of the integer type).
 numeric(p,d): A fixed-point number with user-specified precision.The number consists of p digits (plus a sign), and d of the p digits are to the right of the decimal point. Thus, numeric(3,1) allows 44.5 to be stored exactly, but neither 444.5 or 0 .32 can be stored exactly in a field of this type.   
real, double precision: Floating-point and double-precision floating-point numbers with machine-dependent precision. 
 float(n): A floating-point number, with precision of at least n digits.
	 
Functions of a DBA include
Schema definition.The DBA creates the original database schema by executing a set of data definition statements in the DDL. 
 Storage structure and access-method definition.
Schema and physical-organization modification.The DBA carries out changes to the schema and physical organization to reflect the changing needs of the organization, or to alter the physical organization to improve performance.
 Granting of authorization for data access. By granting different types of authorization, the database administrator can regulate which parts of the database various users can access. The authorization information is kept in a special system structure that the database system consults when ever someone attempts to access the data in the system.
Routine maintenance. Examples of the database administrator’s routine maintenance activities are:

 Periodically backing up the database, either onto tapes or onto remote servers, to prevent loss of data in case of disasters such as flooding.
 Ensuring that enough free disk space is available for normal operations, and upgrading disk space as required.
 Monitoring jobs running on the database and ensuring that performance is not degraded by very expensive tasks submitted by some users.

 Periodically backing up the database, either onto tapes or onto remote servers, to prevent loss of data in case of disasters such as flooding.
 Ensuring that enough free disk space is available for normal operations, and upgrading disk space as required.
 Monitoring jobs running on the database and ensuring that performance is not degraded by very expensive tasks submitted by some users.
The immediate database modification technique allows database modification to be output to the database while the transaction is still in the active state. The data modification written by active transactions are called “uncommitted modification”.
If the system crash or transaction aborts, then the old value field of the log records is used to restore the modified data items to the value they had prior to the start of the transaction. This restoration is accomplished through the undo operation. In order to understand undo operations, let us consider the format of log record.
 
<Ti, Xj, V_old, V_new>
Here, Ti is transaction identifier, Xj is the data item, V_old is the old value of data item and V_new is the modified or new value of the data item Xj.
Undo (Ti):
It restores the value of all data items updated by transaction T1 to the old values.
Before a transaction, T1 starts its execution the record <T1, start> is written to the log. During its execution, any write (x) operation by T1 is performed by writing of the appropriate new update record to the log. When T1 partially commits the record <T1, commit> is written to the log.
It ensures transaction atomicity by recording all database modifications in the log but deferring the execution of all write operations of a transaction until the transaction partially commits.
A transaction is said to be partially committed once the final action of the transaction has been executed. When a transaction has performed all the actions, then the information in the log associated with the transaction is used in executing the deferred writes. In other words, at partial commits, time logged updates are “replayed” into database item.
The recovery procedure of deferred database modification is based on Redo operation 
Redo(Ti)
It sets the value of all data items updated by transaction Ti to the new values from the log of records.
After a failure has occurred the recovery subsystem consults the log to determine which transaction need to be redone. Transaction Ti needs to be redone if an only if the log contains both the record <Ti, start> and the record  <Ti, commit>. Thus, if the system crashes after the transaction completes its execution, then the information in the log is used in restoring the system to a previous consistence state.
Log Based Recovery is used for recording database modification. In log based recovery a log file is maintained for recovery purpose.
The log file is a sequence of log records. Log Record maintains a record of all the operations (update) of the database. 
Types of log records:
<Start> Log Record:
Contain information about the start of each transaction. It has transaction identification. Transaction identifier is the unique identification of the transaction that starts
Representation:
<Ti , start>
<Update> Log Record:
It describes a single database write and has the following fields:
< Ti, Xj, V1,V2 >
Here, Ti is transaction identifier, Xj is the data item, V1 is the old value of data item and V2 is the modified or new value of the data item Xj.
<Commit> Log Record
When a transaction Ti is successfully committed or completed a <Ti, commit> log record is stored in the log file.
<Abort> Log Record
When a transaction Ti is aborted due to any reason, a <Ti, abort> log record is stored in the log file.
 
 A Stable Storage is a storage in which information is never lost. Stable storage devices are the theoretically impossible to obtain. But, we must use some technique to design a storage system in which the chances of data loss are extremely low.
Causes of Failures:
System Crashes
User Error
Carelessness
Sabotage (intentional corruption of data)
Statement Failure
Application software errors
Network Failure
Media Failure
Natural Physical Disasters 
The most important information needed for whole recovery process must be stored in stable storage.
 Data Model can be defined as an integrated collection of concepts for describing and manipulating data, relationships between data,and constraints on the data in an organization.
Different types of data models:
Object Based Data Models -Object based data models use concepts such as entities, attributes, and relationships.
Physical Data Models - Physical data models describe how data is stored in the computer.
Record Based Data Models - Record based logical models are used in describing data at the logical and view levels.
The object based and record based data models are used to describe data at the conceptual and external levels, the physical data model issued to describe data at the internal level.
 
In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. The most common requirement is to minimize the time taken to execute a program, a less common one is to minimize the amount of memory occupied. The growth of portable computers has created a market for minimizing the power consumed by a program. Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources.
 
Synthesis Phase, also known as the back-end of the compiler, the synthesis phase generates the target program with the help of intermediate source code representation and symbol table.
A compiler can have many phases and passes.

Pass: A pass refers to the traversal of a compiler through the entire program.

Pass: A pass refers to the traversal of a compiler through the entire program.

Phase: A phase of a compiler is a distinguishable stage, which takes input from the previous stage, processes and yields output that can be used as input for the next stage. A pass can have more than one phase.

Phase: A phase of a compiler is a distinguishable stage, which takes input from the previous stage, processes and yields output that can be used as input for the next stage. A pass can have more than one phase.
LOOSELY COUPLED SYSTEM
Each processor has its own memory module.
Efficient when tasks running on different processors, has minimal interaction.
It generally, do not encounter memory conflict.
Message transfer system (MTS).
Data rate is low.
Less expensive
TIGHTLY COUPLED SYSTEM
Processors have shared memory modules.
Efficient for high-speed or real-time processing.
It experiences more memory conflicts.
Interconnection networks PMIN, IOPIN, ISIN.
Data rate is high.
More expensive.
An annotated parse tree is one in which various facts about the program have been attached to parse tree nodes. For example, one might compute the set of identifiers that each subtree mentions, and attach that set to the subtree. Compilers have to store information they have collected about the program somewhere; this is a convenient place to store information which is derivable from the tree.
NFA
NFA or Non-Deterministic Finite Automaton is the one in which there exist many paths for a specific input from a current state to next state.
NFA can use Empty String transition.
NFA can be understood as multiple little machines computing at the same time.
If all of the branches of NFA dies or rejects the string, we can say that NFA rejects the string.
We do not need to specify how the NFA reacts according to some symbol.
DFA
Deterministic Finite Automaton is an FA in which there is only one path for a specific input from the current state to next state. There is a unique transition on each input symbol.
DFA cannot use Empty String transition
DFA can be understood as one machine
DFA will reject the string if it ends at other than accepting state
For Every symbol of the alphabet, there is only one state transition in DFA.
Intermediate code generator receives input from its predecessor phase, semantic analyzer, in the form of an annotated syntax tree. That syntax tree then can be converted into a linear representation, e.g., postfix notation. Intermediate code tends to be machine independent code. Therefore, code generator assumes to have an unlimited number of memory storage (register) to generate code.
A three-address code has at most three address locations to calculate the expression. A three-address code can be represented in two forms:
quadruples 
triples
Intermediate code can be represented as

High Level IR - High-level intermediate code representation is very close to the source language itself. They can be easily generated from the source code and we can easily apply code modifications to enhance performance. But for target machine optimization, it is less preferred.

High Level IR - High-level intermediate code representation is very close to the source language itself. They can be easily generated from the source code and we can easily apply code modifications to enhance performance. But for target machine optimization, it is less preferred.

Low Level IR - This one is close to the target machine, which makes it suitable for register and memory allocation, instruction set selection, etc. It is good for machine-dependent optimizations.

Low Level IR - This one is close to the target machine, which makes it suitable for register and memory allocation, instruction set selection, etc. It is good for machine-dependent optimizations.
Intermediate code can be either language specific (e.g., Byte Code for Java) or language independent (three-address code).
We need to translate the source code into intermediate code which is then translated to its target code because:
If a compiler translates the source language to its target machine language without having the option for generating an intermediate code, then for each new machine, a full native compiler is required
Intermediate code eliminates the need for a new full compiler for every unique machine by keeping the analysis portion same for all the compilers.
The second part of compiler, synthesis, is changed according to the target machine.
It becomes easier to apply the source code modifications to improve code performance by applying code optimization techniques on the intermediate code.
The problem in generating three address codes in a single pass is that we may not know the labels that control must go to at the time jump statements are generated.So to get around this problem a series of branching statements with the targets of the jumps temporarily left unspecified is generated.
Back Patching is putting the address instead of labels when the proper label is determined.
Back patching Algorithms perform three types of operations
1) makelist (i) – creates a new list containing only i, an index into the array of quadruples and returns a pointer to the list it has made.
2) Merge (i, j) – concatenates the lists pointed to by i and j, and returns a pointer to the concatenated list.
3) Backpatch (p, i) – inserts i as the target label for each of the statements on the list pointed to by p.
A symbol table, either linear or hash, provides the following operations
insert()
This operation is more frequently used by analysis phase, i.e., the first half of the compiler where tokens are identified and names are stored in the table. This operation is used to add information in the symbol table about unique names occurring in the source code.
The insert() function takes the symbol and its attributes as arguments and stores the information in the symbol table.
EXAMPLE:
int a;
insert(a, int);
 
lookup()
lookup() operation is used to search a name in the symbol table to determine:
if the symbol exists in the table.
if it is declared before it is being used.
if the name is used in the scope.
if the symbol is initialized.
if the symbol declared multiple times.
The format of lookup() function varies according to the programming language.
Basic format:
lookup(symbol)
 
Symbol table is an important data structure created and maintained by compilers in order to store information about the occurrence of various entities such as variable names, function names, objects, classes, interfaces, etc. 
A Symbol table is used for

To store the names of all entities in a structured form at one place.

To store the names of all entities in a structured form at one place.

To verify if a variable has been declared.

To verify if a variable has been declared.

To implement type checking, by verifying assignments and expressions in the source code are semantically correct.

To implement type checking, by verifying assignments and expressions in the source code are semantically correct.

To determine the scope of a name (scope resolution).

To determine the scope of a name (scope resolution).
 
Lexical Analysis
First phase of a compiler.
It is also called scanner.
Main task:
read the input characters and produce as output a sequence of tokens.
Process: Input: program as a single string of characters.
Collects characters into logical groupings and assigns internal codes to the groupings according to their structure.
Groupings: lexemes
Internal codes: tokens
Secondary tasks:
 Stripping out from the source program comments and white spaces in the form of blank, tab, and new line characters. 
Correlating error messages from the compiler with the source program. 
Inserting lexemes for user-defined names into the symbol table.
Syntax Analysis
The syntax analyzer or parser must determine the structure of the sequence of tokens provided to it by the scanner.
Check the input program to determine whether is syntactically correct
 Produce either a complete parse tree of at least trace the structure of the complete parse tree.
Error: produce a diagnostic message and recover (gets back to a normal state and continue the analysis of the input program: find as many errors as possible in one pass).
Different scheduling criteria are:
CPU utilization. We want to keep the CPU as busy as possible. Conceptually, CPU utilization can range from 0 to 100 percent. In a real system, it should range from 40 percent (for a lightly loaded system) to 90 percent (for a heavily used system). 
Throughput. If the CPU is busy executing processes, then work is being done. One measure of work is the number of processes that are completed per time unit, called throughput.
Turnaround time. From the point of view of a particular process, the important criterion is how long it takes to execute that process. The interval from the time of submission of a process to the time of completion is the turnaround time. Turnaround time is the sum of the periods spent waiting to get into memory, waiting in the ready queue, executing on the CPU, and doing I/0.
Waiting time. The CPU-scheduling algorithm does not affect the amount of time during which a process executes or does I/0, it affects only the amount of time that a process spends waiting in the ready queue. Waiting time is the sum of the periods spent waiting in the ready queue. 
Response time. Time from the submission of a request until the first response is produced. This measure, called response time, is the since it takes to start responding, not the time it takes to output the response. 
 
A thread that is to be canceled is often referred to as the target thread.
Cancellation of a target thread may occur in two different ways:
Asynchronous cancellation. One thread immediately terminates the target thread. 
Deferred cancellation. The target thread periodically checks whether it should terminate, allowing it an opportunity to terminate itself in an orderly fashion. 
Benefits of multithreaded programming can be broken down into four major categories: 
Responsiveness. Multithreading an interactive application may allow a program to continue running even if part of it is blocked or is performing a lengthy operation, thereby increasing responsiveness to the user. 
Resource sharing. Processes may only share resources through techniques such as shared memory or message passing. Such techniques must be explicitly arranged by the programmer. However, threads share the memory and the resources of the process to which they belong by default. 
Economy. Allocating memory and resources for process creation is costly. Because threads share the resources of the process to which they belong, it is more economical to create and context-switch threads. Empirically gauging the difference in overhead can be difficult, but in general, it is much more time consuming to create and manage processes than threads.
Scalability. The benefits of multithreading can be greatly increased in a multiprocessor architecture, where threads may be running in parallel on different processors. A single-threaded process can only run on one processor, regardless how many are available. Multithreading on a multiCPU machine increases parallelism
Process Cooperation  is necessary because it provides
Information sharing. Since several users may be interested in the same piece of information (for instance, a shared file), we must provide an environment to allow concurrent access to such information. 
Computation speedup. If we want a particular task to run faster, we must break it into subtasks, each of which will be executing in parallel with the others. Notice that such a speedup can be achieved only if the computer has multiple processing elements (such as CPUs or I/O channels). 
Modularity. We may want to construct the system in a modular fashion, dividing the system functions into separate processes or threads, as we discussed in Chapter 2. 
Convenience. Even an individual user may work on many tasks at the same time. For instance, a user may be editing, printing, and compiling in parallel. 
For each monitor, a semaphore mutex (initialized to 1) is provided. A process must execute wait (mutex) before entering the monitor and must execute signal (mutex) after leaving the monitor. 
Since a signaling process must wait until the resumed process either leaves or waits, an additional semaphore, next, is introduced, initialized to 0. The signaling processes can use next to suspend themselves. An integer variable next_count is also provided to count the number of processes suspended on next. 
Thus, each external procedure F is replaced by :
wait(mutex); 
body of F 
if (next_count > 0)
signal(next);
else signal(mutex); 
Mutual exclusion within a monitor is ensured.
 Condition variables implementation.
For each condition x, we introduce a semaphore x_sem and an integer variable x_count, both initialized to 0. 
For x.wait():
x_count++; 
if (next_count > 0) 
signal(next);
else signal(mutex); 
wait (x_sem) ;
x_count--; 
For x.signal():
if (x_count > 0) {
next_count++;
signal(x_sem);
wait(next);
next_count--;
}
There are a few solutions to the priority-inversion problem in real-time systems. One is to turn off all system interrupts, effectively halting thread preemption in the system, while critical tasks execute. However, to make this work, you cannot implement more than two thread priorities, and critical sections where resources are locked need to be very brief and tightly controlled.
However, a more practical and less-invasive solution is to implement the priority inheritance protocol.
With priority inheritance, the system code that implements resource locking checks to see if a lower priority thread already owns a lock on the associated resource when a thread attempts to lock it. If one does, that owning thread's priority is temporarily increased to match that of the higher priority thread attempting to acquire the lock. As a result, the lock owner (once blocked at a lower priority) will execute, release the lock, and then be restored to its original priority level.
The priority-based model of execution states that a task can only be preempted by another task of higher priority. However, scenarios can arise where a lower priority task may indirectly preempt a higher priority task, in a sense inverting the priorities of the associated tasks, and violating the priority-based ordering of execution. This is called "priority inversion", and usually occurs when resource sharing is involved.
I/O-bound programs have the property of performing only a small amount of computation before performing I/O. Such programs typically do not use up their entire CPU quantum.
CPU-bound programs, on the other hand, use their entire quantum without performing any blocking I/O operations. Consequently, one could make better use of the computer’s resources by giving higher priority to I/O-bound programs and allow them to execute ahead of the CPU-bound programs.
Processor affinity means you can specify which processor(s) a given process or thread should run on.
AFFINITY LEVELS
There are three levels of affinity in the RTSS subsystem:
Subsystem affinity - Subsystem affinity refers to the set of processors you have dedicated to RTSS.
Process affinity - Process affinity refers to the processors that the threads of a given process may run on. If you don't specify a processor for a process to run on, its main thread will run it on the lowest-numbered RTSS processor available in the system. The set of processors that a process's threads can run on must be a subset of the set of processors available to the RTSS subsystem.
Thread affinity - Thread affinity determines the processors that an individual thread can run on. By default, a thread will run on the lowest-numbered  RTSS processor available for the process to run on. The set of processors a thread can run on must be a subset of the set of processors its process can run on.
Spinlocks are not appropriate for single-processor systems because the condition that would break a process out of the spinlock can be obtained only by executing a different process. If the process is not relinquishing the processor, other processes do not get the opportunity to set the program condition required for the first process to make progress. In a multiprocessor system, other processes execute on other processors and thereby modify the program state in order to release the first process from the spinlock.
Long-Term Scheduler
A long-term scheduler determines which programs are admitted to the system for processing. It selects processes from the queue and loads them into memory for execution. Process loads into the memory for CPU scheduling.The primary objective of the job scheduler is to provide a balanced mix of jobs, such as I/O bound and processor bound. It also controls the degree of multiprogramming.It is also called a job scheduler
Short-Term Scheduler
Its main objective is to increase system performance in accordance with the chosen set of criteria. It is the change of ready state to running state of the process. CPU scheduler selects a process among the processes that are ready to execute and allocates CPU to one of them.Short-term schedulers, also known as dispatchers, make the decision of which process to execute next. Short-term schedulers are faster than long-term schedulers.It is also called as CPU scheduler.
Medium-Term Scheduler
It removes the processes from the memory. It reduces the degree of multiprogramming. The medium-term scheduler is in-charge of handling the swapped out-processes.Medium-term scheduling is a part of swapping
A trap is an exception in a user process. It's caused by division by zero or invalid memory access. It's also the usual way to invoke a kernel routine (a system call) because those run with a higher priority than user code. Handling is synchronous (so the user code is suspended and continues afterwards). In a sense they are "active" - most of the time, the code expects the trap to happen and relies on this fact.
An interrupt is something generated by the hardware (devices like the hard disk, graphics card, I/O ports, etc). These are asynchronous (i.e. they don't happen at predictable places in the user code) or "passive" since the interrupt handler has to wait for them to happen eventually.
Single Inheritance
Derived class inherits a single base class.
Class derived_class : access_specifier base class
Derived class access the features of single base class
Public, Private, Protected
Require small amount of run time over head
Multiple Inheritance
Derived class inherits two or more than two base class.
Class derived _class: access_specifier base_class1, access_specifier base_class2, ....
Derived class access the combined features of inherited base classes
Public, Private, Protected
Require additional runtime overhead as compared to single inheritance
If limited to single inheritance, the result is a specialization hierarchy and has a tree topology. Otherwise, in general, it forms a specialization lattice with DAG topology. An entity type with more than one superclass is called a shared subclass. A shared subclass inherits attributes from its superclasses only once, just like in most OO languages.
A category T is a class that is a subset of the union of n defining superclasses D1, D2, ..., Dn,n > 1 and is formally specified as follows:
T ⊆ (D1 ∪ D2 ...∪ Dn) 
Specialization Hierarchy – has the constraint that every subclass participates as a subclass in only one class/subclass relationship, i.e. that each subclass has only one parent. This results in a tree structure.
Specialization Lattice – has the constraint that a subclass can be a subclass of more than one class/subclass relationship.  
In a lattice or hierarchy, the subclass inherits the attributes not only of the direct superclass, but also all of the predecessor super classes all the way to the root.
The subclass namely called child class is that class which extends another class so that it inherits both protected and public members from that class.
A subclass is needed in data modeling because it is an easy way to define inheritance relationship between two classes. The relationship between two classes w.r.t data helps to design the structure of data.
A tuple relational calculus expression may generate an infinite expression.
We need to restrict the relational calculus a bit.
The domain of a formula P, denoted dom(P), is the set of all values referenced in P.
These include values mentioned in P as well as values that appear in a tuple of a relation mentioned in P.

So, the domain of P is the set of all values explicitly appearing in P or that appear in relations mentioned is P.

So, the domain of P is the set of all values explicitly appearing in P or that appear in relations mentioned is P.
We may say an expression { t | P} is safe if all values that appear in the result are values from dom().
A safe expression yields a finite number of tuples as its result. Otherwise, it is called unsafe
Relational calculus is a non procedural query language. It uses mathematical predicate calculus instead of algebra. It provides the description about the query to get the result where as relational algebra gives the method to get the result. It informs the system what to do with the relation, but does not inform how to perform it.
A tuple relational calculus is a non procedural query language which specifies to select the tuples in a relation. It can select the tuples with range of values or tuples for certain attribute values etc. The resulting relation can have one or more tuples.
{t | P (t)}   or {t | condition (t)}
Domain relational calculus uses list of attribute to be selected from the relation based on the condition. It is same as TRC but differs by selecting the attributes rather than selecting whole tuples.
{<EMP_ID, EMP_NAME> | <EMP_ID, EMP_NAME> ? EMPLOYEE Λ DEPT_ID = 10}  
 The two-tier architecture is like client server application. The direct communication takes place between client and server. There is no intermediate between client and server. Because of tight coupling, a 2 tiered application will run faster.
Advantages:

Easy to maintain and modification is bit easy
Communication is faster

Easy to maintain and modification is bit easy
Communication is faster
Disadvantages:

In two tier architecture application performance will degrade upon increasing the users.
Cost-ineffective

In two tier architecture application performance will degrade upon increasing the users.
Cost-ineffective
Three-tier architecture typically comprises of
1) Client layer
2) Business Layer
3) Data layer
Advantages

High performance, lightweight persistent objects
Scalability – Each tier can scale horizontally
Performance – Because the Presentation tier can cache requests, network utilization is minimized, and the load is reduced on the Application and Data tiers.
High degree of flexibility in deployment platform and configuration
Better Re-use
Improve Data Integrity
Improved Security – Client is not direct access to database.
Easy to maintain and modification is bit easy, won’t affect other modules
In three tier architecture application performance is good.

High performance, lightweight persistent objects
Scalability – Each tier can scale horizontally
Performance – Because the Presentation tier can cache requests, network utilization is minimized, and the load is reduced on the Application and Data tiers.
High degree of flexibility in deployment platform and configuration
Better Re-use
Improve Data Integrity
Improved Security – Client is not direct access to database.
Easy to maintain and modification is bit easy, won’t affect other modules
In three tier architecture application performance is good.
Disadvantages

Increase Complexity/Effort

Increase Complexity/Effort
The schema is sometimes called the intention, and a database state an extension of the schema.
When we define a new database, we specify its database schema only to the DBMS. At this point, the corresponding database state is the empty state with no data. We get the initial state of the database when the database is first populated or loaded with the initial data. From then on, every time an update operation is applied to the database, we get another database state. At any point in time, the database has a current state. The DBMS is partly responsible for ensuring that every state of the database is a valid state-that is, a state that satisfies the structure and constraints specified in the schema. The DBMS stores the descriptions of the schema constructs and constraints-also called the meta-data-in the DBMS catalog so that DBMS software can refer to the schema whenever it needs to.
Redundancy is the state of being not or no longer needed or useful.In the traditional approach, uncontrolled redundancy in storing the same data/information many times in the database leads to several problems. This leads to Duplication of effort, Wastage of storage space and inconsistent data.
A controlled redundancy is a necessary technique to use redundant fields in a database. This speed ups the database access and also improves the performance of queries. Usually, the DBMS ensures the allocation of the data in the records. It should have the capability to control this redundancy in order to prohibit inconsistencies among the files.
 
Updating statistics ensures that queries compile with up-to-date statistics. However, updating statistics causes queries to recompile. We recommend not updating statistics too often because there is a performance tradeoff between improving query plans and the time it takes to recompile queries. The specific tradeoffs depend on your application. UPDATE STATISTICS can use tempdb to sort the sample of rows for building statistics.
 
A test case may be defined as a set of instructions for getting an error in the system by causing a failure. Testing software is not so much expensive in the comparison of software testing. Many kinds of aspects are to be kept in mind when test cases are selected.

The aim of the test case should be getting a program which has no errors if any error is found in the program, it is solved it quickly.

The aim of the test case should be getting a program which has no errors if any error is found in the program, it is solved it quickly.

The selected test case should contain all inputs to the program.

The selected test case should contain all inputs to the program.

A specified area should be present for the valuation of a test case.

A specified area should be present for the valuation of a test case.

A test case should be plan quickly as possible in the development process.

A test case should be plan quickly as possible in the development process.

A good testing should have following qualities:


correctness


Reliability


Usability


Efficiency


Integrity


Flexibility


Structure



A good testing should have following qualities:


correctness


Reliability


Usability


Efficiency


Integrity


Flexibility


Structure



correctness

correctness

Reliability

Reliability

Usability

Usability

Efficiency

Efficiency

Integrity

Integrity

Flexibility

Flexibility

Structure

Structure
Alpha testing
Alpha testing may be defined as a system testing which is done by the customer at the place where the developer has developed the system.
Alpha testing takes place once development is complete.
Alpha testing continues until customer agrees that system implementation is as per his/her expectation.
Alpha testing results in minor design changes.
Alpha testing is done in a controlled manner because the software is tested in developer's area.
Beta testing
Beta testing may be defined as system testing which is done by the customer on customer's own sites.
The application is tested in Beta Testing after development and testing is completed.
The problems faced by the customer are reported and software is re-released after beta testing for next beta test cycle.
To get problems and defects before the final release of the product, beta testing is very helpful.
Beta testing is done in normal environment and developers are not present during beta testing.
 
It is a measure to assess how practical and beneficial the software project development will be for an organization. The software analyzer conducts a thorough study to understand economic, technical and operational feasibility of the project.

Economic - Resource transportation, cost for training, cost of additional utilities and tools and overall estimation of costs and benefits of the project.

Economic - Resource transportation, cost for training, cost of additional utilities and tools and overall estimation of costs and benefits of the project.

Technical - Is it possible to develop this system? Assessing suitability of machine(s) and operating system(s) on which software will execute, existing developers’ knowledge and skills, training, utilities or tools for project.

Technical - Is it possible to develop this system? Assessing suitability of machine(s) and operating system(s) on which software will execute, existing developers’ knowledge and skills, training, utilities or tools for project.

Operational - Can the organization adjust smoothly to the changes done as per the demand of project? Is the problem worth solving?

Operational - Can the organization adjust smoothly to the changes done as per the demand of project? Is the problem worth solving?
Software scope is a well-defined boundary, which encompasses all the activities that are done to develop and deliver the software product.
The software scope clearly defines all functionalities and artifacts to be delivered as a part of the software. The scope identifies what the product will do and what it will not do, what the end product will contain and what it will not contain.
SDLC Models are adopted as per requirements of development process. It may very software-to-software to ensuring which model is suitable.
We can select the best SDLC model if following answers are satisfied -
Is SDLC suitable for selected technology to implement the software ?
Is SDLC appropriate for client’s requirements and priorities ?
Is SDLC model suitable for size and complexity of the software ?
Is the SDLC model suitable for the type of projects and engineering we do?
Is the SDLC appropriate for the geographically co-located or dispersed developers?
Nested loop (loop over loop)
An outer loop within an inner loop is formed consisting of fewer entries and then for individual entry, inner loop is individually processed.
E.g.
Select col1.*, col2.* from coll, col2 where coll.col1=col2.col2;
It’s processing takes place in this way:
For i in (select * from col1) loop
For j in (select * from col2 where col2=i.col1) loop
Results are displayed;
End of the loop;
End of the loop;
The Steps of nested loop are:
Identify outer (driving) table
Assign inner (driven) table to outer table.
For every row of outer table, access the rows of inner table.
Nested Loops is executed from the inner to the outer as:
outer_loop
inner_loop
Hash join
While joining large tables, the use of Hash Join is preferred.
Algorithm of Hash Join is divided into:
Build: It is a hash table having in-memory which is present on the smaller table.
Probe: this hash value of the hash table is applicable for each second row element.
Sort merge join
Two independent sources of data are joined in sort merge join. They performance is better as compared to nested loop when the data volume is big enough but it is not good as hash joins generally.
The full operation can be divided into parts of two:
Sort join operation :
Get first row R1 from input1
Get first row R2 from input2.
Merge join operation:
‘while’ is not present at either loop’s end.
if R1 joins with R2
next row is got R2 from the input 2
return (R1, R2)
else if R1 < style=””> next row is got from R1 from input 1
else
next row is got from R2 from input 2
end of the loop
The disadvantages of query are:
No indexes
Stored procedures are excessively compiled.
Triggers and procedures are without SET NOCOUNT ON.
Complicated joins making up inadequately written query.
Cursors and temporary tables showcase a bad presentation.
Storage and access of data from the central location in order to take some strategic decision is called Data Warehousing. Enterprise management is used for managing the information whose framework is known as Data Warehousing.
An overview of data warehouse:
Restrictions that are applied are:
Only the current database can have views.
You are not liable to change any computed value in any particular view.
Integrity constants decide the functionality of INSERT and DELETE.
Full-text index definitions cannot be applied.
Temporary views cannot be created.
Temporary tables cannot contain views.
No association with DEFAULT definitions.
Triggers such as INSTEAD OF is associated with views.
COALESCE function is used to return the value which is set to be not null in the list. If all values in the list are null, then the coalesce function will return NULL.
Coalesce(value1, value2,value3,...)
RAW datatype is used to store values in binary data format. The maximum size for a raw in a table in 32767 bytes.
Varchar can store upto 2000 bytes and varchar2 can store upto 4000 bytes. Varchar will occupy space for NULL values and Varchar2 will not occupy any space. Both are differed with respect to space.
SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). Its purpose is to ease the implementation of tasks for the DBA, with its full- function scheduling engine, which allows you to schedule your own jobs and scripts.
Subquery – The inner query is executed only once. The inner query will get executed first and the output of the inner query used by the outer query. The inner query is not dependent on outer query.
Correlated subquery: – The outer query will get executed first and for every row of outer query, inner query will get executed. So the inner query will get executed as many times as number of rows in the result of the outer query. The outer query output can use the inner query output for comparison. This means inner query and outer query dependent on each other
A CTE can be used:
• For recursion
• Substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.
• Reference the resulting non-large table multiple times in the same statement.
No, we don’t have UPDATED magic table.
The ‘magic tables’ are the INSERTED and DELETED tables, as well as the update() and columns_updated() functions, and are used to determine the changes resulting from DML statements.
• For an INSERT statement, the INSERTED table will contain the inserted rows.
• For an UPDATE statement, the INSERTED table will contain the rows after an update, and the DELETED table will contain the rows before an update.
• For a DELETE statement, the DELETED table will contain the rows to be deleted.
Both CTEs and Sub Queries have pretty much the same performance and function.
CTE’s have an advantage over using a subquery in that you can use recursion in a CTE.
The biggest advantage of using CTE is readability. CTEs can be referenced multiple times in the same statement where as sub query cannot.
select * into <new table> from <existing table> where 1=2 
select top 0 * into <new table> from <existing table>
SELECT column FROM table ORDER BY RAND() LIMIT 1;
select distinct hiredate from emp a where &n =  (select count(distinct sal) from emp b where a.sal >= b.sal);
select * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);
select * from emp where rownum <= &n;
1.Using Filter Index. Filtered index is used to Index a portion of rows in a table. While creating an index, we can specify conditional statements. The below SQL Query will create a Unique Index on the rows having non null values:
CREATE UNIQUE INDEX IX_ClientMaster_ClientCode ON ClientMaster(ClienCode)
WHERE ClientCode IS NOT NULL
2.Create a view having the unique fields and create a Unique Clustered Index on it:
Create View vClientMaster_forIndex
With SchemaBinding
As
Select ClientCode Fromdbo.ClientMaster Where ClientCode IS NOT NULL;
Go
CREATE Unique Clustered Index UK_vClientMaster_ForIndex
on vClientMaster_forIndex(ClientCode)
INSERT INTO table DEFAULT VALUES;

The only difference between the RANK() and DENSE_RANK() functions is in cases where there is a “tie”; i.e., in cases where multiple values in a set have the same ranking. In such cases, RANK() will assign non-consecutive “ranks” to the values in the set (resulting in gaps between the integer ranking values when there is a tie), whereas DENSE_RANK() will assign consecutive ranks to the values in the set (so there will be no gaps between the integer ranking values in the case of a tie).
For example, consider the set {25, 25, 50, 75, 75, 100. For such a set, RANK() will return {1, 1, 3, 4, 4, 6} (note that the values 2 and 5 are skipped), whereas DENSE_RANK()​​​​​​​ will return {1, 1, 2, 3, 3, 4}.
Both the NVL(exp1, exp2) and NVL2(exp1, exp2, exp3)  functions check the value exp1 to see if it is null.
With the NVL(exp1, exp2) function, if exp1 is not null, then the value of exp1 is returned; otherwise, the value of exp2 is returned, but case to the same data type as that of exp1.
With the NVL2(exp1, exp2, exp3)  function, if exp1 is not null, then exp2 is returned; otherwise, the value of exp3 is returned.
To select all the even number records from a table:
Select * from table where id % 2 = 0 

To select all the odd number records from a table:
Select * from table where id % 2 != 0
An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL server’s query optimizer for a stored procedure or ad hoc query. Execution plans are very useful for helping a developer understand and analyze the performance characteristics of a query or stored procedure since the plan is used to execute the query or stored procedure.
SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X

Servletrunner is a small utility that runs servlets. It is included in the JSDK 2.0, while the JSDK 2.1 includes an HTTP server for this purpose. 
The servletrunner is a small, multithreaded process that handles requests for servlets. Because servletrunner is multithreaded, it can be used to run multiple servlets simultaneously or to test one servlet that calls other servlets to satisfy client requests.
The rmiregistry command creates and starts a remote object registry on the specified port on the current host. If port is omitted, the registry is started on port 1099. The rmiregistry command produces no output and is typically run in the background. 
EXAMPLE:
 
rmiregistry &
A remote object registry is a bootstrap naming service that is used by RMI servers on the same host to bind remote objects to names. Clients on local and remote hosts can then look up remote objects and make remote method invocations.
The registry is typically used to locate the first remote object on which an application needs to invoke methods. That object, in turn, will provide application-specific support for finding other objects.
 A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible for carrying out the method call on the remote object. In RMI, a stub for a remote object implements the same set of remote interfaces that a remote object implements.
When a stub's method is invoked, it does the following:
initiates a connection with the remote JVM containing the remote object,
marshals (writes and transmits) the parameters to the remote JVM,
waits for the result of the method invocation,
unmarshals (reads) the return value or exception returned, and
returns the value to the caller.
The skeleton is responsible for dispatching the call to the actual remote object implementation
When a skeleton receives an incoming method invocation it does the following:
unmarshals (reads) the parameters for the remote method,
invokes the method on the actual remote object implementation, and
marshals (writes and transmits) the result (return value or exception) to the caller.
CHECKBOX
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
EXAMPLE:
import java.awt.*;  
public class CheckboxExample  
{  
     CheckboxExample(){  
       Frame f= new Frame("Checkbox Example");  
        Checkbox checkbox1 = new Checkbox("C++");  
        checkbox1.setBounds(100,100, 50,50);  
        Checkbox checkbox2 = new Checkbox("Java", true);  
        checkbox2.setBounds(100,150, 50,50);  
        f.add(checkbox1);  
        f.add(checkbox2);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);  
     }  
public static void main(String args[])  
{  
    new CheckboxExample();  
}  
}  
OUTPUT:

CHECKBOX GROUP
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one check box button is allowed to be in "on" state and remaining check box button in "off" state. It inherits the object class.
EXAMPLE:
import java.awt.*;    
public class CheckboxGroupExample    
{    
       CheckboxGroupExample(){    
       Frame f= new Frame("CheckboxGroup Example");    
        CheckboxGroup cbg = new CheckboxGroup();  
        Checkbox checkBox1 = new Checkbox("C++", cbg, false);    
        checkBox1.setBounds(100,100, 50,50);    
        Checkbox checkBox2 = new Checkbox("Java", cbg, true);    
        checkBox2.setBounds(100,150, 50,50);    
        f.add(checkBox1);    
        f.add(checkBox2);    
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
public static void main(String args[])    
{    
    new CheckboxGroupExample();    
}    
}  
OUTPUT:
FileInputStream is used for reading streams of raw bytes of data, like raw images. FileReaders, on the other hand, are used for reading streams of characters
The difference between FileInputStream and FileReader is, FileInputStream reads the file byte by byte and FileReader reads the file character by character.
So when you are trying to read the file which contains the character "Č", in FileInputStream will give the result as,196 140 because the ASCII value of Č is 268.
In FileReader will give the result as 268 which is the ASCII value of the char Č.
Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing and waiting for another thread with duties that are understood to have time requirements
EXAMPLE:
try        
{
    Thread.sleep(1000);
} 
catch(InterruptedException ex) 
{
    Thread.currentThread().interrupt();
}
Here, the program will be paused for 1000 miliseconds.
The date class is deprecated because of handling internationalization date and time. It allows date object to be accessed in a system independent manner.
The calendar class should be used instead of the date class.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1988);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date dateRepresentation = cal.getTime();
 
The current length of a StringBuffer can be found via the method. The total allocated capacity can be found through the capacity() method.
int capacity() Returns the current capacity.
int length() Returns the length (character count).
EXAMPLE:
public class Main {
  public static void main(String[] argv) {
    StringBuffer sb = new StringBuffer();
    sb.append("abcdef.com");
    System.out.println(sb.length());

    System.out.println(sb.capacity());
  }
}
 OUTPUT:
10
16
setChartAt()
The java.lang.StringBuffer.setCharAt() method sets the character at the specified index to ch. This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.
insert()
This method inserts the data into a substring of this StringBuffer. We should specify the offset value (integer type) of the buffer, at which we need to insert the data. Using this method, data of various types like integer, character, string etc. can be inserted.
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.
 
The println("...") method prints the string "..." and moves the cursor to a new line. The print("...") method instead prints just the string "...", but does not move the cursor to a new line. Hence, subsequent printing instructions will print on the same line.
Example
print
for(int i = 0; i < 5; i++)
System.out.print(" " + i);
OUTPUT:
0 1 2 3 4
println
for(int i = 0; i < 5; i++)
System.out.println(" " + i);
OUTPUT:
0
1
2
3
4
 
A derived data type is a complex classification that identifies one or various data types and is made up of simpler data types called primitive data types. Derived data types have advanced properties and use far beyond those of the basic primitive data types that operate as their essential building blocks.
In a Java program, all characters are grouped into symbols called tokens.
A token is the smallest element of a program that is meaningful to the compiler.
EXAMPLE:
Public class Hello

{

Public static void main(String args[])

{

System.out.println(“welcome in Java”);   //print welcome in java

}

}
In above Example, the source code contains tokens such as public, class, Hello, {, public, static, void, main, (, String, [], args, {, System, out, println, (, “welcome in Java”, }, }.
The resulting tokens are compiled into Java bytecodes that are capable of being run from within an interpreted Java environment. Tokens are useful for the compiler to detect errors. When tokens are not arranged in a particular sequence, the compiler generates an error message.
Bytecode is computer object code that is processed by a program, usually referred to as a virtual machine, rather than by the "real" computer machine, the hardware processor.
Rather than being interpreted one instruction at a time, Java bytecode can be recompiled at each particular system platform by a just-in-time compiler. Usually, this will enable the Java program to run faster. In Java, bytecode is contained in a binary file with a .CLASS suffix.
It is used to create an instance of driver and register it with the DriverManager. Once you have loaded a driver, it is available for making a connection with DBMS. 
A Statement object is used to represent SQL statement such DML statement or DDL statement. You simply create a  Statement object and then execute it, supplying the appropriate execute() method with SQL statement you want to send.
Type 4 is the fastest JDBC driver. Type 1 and 3 drivers will be slower than Type 2 drivers(the database calls are made at least three translations in contrast to two). Type 4 drivers requires one translation.
The Java URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL.
The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed.
EXAMPLE:
import java.io.*;  
import java.net.*;  
public class URLConnectionExample {  
public static void main(String[] args){  
try{  
URL url=new URL("http://www.geeksforgeeks.org");  
URLConnection urlcon=url.openConnection();  
InputStream stream=urlcon.getInputStream();  
int i;  
while((i=stream.read())!=-1){  
System.out.print((char)i);  
}  
}catch(Exception e){System.out.println(e);}  
}  
}  
 
JTree is a Swing component with which we can display hierarchical data. JTree is quite a complex component. A JTree has a 'root node' which is the top-most parent for all nodes in the tree. A node is an item in a tree. A node can have many children nodes. These children nodes themselves can have further children nodes. If a node doesn't have any children node, it is called a leaf node.
The leaf node is displayed with a different visual indicator. The nodes with children are displayed with a different visual indicator along with a visual 'handle' which can be used to expand or collapse that node. Expanding a node displays the children and collapsing hides them. 
package net.codejava.swing;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample extends JFrame
{
    private JTree tree;
    public TreeExample()
    {
        //create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
        //create the child nodes
        DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
        DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits");
        //add the child nodes to the root node
        root.add(vegetableNode);
        root.add(fruitNode);
         
        //create the tree by passing in the root node
        tree = new JTree(root);
        add(tree);
         
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("JTree Example");       
        this.pack();
        this.setVisible(true);
    }
     
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TreeExample();
            }
        });
    }       
}
OUTPUT WITH TWO CHILDREN:
A JSplitPane has a splitter to split two components. The splitter bar can be displayed horizontally or vertically.
The JSplitPane class provides many constructors. we can create it using its default constructor and add two components using its setTopComponent(Component c), setBottomComponent(Component c),setLeftComponent(Component c), setRightComponent(Component c).
JSplitPane can redraw components in a continuous or non-continuous way when we change the position of the splitter bar.
The JProgressBar class is used to display the progress of the task. It inherits JComponent class.
EXAMPLE:
import javax.swing.*;    
public class ProgressBarExample extends JFrame
{    
    JProgressBar jb;    
    int i=0,num=0;     
    ProgressBarExample()
    {    
        jb=new JProgressBar(0,2000);    
        jb.setBounds(40,40,160,30);         
        jb.setValue(0);    
        jb.setStringPainted(true);    
        add(jb);    
        setSize(250,150);    
        setLayout(null);    
    }    
    public void iterate()
    {    
        while(i<=2000)
        {    
            jb.setValue(i);    
            i=i+20;    
            try{Thread.sleep(150);}catch(Exception e){}    
        }    
    }    
    public static void main(String[] args) 
    {    
        ProgressBarExample m=new ProgressBarExample();    
        m.setVisible(true);    
        m.iterate();    
    }    
}    
OUTPUT:
The JTabbedPane class is used to switch between a group of components by clicking on a tab with a given title or icon. It inherits JComponent class.
EXAMPLE:
import javax.swing.*;  
public class TabbedPaneExample {  
JFrame f;  
TabbedPaneExample(){  
    f=new JFrame();  
    JTextArea ta=new JTextArea(200,200);  
    JPanel p1=new JPanel();  
    p1.add(ta);  
    JPanel p2=new JPanel();  
    JPanel p3=new JPanel();  
    JTabbedPane tp=new JTabbedPane();  
    tp.setBounds(50,50,200,200);  
    tp.add("main",p1);  
    tp.add("visit",p2);  
    tp.add("help",p3);    
    f.add(tp);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new TabbedPaneExample();  
}}  
OUTPUT:
javax.swing.filechooser.FileFilter is used to restrict the files that are shown in a JFileChooser By default, a file chooser shows all user files and directories in a file chooser dialog, with the exception of "hidden" files in Unix (those starting with a '.'). You may restrict the list that is shown by setting the file filter for a file chooser dialog.
The Java JSlider class is used to create the slider. By using JSlider, a user can select a value from a specific range.
import javax.swing.*;  
public class SliderExample1 extends JFrame
{  
    public SliderExample1() 
    {  
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  
        JPanel panel=new JPanel();  
        panel.add(slider);  
        add(panel);  
    }  
  
    public static void main(String s[]) 
    {  
        SliderExample1 frame=new SliderExample1();  
        frame.pack();  
        frame.setVisible(true);  
    }  
}  
OUTPUT:
A spinner consists of a text field on the left side and two buttons with up and down arrows on the right side. If you press the up or down button, the item that displays in the input text will change in a given ordered sequence.
Example:
package jspinnerdemo;
 
import java.awt.*;
import java.util.*;
import javax.swing.*;
 
public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("JSpinner Demo");
 
        // Spinner with number
        SpinnerNumberModel snm = new SpinnerNumberModel(
                new Integer(0),
                new Integer(0),
                new Integer(100),
                new Integer(5)
        );
        JSpinner spnNumber = new JSpinner(snm);
 
        // Spinner with Dates
        SpinnerModel snd = new SpinnerDateModel(
                new Date(),
                null,
                null,
                Calendar.DAY_OF_MONTH
        );
        JSpinner spnDate = new JSpinner(snd);
 
        // Spinner with List
        String[] colors = {"Red","Green","Blue"};
        SpinnerModel snl = new SpinnerListModel(colors);
        JSpinner spnList = new JSpinner(snl);
 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 100);
 
        Container cont = frame.getContentPane();
 
        cont.setLayout(new FlowLayout());
        cont.add(new JLabel("Select Number:"));
        cont.add(spnNumber);
 
        cont.add(new JLabel("Select Date:"));
        cont.add(spnDate);
 
        cont.add(new JLabel("Select Color:"));
        cont.add(spnList);
 
        frame.setVisible(true);
    }
}
OUTPUT:
The java.net.Socket class represents the socket that both the client and the server use to communicate with each other.
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
The following steps occur when establishing a TCP connection between two computers using sockets −
The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.
Example:
// File Name GreetingServer.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }

   public void run() {
      while(true) {
         try {
            System.out.println("Waiting for client on port " + 
               serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            
            System.out.println("Just connected to " + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
               + "\nGoodbye!");
            server.close();
            
         }catch(SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e) {
            e.printStackTrace();
            break;
         }
      }
   }
   
   public static void main(String [] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
         t.start();
      }catch(IOException e) {
         e.printStackTrace();
      }
   }
}
Compile the client and the server and then start the server as
$ java GreetingServer 6066
Waiting for client on port 6066...
Output:
$ java GreetingClient localhost 6066 
Connecting to localhost on port 6066 
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066 
Goodbye!
There are four types of sockets.

Stream Sockets − Delivery in a networked environment is guaranteed. If you send through the stream socket three items "A, B, C", they will arrive in the same order − "A, B, C". These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do not have any boundaries.
Datagram Sockets − Delivery in a networked environment is not guaranteed. They're connectionless because you don't need to have an open connection as in Stream Sockets − you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol).
Raw Sockets − These provide users access to the underlying communication protocols, which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more cryptic facilities of an existing protocol.
Sequenced Packet Sockets − They are similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as a part of the Network Systems (NS) socket abstraction and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the Sequence Packet Protocol (SPP) or Internet Datagram Protocol (IDP) headers on a packet or a group of packets, either by writing a prototype header along with whatever data is to be sent, or by specifying a default header to be used with all outgoing data, and allows the user to receive the headers on incoming packets.

Stream Sockets − Delivery in a networked environment is guaranteed. If you send through the stream socket three items "A, B, C", they will arrive in the same order − "A, B, C". These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do not have any boundaries.
Datagram Sockets − Delivery in a networked environment is not guaranteed. They're connectionless because you don't need to have an open connection as in Stream Sockets − you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol).
Raw Sockets − These provide users access to the underlying communication protocols, which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more cryptic facilities of an existing protocol.
Sequenced Packet Sockets − They are similar to a stream socket, with the exception that record boundaries are preserved. This interface is provided only as a part of the Network Systems (NS) socket abstraction and is very important in most serious NS applications. Sequenced-packet sockets allow the user to manipulate the Sequence Packet Protocol (SPP) or Internet Datagram Protocol (IDP) headers on a packet or a group of packets, either by writing a prototype header along with whatever data is to be sent, or by specifying a default header to be used with all outgoing data, and allows the user to receive the headers on incoming packets.
A combination of an IP address and a port number is called a socket.
Sockets allow communication between two different processes on the same or different machines. 
A Unix Socket is used in a client-server application framework. A server is a process that performs some functions on request from a client. Most of the application-level protocols like FTP, SMTP, and POP3 make use of sockets to establish a connection between client and server and then for exchanging data.
Types
Stream Sockets
Datagram Sockets
Raw Sockets
Sequenced Packet Sockets
JInternalFrame differs from JFrame in that it is a lightweight component and so must be contained inside another container like JDesktopPane of JFrame of JApplet. 
JInternalFrame Example:
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.*;

public class JInternalFrameDemo extends JFrame {

	JDesktopPane jdpDesktop;
	static int openFrameCount = 0;
	public JInternalFrameDemo() {
		super("JInternalFrame Usage Demo");
		// Make the main window positioned as 50 pixels from each edge of the
		// screen.
		int inset = 50;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setBounds(inset, inset, screenSize.width - inset * 2,
				screenSize.height - inset * 2);
		// Add a Window Exit Listener
		addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		// Create and Set up the GUI.
		jdpDesktop = new JDesktopPane();
		// A specialized layered pane to be used with JInternalFrames
		createFrame(); // Create first window
		setContentPane(jdpDesktop);
		setJMenuBar(createMenuBar());
		// Make dragging faster by setting drag mode to Outline
		jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
	}
	protected JMenuBar createMenuBar() {
		JMenuBar menuBar = new JMenuBar();
		JMenu menu = new JMenu("Frame");
		menu.setMnemonic(KeyEvent.VK_N);
		JMenuItem menuItem = new JMenuItem("New IFrame");
		menuItem.setMnemonic(KeyEvent.VK_N);
		menuItem.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				createFrame();
			}
		});
		menu.add(menuItem);
		menuBar.add(menu);
		return menuBar;
	}
	protected void createFrame() {
		MyInternalFrame frame = new MyInternalFrame();
		frame.setVisible(true);
		// Every JInternalFrame must be added to content pane using JDesktopPane
		jdpDesktop.add(frame);
		try {
			frame.setSelected(true);
		} catch (java.beans.PropertyVetoException e) {
		}
	}
	public static void main(String[] args) {
		JInternalFrameDemo frame = new JInternalFrameDemo();
		frame.setVisible(true);
	}
	class MyInternalFrame extends JInternalFrame {

		static final int xPosition = 30, yPosition = 30;
		public MyInternalFrame() {
			super("IFrame #" + (++openFrameCount), true, // resizable
					true, // closable
					true, // maximizable
					true);// iconifiable
			setSize(300, 300);
			// Set the window's location.
			setLocation(xPosition * openFrameCount, yPosition
					* openFrameCount);
		}
	}
}
OUTPUT: 
JFrame Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JFrameDemo {

	public static void main(String s[]) {
		JFrame frame = new JFrame("JFrame Source Demo");
		// Add a window listner for close button
		frame.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		// This is an empty content area in the frame
		JLabel jlbempty = new JLabel("");
		jlbempty.setPreferredSize(new Dimension(175, 100));
		frame.getContentPane().add(jlbempty, BorderLayout.CENTER);
		frame.pack();
		frame.setVisible(true);
	}
}
OUTPUT:
PLAF stands for Pluggable Look And Feel,  allows a Swing application to change its entire appearance with one or two lines of code. The most common use of this feature is to give applications a choice between the native platform look-and-feel and a new platform-independent Java look-and-feel (also known as the Metal look-and-feel). 
Modal dialog boxes forces the user to acknowledge the dialog before moving before moving onto the application. Modeless dialog boxes enable the user to interact with the dialog and the application interchangeably.
A modal dialog box doesn’t allow the user to access the parent window while the dialog is open – it must be dealt with and closed before continuing. A modeless dialog can be open in the background.
Example for Model Dialog is Save, Save As Dialog in MS – Word. while it is opening you can’t do any thing in the application until you close that window. Example for Modeless Dialog is Find, Replace dialogs. You can use Find Dialog, same time you can also work in that word application.
Using the following statements we can determine the dimensions of our applet.
Dimension dim = getSize();
int appletHeight = dim.height();
int appletWidth = dim.width();
The first statement uses the getsize() method to return the size of the applet as a Dimension object. The Applet class inherits it from the Component class in the java.awt package. The next two statements extract separate width and height fields.
The paint () method supports painting via a Graphics object. This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
The repaint () method is used to cause paint () to be invoked by the AWT painting method. This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not it's size ( like changing color, animating, etc. ) then call this method.
The immediate superclass of Applet is Panel. 
Panel provides the following things:

1) Panels allow us to format the screen. Panels must have a specific layout. If a layout is not specified, the default will be a FlowLayout. 
2) FlowLayout adds components to the screen one after another from top to bottom and from left to right. Components are rearranged when the user resizes the window. FlowLayout may take no arguments.
Constructor: FlowLayout fl = new FlowLayout( );
3) BorderLayout divides the screen in nine sections based in geographic orientation such as "North", "South", "East"....etc. BorderLayout takes no arguments.
Constructor: BorderLayout bl = new BorderLayout( );
4) GridLayout divides the screen in the number of sections specified by the programmer. GridLayout takes two arguments (#rows, #cols).
Constructor: GridLayout gl = new GridLayout(rows, cols ); //rows and cols are int numbers 
We use codebase in applet whenever the applet class file is not in the same directory.
codebase = codebaseURL 
This optional attribute specifies the base URL of the applet: the directory that contains the applet's code. If this attribute is not specified, then the document's URL is used. 
HTML code:
<object type="application/x-java-applet" code="HelloWorld.class" 
        codebase="/external/examples/common/java/" width="200px" height="50px">
</object>
 
Whenever a screen needs redrawing,  the update() method is called. By default, the update() method clears the screen and then calls the paint() method, which normally contains all the drawing code.
Example
import java.awt.*; 
import java.applet.Applet; 
import java.awt.event.*; 
/*<applet code="UpdateExample.class" width="350" height="150"> </applet>*/ 
public class UpdateExample extends Applet implements MouseListener 
{ 
        private int mouseX, mouseY; 
        private boolean mouseclicked = false; 
        public void init() 
        { 
          setBackground(Color.black); 
          addMouseListener(this); 
        } 
        public void mouseClicked(MouseEvent e) 
        { 
          mouseX=e.getX(); 
          mouseY=e.getY(); 
          mouseclicked = true; 
          repaint(); 
        } 
        public void mouseEntered(MouseEvent e){}; 
        public void mousePressed(MouseEvent e){}; 
        public void mouseReleased(MouseEvent e){}; 
        public void mouseExited(MouseEvent e){}; 
        public void update(Graphics g) 
        {      
          paint(g); 
        } 
        public void paint( Graphics g) 
        { 
           String str; 
           g.setColor(Color.white); 
           if (mouseclicked) 
           { 
             str = "X="+ mouseX + "," + "Y=" + mouseY; 
             g.drawString(str,mouseX,mouseY); 
             mouseclicked = false; 
           } 
        } 
} 
 
Yes, using <paran> tag as follows,
<paran name = "param1" value = "value1">
<param name = "param2" value = "value2>
One can access these parameters inside the applet by calling getParameter() method inside the applet.
HTML File
<HTML> 
<HEAD> 
<TITLE>Java applet example - Passing applet parameters to Java applets</TITLE> 
</HEAD> 
<BODY> 
<APPLET CODE="AppletParameterTest.class" WIDTH="400" HEIGHT="50">
    <PARAM NAME="font"    VALUE="Dialog">
    <PARAM NAME="size"    VALUE="24">
    <PARAM NAME="string"  VALUE="Hello, world ... it's me.   :)">
</APPLET> 
</BODY> 
</HTML>
Applet 
import java.applet.*;
import java.awt.*;

/**
 * A Java applet parameter test class.
 * Demonstrates how to read applet parameters.
 */
public class AppletParameterTest extends Applet {

   public void paint(Graphics g) {

      String myFont   = getParameter("font");
      String myString = getParameter("string");
      int mySize      = Integer.parseInt(getParameter("size"));

      Font f = new Font(myFont, Font.BOLD, mySize);
      g.setFont(f);
      g.setColor(Color.red);
      g.drawString(myString, 20, 20);

   }
}
 
When an applet begin,
init() -> start() ->paint()

The init() and start() methods are invoked first.
That, in turn, creates a thread and starts that thread, which causes this class's run() method to be invoked.
The  paint() method is invoked by Swing independently in the GUI event handling thread if Swing detects that the applet needs to be redrawn.

The init() and start() methods are invoked first.
That, in turn, creates a thread and starts that thread, which causes this class's run() method to be invoked.
The  paint() method is invoked by Swing independently in the GUI event handling thread if Swing detects that the applet needs to be redrawn.
When an applet is terminated,
stop() -> destroy()
We don't have the concept of constructor in applets. Applets can be invoked either through browser or through Appletviewer utility provided by JDK.
Applets don't have implicit constructors but you can define explicitly, but actually no need to mention it because it is initialized using an init().
FlowLayout - Top to bottom, left to right.
BoderLayout  - At borders(North, South, East, West) and at the center of a container.
CardLayout - Elements are stacked on top of each other.
GridLayout - Elements are of equal size and are laid out using the square of grid.
GridBagLayout - Elements organized according to grid. The elements are of different sizes and may occupy more than one row or column of grid.
Double buffering is the process of use of two buffers rather than one to temporarily hold data being moved to and from I/O device.
The resulting image is smoother, less flicker and quicker than drawing on the screen. It also helps prevent bottlenecks.
AWT components depend upon native code counterparts(called peers) to handle their functionality(drawing and rendering). This extra 'baggage' makes them heavy weight components.
The Font class is used to render glyphs you characters you see on the screen.
FontMetrics class encapsulates information about a specific font on a specific graphics object.
1.The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
2.The java.io.RandomAccessFile class implements a random access file.

3.Random access file offers a seek feature that can go directly to a particular position.

4.Unlike the input and output stream classes in java.io. RandomAccessFile is used for both reading and writing files.

5. RandomAccessFile does not inherit from InputStream or OutputStream. It implements the DataInput and DataOutput interfaces.
When a task invokes yield() method, it returns to the ready state either from running, waiting or after its creation. When a task invokes sleep() method it returns to the waiting state from a running state.
Yielding
1.Yield will cause the thread to rejoin the queue.
2.When a task is invoked in yielding, it returns to the ready state.
3.It is used to get the running thread into out of runnable state with the same priority.
Sleeping
1.Sleep holds the thread's execution for the specified time.
2.When a task is invoked in sleeping, it returns to the waiting state.
3.It is used to delay the execution for a period of time.
No.
There are two ways to create a thread:
extends Thread class
implement Runnable interface
Even when implemented Runnable to create a thread,  we have to create an instance of the Thread class, pass the instance of the class implementing Runnable as the argument in Thread class's constructor.
Using extend:
public class MyThread extends Thread{
     public void run()
     {
      System.out.println("Thread started running..");
     }
     public static void main( String args[] )
     {
        MyThread mt = new  MyThread();
        mt.start();
     }
}
OUTPUT:
Thread started running..
Using Runnable:
public void run() {
        System.out.println("Thread started running..");
    }
 
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        Thread t = new Thread(mt);
        t.start();
    }
}
OUTPUT:
Thread started running..
 
Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is generally used in applications with graphical user interfaces where a new thread may be created to do some work relating to processing while the main thread keeps the interface responsive to human interaction.
Both start() and run() provide ways to create threaded programs. The start() method starts the execution of the new thread and calls run() method. the start() method returns immediately as the new thread normally continues until the run() method returns.
Here is a simple code example which prints name of Thread which executes run() method of Runnable task. Its clear that if you call start() method a new Thread executes Runnable task while if you directly call run() method task, current thread which is main in this case will execute the task.
public class StartVsRunCall{

    public static void main(String args[]) {
        
        //creating two threads for start and run method call
        Thread startThread = new Thread(new Task("start"));
        Thread runThread = new Thread(new Task("run"));
        
        startThread.start(); //calling start method of Thread - will execute in new Thread
        runThread.run();  //calling run method of Thread - will execute in current Thread

    }

    /*
     * Simple Runnable implementation
     */
    private static class Task implements Runnable{
        private String caller;
        
        public Task(String caller){
            this.caller = caller;
        }
        
        @Override
        public void run() {
            System.out.println("Caller: "+ caller + " and code on this Thread is executed by : " + Thread.currentThread().getName());
            
        }         
    } 
}



Output:
Caller: start and code on this Thread is executed by:  Thread-0
Caller: run and code on this Thread is executed by:  main
In Summary only difference between start() and run() method in Thread is that start creates new thread while run doesn't create any thread and simply execute in current thread like a normal method call.


 
java.lang.Throwable
In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw.
In overloading, the compiler picks an overloaded method. When translating the program, before the program ever runs. This method selection is known as static or early binding. However, in polymorphism, the compiler does not makes any decision when translating the method. The program has to run before any one can know what is stored in the object reference variable. Therefore, the JVM and not the compiler selects the appropriate method, This method selection is known as late binding.
Assigning an object to another object does not create a duplicate object. It simply assigns a reference of already existing object to a new object.
The clone() method when used creates a new object with separate memory space.
For example:  aObj = bObj.clone();
This statement copies on object bObj to new memory location and assign the reference of new object to aObj.
Within the inner class, the keyword this holds a reference to the current object but if inner class needs to access the current outer class object then precede the keyword this with the outerclass name.
Using this in inner class:
class Outer 
{
    private int a = 10;
    class Inner 
    {
        private int a = 20;
        public void myMethod() 
        {
            System.out.println(this.a);
        }
    }
}
OUTPUT:
20
Using this in outerclass:
class Outer
{
    private int a = 10;
    class Inner 
    {
        private int a = 20;
        public void myMethod()
        {
            System.out.println(Outer.this.a);
        }
    }
}
OUTPUT:
10
The instanceof() keyword is a two argument that tests whether the runtime type of its first argument compatible with its second argument compatible with its second argument. It performs test at compile time and runtime.
The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.
Example:
class Simple1
{  
    public static void main(String args[])
    {  
        Simple1 s = new Simple1();  
        System.out.println(s instanceof Simple1);  
    }  
} 
OUTPUT:
true
The class is instantiated and declared in the same place. The declaration and instantiation takes the form
new Xxx()
{ //body }
Here, Xxx is an interface name. An anonymous class cannot have a constructor. This is because you do not specify a name of the class, you cannot use that name to specify a constructor.
Constructing an instance of a class invokes the constructor of all the superclass along the inheritance chain. A superclasss constructor is called before the subclass's constructor. This is called constructor chaining.
package com.myjava.constructors;
 
public class MyChaining {
     
    public MyChaining(){
        System.out.println("In default constructor...");
    }
    public MyChaining(int i){
        this();
        System.out.println("In single parameter constructor...");
    }
    public MyChaining(int i, int j){
        this(j);
        System.out.println("In double parameter constructor...");
    }
     
    public static void main(String a[]){
        MyChaining ch = new MyChaining(10, 20);
    }
}
OUTPUT:
In default constructor...
In single parameter constructor...
In double parameter constructor...
this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a superclass instructor.
OR
super is used to access methods of the base class while this is used to access methods of the current class.
There are some classes that cannot be extended(i.e subclasses).

A non-public class can only be subclassed by classes in the same package as the class but not from classes in a different package.
A final class cannot be classed.
A class that has only private construction cannot b subclassed.
If the class has private members then regular inner class can access them.

A non-public class can only be subclassed by classes in the same package as the class but not from classes in a different package.
A final class cannot be classed.
A class that has only private construction cannot b subclassed.
If the class has private members then regular inner class can access them.
Yes, it is possible by using super keyword.  For example, consider the following code statement.
public void play()
{
    super.play();
    //my own play() method code
}
Thus, the first statement in the body calls inherited version of play() and then it comes back to the subclass's specific code.
The string value is represented using private array variable. The array cannot be accessed outside the String class. The String class provides many public methods( such as length(), charAt() ) to retrieve array information. If array were not private, the user would be able to change the string content by modifying the array. This would violate that String class is immutable. 
Float One = new Float(3.7);
Float Two = new Float(5.2);
Float Sum = new Float(One.floatValue() +Two.floatValue());
Here, floatValue() method is used. The Float​​​​​​ wrapper class does not support floating point arithmetic. So it is necessary to convert it to float primitive type before performing arithmetic operations.
Locale class is used to tailor a program output to the conventions of a particular geographic, political or cultural region.

An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to form information for the user.

An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to form information for the user.

Locale is a mechanism for identifying objects, not a container for the objects themselves.

Locale is a mechanism for identifying objects, not a container for the objects themselves.
A locale consists of a language and a country. Class Locale, in package java.util contains information about 140 locales.
length() method is used to get the number of elements in string buffer whereas length parameter is used only with arrays to get its length.
Here is an example for better understanding.
public class length
{
    public static void main(String args[])
    {
        String x = "test";
        int a[] = {1, 2, 3, 4};
        System.out.println(x.length());
        System.out.println(a.length);
    }
}
OUTPUT
4
4
Not directly. Although Java provides wrapper classes that wrap the primitive types in objects. These are Integers, Double, Byte, Float, Long and  Character. In addition to allowing a primitive type to be passed by reference, the wrapper classes define several methods that enable you to manipulate their values. 
Although the finalize() method approximates the function of a destructor, it is not the same.
A C++ destructor is always called just before an object goes out of scope, but you can't know when would finalize() be called for specific object.
In C++,

Every object is destroyed when it goes out of scope. Thus, if you declare a local object inside a function, when that function returns, that local object is automatically destroyed. The same goes for function parameters and for objects returned by functions.
Just before destruction, the object's destructor is called. This happens immediately, and before any other program statements will execute. Thus, a C++ destructor will always execute in a deterministic fashion. You can always know when and where a destructor will be executed.

Every object is destroyed when it goes out of scope. Thus, if you declare a local object inside a function, when that function returns, that local object is automatically destroyed. The same goes for function parameters and for objects returned by functions.
Just before destruction, the object's destructor is called. This happens immediately, and before any other program statements will execute. Thus, a C++ destructor will always execute in a deterministic fashion. You can always know when and where a destructor will be executed.
 In Java, objects are not explicitly destroyed when they go out of scope. Rather, an object is marked as unused when there are no longer any references pointing to it. Even then, the finalize() method will not be called until the garbage collector runs. Thus, you cannot know precisely when or where a call to finalize( ) will occur. Even if you execute a call to gc( ) (the garbage collector), there is no guarantee that finalize( ) will immediately be executed.
No, arithmetic operations cannot be performed on a reference variable because the reference variable is an alias of another variable. 
We use if else-if ladder when conditions controlling the selection process involves multiple variables.
For example,
if (p<0) //........
else if (q>10.7) //.........
else if (!finish) //........
This sequence cannot be re-coded with switch statement because all conditions involve different variables and different types.
Java is strongly typed language. This implies that all operations are type checked by the compiler for type compatibility. Illegal operations will not be compiled. Therefore, strong type checking present errors and enhance reliability.
Primitive types are the data types that are defined by the language itself. In contrast, reference types are types that are defined by classes in the Java API rather than by language itself.
Moreover, memory location associated with primitive type contains the actual value of the variable. In contrast, memory location associated with reference variable contains an address that indicates the memory location of the actual object.
Although Java does not have unsigned int's but one can convert an int to unsigned representation by using the following convention.
((long) i) & 0x00000000FFFFFFFFL;
Here, i is a variable of int type that you want to convert to unsigned int.
Yes. In Java, identifiers can be at maximum 65535 character length. Although there is no restriction placed in principle but Java source code is compiled into Java class files and the specification for class files does in effect, place an upper bound on the size of identifiers.
The precedence of operators refers to the order in which operators are evaluated within an expression whereas associativity refers to the order in which the consecutive operators within the same group are carried out.
Precedence rules specify the priority of operators (which operators will be evaluated first, e.g. multiplication has higher precedence than addition, PEMDAS). The associativity rules tell how the operators of the same precedence are grouped
Yes, an application can have multiple classes having main method, but while starting the application, mention the classname which is to be run i.e the classname which is to be executed. The JVM will only look for the main() method in that class which you have mentioned.
String[]  args is the only parameter in the main method. It declares a parameter named args which contains an array of objects of the class type String.In other words, if you run your program as java MyProgram one two then args will contain ["one", "two"].
select max(salary) from employees where pin < (select max(salary) from employees)

Weekly


Monthly


Overall

Error
Content Related Issue
Sofware Related Issue