Saturday, January 22, 2022

UGC-NET Computer Science December 2014 Paper 2 with Solution

Q : 1 Consider a set A = {1, 2, 3, …….., 1000}. How many members of A shall be divisible by
3 or by 5 or by both 3 and 5 ?

(A) 533
(B) 599
(C) 467
(D) 66

Answer: (C)

Explanation:

Given Set is A = {1, 2, 3, …….., 1000}.
The members of 'A' which are divisible by 3 are given by {3,6,9,12...,999} these are total 333 elements.
The members of 'A' which are divisible by 5 are given by {5,10,15,20,...,1000} these are total 200 elements.
The members of 'A' which are divisible by both 3 and 5 i.e. divisible by 15 are given by {15,30,45,...,990} these are total 66 elements.

So, we have to find How many members of A shall be divisible by
3 or by 5 or by both 3 and 5?
i.e. No. of elements divisible by 3 +  No. of elements divisible by 5 -  No. of elements divisible by 15. 
(Union operation n(X union Y)=n(X)+n(Y) - n(X intersection Y))

=> 333 + 200 - 66=533 - 66 = 467.

Hence correct option is (C).


Q : 2 A certain tree has two vertices of degree 4, one vertex of degree 3 and one vertex of
degree 2. If the other vertices have degree 1, how many vertices are there in the graph ?
(A) 5
(B) n – 3
(C) 20
(D) 11

Answer: (D)

Explanation:

We know that in a tree the total number of edges are always 1 less than total number of vertices.
Also according to handshaking theorem:
Sum of degrees of all the vertices in a graph is equal to twice the number of edges.
So, by applying these two concepts together let total number vertices be 'n'.

   => 2 * 4 + 1 * 3 + 1 * 2 + 1 * ( n - 4 ) = 2*( n - 1 )
   => 8 + 3 + 2 + n - 4 = 2n - 2
   => 13 - 4 + n = 2n - 2
   => n = 11.

Hence correct option is (D).


Q : 3 Consider the Graph shown below :

This graph is a __________.
(A) Complete Graph
(B) Bipartite Graph
(C) Hamiltonian Graph
(D) All of the above

Answer: (C)

Explanation: 

Let us examine all the options one by one.
(A) Complete Graph: It is a graph in which each vertex is connected to all the other vertices in the graph. But in the given graph there is no direct edge between (A,C), (B,D) So, it is not a complete graph. This option is wrong also option (D) becomes incorrect.

(B) Bipartite Graph: It is a graph whose vertices can be divided into two disjoint sets and (that is, and are each independent sets) such that every edge connects a vertex in to one in . Vertex set and are often denoted as partite sets. This option is also incorrect.

(C) Hamiltonian Graph: A graph is a Hamiltonian graph if it contains a Hamiltonian circuit or cycle.
Hamilton circuit, is a graph cycle (i.e., closed loop) through a graph that visits each node exactly once. The above graph has Hamiltonian circuit A->F->B->C->E->D->A. Hence it is a Hamiltonian Graph. So, option (C) is correct.


Q : 4 A computer program selects an integer in the set {k : 1 £ k £ 10,00,000} at random and
prints out the result. This process is repeated 1 million times. What is the probability that
the value k = 1 appears in the printout at least once ?
(A) 0.5
(B) 0.704
(C) 0.632121
(D) 0.68


Q : 5 If we define the functions f, g and h that map R into R by :
f(x) = x4, g(x) = x2 + 1, h(x) = x2 + 72, then the value of the composite functions ho(gof)
and (hog)of are given as
(A) x8 – 71 and x8 – 71
(B) x8 – 73 and x8 – 73
(C) x8 + 71 and x8 + 71
(D) x8 + 73 and x8 + 73

Answer: (D)

Explanation:

We have to compute ho(gof), firstly we will calculate gof which is g(x4) = + 1.
Now we will calculate ho(gof) i.e. h(√+ 1) = (√+ 1)+ 72= + 73.
So, option (D) is correct.


Q : 11 What will be the output of the following ‘C’ code ?
main ( )
{
int x = 128;
printf ("\n%d", 1 + x ++);
}

(A) 128
(B) 129
(C) 130
(D) 131

Answer: (B)

Explanation:

Firstly variable 'x' is assigned 128, then in printf("\n%d",1+x++)  here '++' is used as post increment operator this means when the expression '1+x++' is evaluated 'x++' is substituted as 128 and '1+128' becomes 129. After the printf is executed 'x' will become 129 as a result of post increment '++' operator. Hence correct option is (B).


Q : 12 What does the following expression means ?
char *(*(* a[N]) ( )) ( );

(A) a pointer to a function returning array of n pointers to function returning character pointers.
(B) a function return array of N pointers to functions returning pointers to characters
(C) an array of n pointers to function returning pointers to characters
(D) an array of n pointers to function returning pointers to functions returning pointers to characters.


Answer: (D)

Explanation:

By clearly examining the above question let us begin from the inner most parenthesis which indicates that it is an array of 'N' pointers to the function, moving one step out it shows it is again returning pointer to function and in the end it indicates the return type of function which is char pointer. So, we can say that it represents an array of n pointers to function returning pointers to functions returning pointers to characters. Hence correct option is (D).


Q : 13 Which of the following is not a member of class ?
(A) Static function
(B) Friend function
(C) Const function

(D) Virtual function

Answer: (B)

Explanation:

Let us examine all the options one by one. First option is Static function it is a function which does not belong to an object but it is shared by all the objects and can be accessed by class-name::function-name. No need to create object of the class it is a member of class. This option is incorrect.

Next option is Friend function it is a function which is defined outside the class and it is not a member of the class. It is used to access data of the other class whose friend it is declared.
So, it is the correct answer.

Next is Const function this function cannot change or modify anything it remains constant and can only be used for printing output purpose. It is also a member of class so this option is also incorrect.

Next is Virtual function this is a type of function which is generally declared to resolve the ambiguity in case of hybrid inheritance so that only a single copy of the function is inherited.
It is also a member of class hence this option is also incorrect.
We can say that friend function is not a member of class but it require an object of the class to access its data to whom it is declared as friend.

Q : 14 When an array is passed as parameter to a function, which of the following statements is correct ?
(A) The function can change values in the original array.
(B) In C, parameters are passed by value, the function cannot change the original value in the array.
(C) It results in compilation error when the function tries to access the elements in the array.
(D) Results in a run time error when the function tries to access the elements in the array.


Answer: (B)

Explanation:

Let us examining all the options.
First option is correct as by default in 'C' arrays are passed by address so it can change the values in the original array. Normal variables are passed by value in 'C'.
void change(int a[],int n);
void change(int *a,int n);

Second option is incorrect in case of arrays as we explained above.
Similarly C,D both are incorrect.


Q : 15 Which of the following differentiates between overloaded functions and overridden
functions ?

(A) Overloading is a dynamic or runtime binding and overridden is a static or compile time binding.
(B) Overloading is a static or compile time binding and overriding is dynamic or runtime binding.
(C) Redefining a function in a friend class is called overloading, while redefining a function in a derived class is called as overridden function.
(D) Redefining a function in a derived class is called function overloading, while redefining a function in a friend class is called function overriding.

Answer: (B)

Explanation:

Function overloading means having more than one same name functions but with different parameters. Return type alone is not sufficient for function overloading. It is done at compile time.

Function overriding is defined as when derived class has same name method as in base class with same signature then definition of function in derived class overrides the definition in base class.
It is done at run-time. Hence correct option is (B).


Q : 21 Convert the following infix expression into its equivalent post fix expression
(A + B^ D) / (E – F) + G ?

(A) ABD^ + EF – / G+

(B) ABD + ^EF – / G+
(C) ABD + ^EF / – G+

(D) ABD^ + EF / – G+

Answer: (A)

Explanation:

To convert this expression into post fix expression firstly we should consider the priority of all the operators in the expression. The operator with highest priority will be considered first.
The expression part which is converted into its post fix notation has been underlined.
Highest priority is of brackets, let us consider (A + B^ D) in this bracket further the highest priority is of '^' so it will converted first the whole expression would look like:

(A + BD^)  / (E – F) + G

=> ABD^+ / EF- + G
=>ABD^+EF-/ + G
=>ABD^+EF-/ G+

Hence Final result is ABD ^ + EF - / G +, So correct option is (A).


Q : 24 Consider an array A[20, 10], assume 4 words per memory cell and the base address of
 array A is 100. What is the address of A[11, 5] ? Assume row major storage.

(A) 560

(B) 565
(C) 570

(D) 575

Answer: (A)

Explanation:

In computers memory the array elements are always stored linearly whether they are 1-Dimensional or 2-Dimensional. Like this is an example of 2-Dimensional array stored in memory linearly:





As we can see element A11 is stored at location '0' in memory and it is known as its offset.
Step 1:
Now to calculate the offset in case of Row major order we will use the formula:
Offset = (Row No. * Total No. of Columns) + Column No.

Now to calculate the offset in case of Column major order we will use the formula:
Offset = (Column No. * Total No. of Rows) + Row No.

'Row No.' is the row number of the location whose address we need to calculate.
'Column No.' is the column number of the location whose address we need to calculate.
'Total No. of Columns' is the total number of columns in the given matrix.
'Total No. of Rows' is the total number of rows in the given matrix.

Step 2:

Multiply the offset calculated with the size of each memory word.

Step 3:

Add the Base address to calculate the effective address.

Given matrix is A[20][10], Size of memory word is 4 bytes, address of the location to find A[11][5], Base address is 100.

Step 1:
Offset = (11 * 10) + 5 = 115.
Step 2:
115 * 4 = 460.
Step 3:
100 + 460 = 560.

So, correct option is (A) 560.


Q : 25 A full binary tree with n leaves contains

(A) n nodes

(B) log2n nodes
(C) 2n –1 nodes
(D) 2n nodes

Answer : (C)

Explanation :

A full binary tree is one in which each node has exactly two children. Like on given below is a full binary tree with 15 nodes:
No. of internal nodes are given by 'No. of External or Leaf nodes - 1'.
In our question we have to find total no. of nodes in the tree. We are given that total no. of leaf nodes are 'n'. Total no. of nodes in tree = Total No. of Leaf Nodes + Total No. of Internal Nodes
=> Total no. of nodes in tree = n + n - 1 = 2n-1.
We can examine this by putting the no. leaf nodes of the above tree in given formula which is 8.
Total no. nodes in tree = 2 * 8 - 1 = 16 - 1 = 15.
Hence correct option is (C).

Q : 26 The period of a signal is 10 ms. What is its frequency in Hertz ?

(A) 10

(B) 100
(C) 1000

(D) 10000

Answer: (B)

Explanation:

We know that period and frequency are reciprocals of each other.
f = 1/T
1 sec  = 1 hertz
1 millisecond = 1000 Hz = 1 KHz
1 microsecond = 1000000 hertz = 1 MHz

In our question Period is 10 ms.
10 ms = 10 * 10-3 sec = 10-2 sec
 f = 1/10-2 = 100 Hz.

Hence correct option is (B).


Q : 28 Which of the following algorithms is not a broadcast routing algorithm ?

(A) Flooding

(B) Multidestination routing
(C) Reverse path forwarding

(D) All of the above

Answer:

Explanation:(B)

Flooding:
Flooding is a simple computer network routing algorithm in which every incoming packet is sent through every outgoing link except the one it arrived on. It is a broadcast routing algorithm, So, this option is incorrect.

Multi destination routing:
Algorithms for effectively routing messages from a source to multiple destination nodes in a store-and-forward computer network are studied. The focus is on minimizing the network cost (NC), which is the sum of weights of the links in the routing path. Several heuristic algorithms are studied for finding the NC minimum path (which is an NP-complete problem). It is not a broadcasting routing algorithm So, it is the correct option.


Reverse path forwarding:
Reverse path forwarding (RPF) is a technique used in modern routers for the purposes of ensuring loop-free forwarding of multicast packets in multicast routing and to help prevent IP address spoofing in unicast routing. In Reverse path forwarding, the decision to forward traffic is based upon source address and not on destination address as in unicast routing. It does this by utilizing either a dedicated multicast routing table or alternatively the router's unicast routing table. It is also a broadcast routing algorithm, So, this option is incorrect.


Q : 29 An analog signal has a bit rate of 6000 bps and a baud rate of 2000 baud. How many data elements are carried by each signal element ?
(A) 0.336 bits/baud
(B) 3 bits/baud
(C) 120,00,000 bits/baud
(D) None of the above

Answer: (B)

Explanation:

No. of elements carried by each signal element or baud = Bit Rate / Baud Rate

Bit Rate = 6000 bits per sec

Baud Rate = 2000 Bauds

No. of elements carried by each signal element or baud= 6000 / 2000 = 3.

So, each baud or signal carries 3 data elements.
Hence correct option is (B).


Q : 30 How many distinct stages are there in DES algorithm, which is parameterized by a
56-bit key ?
(A) 16
(B) 17
(C) 18
(D) 19

Answer:

Explanation:

Data Encryption Standard (DES): DES was designed by IBM and adopted by the U.S. government as the standard encryption method for nonmilitary and nonclassified use. The algorithm encrypts a 64-bit plain text block using a 64-bit key (56 bit key + 8 bit parity).
DES has two transposition blocks (P-boxes) and 16 complex round ciphers (they are repeated). Although the 16 iteration round ciphers are conceptually the same, each uses a different key derived from the original key.
The initial and final permutations are keyless straight permutations that are the
inverse of each other. The permutation takes a 64-bit input and permutes them according
to predefined values.
DES Function: The heart of DES is the DES function. The DES function applies a
48-bit key to the rightmost 32 bits Ri to produce a 32-bit output. This function is made
up of four operations: an XOR, an expansion permutation, a group of S-boxes, and a
straight permutation,
Hence correct option is (A).


Q : 33 In a two-pass assembler, symbol table is
(A) Generated in first pass
(B) Generated in second pass
(C) Not generated at all
(D) Generated and used only in second pass

Answer: (A)

Explanation:

Two-pass Assembler
An assembler is a translator, that translates an assembler program into a conventional machine language program. Basically, the assembler goes through the program one line at a time, and generates machine code for that instruction. Then the assembler procedes to the next instruction. In this way, the entire machine code program is created. For most instructions this process works fine, for example for instructions that only reference registers, the assembler can compute the machine code easily, since the assembler knows where the registers are.
Consider an assembler instruction like the following


          JMP  LATER
          ...
          ...
LATER:


This is known as a forward reference. If the assembler is processing the file one line at a time, then it doesn't know where LATER is when it first encounters the jump instruction. So, it doesn't know if the jump is a short jump, a near jump or a far jump. There is a large difference among these instructions. They are 2, 3, and 5 bytes long respectively. The assembler would have to guess how far away the instruction is in order to generate the correct instruction. If the assembler guesses wrong, then the addresses for all other labels later in the program woulds be wrong, and the code would have to be regenerated. Or, the assembler could always choose the worst case. But this would mean generating inefficiency in the program, since all jumps would be considered far jumps and would be 5 bytes long, where actually most jumps are short jumps, which are only 2 bytes long.So, what is to be done to allow the assembler to generate the correct instruction? Answer: scan the code twice. The first time, just count how long the machine code instructions will be, just to find out the addresses of all the labels. Also, create a table that has a list of all the addresses and where they will be in the program. This table is known as the symbol table. On the second scan, generate the machine code, and use the symbol table to determine how far away jump labels are, and to generate the most efficient instruction.
This is known as a two-pass assembler. Each pass scans the program, the first pass generates the symbol table and the second pass generates the machine code.
Hence correct option is (A).


Q : 34 Debugger is a program that
(A) allows to examine and modify the contents of registers
(B) does not allow execution of a segment of program
(C) allows to set breakpoints, execute a segment of program and display contents of register
(D) All of the above


Answer: (C)

Explanation:

Debugger: A special program used to find errors (bugs) in other programs. A debugger allows a programmer to stop a program at any point and examine and change the values of variables.
Typically, debuggers also offer more sophisticated functions such as running a program step by step (single-stepping or program animation), stopping (breaking) (pausing the program to examine the current state) at some event or specified instruction by means of a breakpoint, and tracking the values of some variables. Some debuggers have the ability to modify the state of the program while it is running, rather than merely to observe it. It may also be possible to continue execution at a different location in the program to bypass a crash or logical error.
Hence correct option is (C).

Q : 35 The following Context-Free Grammar (CFG) :

S -> aB | bA

A -> a | aS | bAA

B -> b | bS | aBB

will generate

(A) odd numbers of a’s and odd numbers of b’s
(B) even numbers of a’s and even numbers of b’s
(C) equal numbers of a’s and b’s
(D) different numbers of a’s and b’s


Answer: (C)

Explanation:

S -> aB -> ab

S -> aB -> abS -> abaB -> abab

S -> aB -> abS -> abaB -> abaaBB -> abaabb

S -> bA -> ba

S -> bA -> baS -> babA -> baba

Like this we can prove it for each rule and it will always generate equal numbers of a’s and b’s.

Hence correct option is (C).


Q : 38 Which of the following conditions does not hold good for a solution to a critical section
problem ?
(A) No assumptions may be made about speeds or the number of CPUs.
(B) No two processes may be simultaneously inside their critical sections.
(C) Processes running outside its critical section may block other processes.
(D) Processes do not wait forever to enter its critical section.


Answer: (C)

Explanation:



The Critical-Section Problem:

Consider a system consisting of n processes {P0, P1, ..., Pn−1}. Each process has a segment of code, called a critical section, in which the process may be changing common variables, updating a table, writing a file, and so on. The important feature of the system is that, when one process is executing in
its critical section, no other process is to be allowed to execute in its critical section. That is, no two processes are executing in their critical sections at the same time. The critical-section problem is to design a protocol that the processes can use to cooperate. Each process must request permission to enter its critical section. The section of code implementing this request is the entry section. The critical section may be followed by an exit section. The remaining code is the remainder section. The general structure of a typical process Pi is shown here:

while (true) {
entry section
critical section
exit section
remainder section
}
 General structure of a typical process Pi

A solution to the critical-section problem must satisfy the following three requirements:

1. Mutual exclusion: If process Pi is executing in its critical section, then no other processes can be executing in their critical sections.

2. Progress: If no process is executing in its critical section and some processes wish to enter their critical sections, then only those processes that are not executing in their remainder sections can participate in deciding which will enter its critical section next, and this selection cannot
be postponed indefinitely.

3. Bounded waiting: There exists a bound, or limit, on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted.

We assume that each process is executing at a nonzero speed. However,we can make no assumption concerning the relative speed of the 'n' processes.

Hence correct option is (C).



Q : 39 For the implementation of a paging scheme, suppose the average process size be x bytes,
the page size be y bytes, and each page entry requires z bytes. The optimum page size that
minimizes the total overhead due to the page table and the internal fragmentation loss is
given by
(A) x/2
(B) xz/2
(C) √(2xz)
(D) √(xz)/2

Answer: (C)

Explanation:


Important consideration is size of pages to use. OS often has choice in this matter---many MMUs allow various different page sizes.
  • Small size: less wasted space due to internal fragmentation; fewer unused pages in memory.
  • Large page size: more efficient disk I/O, smaller page tables
If average process segment size is x; page table entry size is z bytes; page size is y,
Average amount of internal fragmentation per segment is y/2.
Average number of pages per process segment is x/y. Each page requires 'z' bytes of page table, so each process segment requires page table size of xz/y bytes.
Total overhead per segment, therefore, due to internal fragmentation and page table entries, is
xz/y + y/2
To minimize the overhead, differentiate with respect to page size, y, and equate to 0:

-xz/y2 + 1/2 = 0
=> y = √(2xz)
So for example, if the average segment size were 256 K, and the page table entry size were 8 bytes, the optimum page size, to minimize overhead due to page table entries and internal fragmentation, would be √(2 × 256K × 8) = 2048 = 2K.
Note: that this calculation ignores the need to keep page sizes large in order to speed up paging operations; it only considers memory overheads.


Q : 40 In a demand paging memory system, page table is held in registers. The time taken to service a page fault is 8 m.sec. if an empty frame is available or if the replaced page is not modified, and it takes 20 m.secs., if the replaced page is modified. What is the average access time to service a page fault assuming that the page to be replaced is modified 70% of the time ?

(A) 11.6 m.sec.

(B) 16.4 m.sec.
(C) 28 m.sec.

(D) 14 m.sec.

Answer: (B)

Explanation:

Time to serve  page fault if frame is empty or page replaced is not modified = 8 m.sec

Time to serve  page fault if page is modified = 20 m.sec

Frequency of Page modification  = 70% = 70/100 = 0.7

Frequency when page is not modified or frame is empty = (100-70)% = 30% = 30/100 = 0.3

Average access time = (0.3 * 8) + (0.7 * 20) = 2.4 + 14 = 16.4 m.sec

Hence correct option is (B) 16.4 m.sec.



Q : 41 __________ are applied throughout the software process.

(A) Framework activities
(B) Umbrella activities
(C) Planning activities
(D) Construction activities

Answer: (B)

Explanation:

Any standard software process model would primarily consist of two types of activities: A set of framework activities, which are always applicable, regardless of the project type, and a set of umbrella activities, which are the non SDLC activities that span across the entire software development life cycle.


The umbrella activities in a software development life cycle process include the following:
  • Software Project Management. 
  • Formal Technical Reviews. 
  • Software Quality Assurance. 
  • Software Configuration Management. 
  • Re-usability Management. 
  • Risk Management. 
  • Measurement and Metrics. 
  • Document Preparation and Production


Q: 42 Requirement Development, Organizational Process Focus, Organizational Training, Risk Management and Integrated Supplier Management are process areas required to achieve maturity level

(A) Performed
(B) Managed
(C) Defined
(D) Optimized

Answer: 

Explanation:

SEI Capability Maturity Model

SEI Capability Maturity Model (SEI CMM) helped organizations to improve the quality of the software they develop and therefore adoption of SEI CMM model has significant business benefits.
SEI CMM can be used two ways: capability evaluation and software process assessment. Capability evaluation and software process assessment differ in motivation, objective, and the final use of the result. Capability evaluation provides a way to assess the software process capability of an organization. The results of capability evaluation indicates the likely contractor performance if the contractor is awarded a work.On the other hand, software process assessment is used by an organization with the objective to improve its process capability. Thus, this type of assessment is for purely internal use.
SEI CMM classifies software development industries into the following five maturity levels. The different levels of SEI CMM have been designed so that it is easy for an organization to slowly build its quality system starting from scratch.

Level 1: Initial: A software development organization at this level is characterized by adhoc activities. Very few or no processes are defined and followed. Since software production processes are not defined, different engineers follow their own process and as a result development efforts become chaotic. Therefore, it is also called chaotic level. The success of projects depends on individual efforts and heroics. When engineers leave, the successors have great difficulty in understanding the process followed and the work completed. Since formal project management practices are not followed, under time pressure short cuts are tried out leading to low quality.

Level 2: Repeatable: At this level, the basic project management practices such as tracking cost and schedule are established. Size and cost estimation techniques like function point analysis, COCOMO, etc. are used. The necessary process discipline is in place to repeat earlier success on projects with similar applications. Please remember that opportunity to repeat a process exists only when a company produces a family of products.

Level 3: Defined: At this level the processes for both management and development activities are defined and documented. There is a common organization-wide understanding of activities, roles, and responsibilities. The processes though defined, the process and product qualities are not measured. ISO 9000 aims at achieving this level.

Level 4: Managed: At this level, the focus is on software metrics. Two types of metrics are collected. Product metrics measure the characteristics of the product being developed, such as its size, reliability, time complexity, understandability, etc. Process metrics reflect the effectiveness of the process being used, such as average defect correction time, productivity, average number of defects found per hour inspection, average number of failures detected during testing per LOC, etc. Quantitative quality goals are set for the products. The software process and product quality are measured and quantitative quality requirements for the product are met. Various tools like Pareto charts, fishbone diagrams, etc. are used to measure the product and process quality. The process metrics are used to check if a project performed satisfactorily. Thus, the results of process measurements are used to evaluate project performance rather than improve the process.

Level 5: Optimizing: At this stage, process and product metrics are collected. Process and product measurement data are analyzed for continuous process improvement. For example, if from an analysis of the process measurement results, it was found that the code reviews were not very effective and a large number of errors were detected only during the unit testing, then the process may be fine tuned to make the review more effective. Also, the lessons learned from specific projects are incorporated in to the process. Continuous process improvement is achieved both by carefully analyzing the quantitative feedback from the process measurements and also from application of innovative ideas and technologies. Such an organization identifies the best software engineering practices and innovations which may be tools, methods, or processes. These best practices are transferred throughout the organization.

CMM LevelFocusKey Process Ares
1. Initial
Competent people

2. Repeatable
Project management
Software project planning
Software Configuration
Management
3. Defined
Definition of Processes
Process definition
Training program Peer reviews
4. Managed
Product and Process Quality
Quantitative Process Metrics
Software Quality Management
5. Optimizing
Continuous Process Improvement
Defect Prevention
Process Change Management
Technology change management

Hence correct option is (C).

Q : 43 The software _________ of a program or a computing system is the structure or structures of the system, which comprise software components, the externally visible properties of those components, and the relationships among them.

(A) Design
(B) Architecture
(C) Process
(D) Requirement


Answer:

Explanation:

Software Architecture: 

Software architecture refers to the high level structures of a software system, the discipline of creating such structures, and the documentation of these structures. These structures are needed to reason about the software system. Each structure comprises software elements, relations among them, and properties of both elements and relations. The architecture of a software system is a metaphor, analogous to the architecture of a building.

Software architecture is about making fundamental structural choices which are costly to change once implemented. Software architecture choices include specific structural options from possibilities in the design of software. For example, the systems that controlled the space shuttle launch vehicle had the requirement of being very fast and very reliable. Therefore, an appropriate real-time computing language would need to be chosen. Additionally, to satisfy the need for reliability the choice could be made to have multiple redundant and independently produced copies of the program, and to run these copies on independent hardware while cross-checking results.

Documenting software architecture facilitates communication between stakeholders, captures early decisions about the high-level design, and allows reuse of design components between projects.

Hence correct option is (B).


Q : 44 Which one of the following set of attributes should not be encompassed by effective software metrics ?
(A) Simple and computable
(B) Consistent and objective
(C) Consistent in the use of units and dimensions
(D) Programming language dependent


Answer: (D)

Explanation: 

Software Metrics should never be Programming Language Dependent as in each programming language syntax, functions, operators, statements may differ a lot.
Hence correct option is (D).

Q : 45 Which one of the following is used to compute cyclomatic complexity ?
(A) The number of regions – 1
(B) E – N + 1, where E is the number of flow graph edges and N is the number of flow graph nodes.
(C) P – 1, where P is the number of predicate nodes in the flow graph G.
(D) P + 1, where P is the number of predicate nodes in the flow graph G.


Answer: (D)

Explanation:

Looking at first option which is incorrect it should be The number of regions + 1.

In second option which is also incorrect it should be E – N + 2P, where E is the number of flow graph edges and N is the number of flow graph node.







E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.

In the third option which is again incorrect it should be P + 1, where P is the number of predicate nodes in the flow graph G.
Hence correct option is (D) P+1, where P is the number of predicate nodes in the flow graph G.


Q : 46 Consider the following statements S1 and S2 :
S1 : A hard handover is one in which the channel in the source cell is retained and used
for a while in parallel with the channel in the target cell.
S2 : A soft handover is one in which the channel in the source cell is released and only
then the channel in the target cell is engaged.
(A) S1 is true and S2 is not true.
(B) S1 is not true and S2 is true.
(C) Both S1 and S2 are true.
(D) Both S1 and S2 are not true.

Answer: (D)

Explanation:

In cellular telecommunications, the term handover or handoff refers to the process of transferring an ongoing call or data session from one channel connected to the core network to another channel. In satellite communications it is the process of transferring satellite control responsibility from one earth station to another without loss or interruption of service.

Hard Handover: A Hard handover is one in which the channel in the source cell is released and only then the channel in the target cell is engaged. Thus the connection to the source is broken before or 'as' the connection to the target is made—for this reason such handovers are also known as break-before-make. Hard handovers are intended to be instantaneous in order to minimize the disruption to the call. A hard handover is perceived by network engineers as an event during the call. It requires the least processing by the network providing service. When the mobile is between base stations, then the mobile can switch with any of the base stations, so the base stations bounce the link with the mobile back and forth. This is called 'ping-ponging'.

Soft Handover: 
A soft handover is one in which the channel in the source cell is retained and used for a while in parallel with the channel in the target cell. In this case the connection to the target is established before the connection to the source is broken, hence this handover is called make-before-break. The interval, during which the two connections are used in parallel, may be brief or substantial. For this reason the soft handover is perceived by network engineers as a state of the call, rather than a brief event. Soft handovers may involve using connections to more than two cells: connections to three, four or more cells can be maintained by one phone at the same time. When a call is in a state of soft handover, the signal of the best of all used channels can be used for the call at a given moment or all the signals can be combined to produce a clearer copy of the signal. The latter is more advantageous, and when such combining is performed both in the downlink (forward link) and the uplink (reverse link) the handover is termed as softer. Softer handovers are possible when the cells involved in the handovers have a single cell site.

Hence correct option is (D).

Q : 47 Fact-less fact table in a data warehouse contains
(A) only measures
(B) only dimensions
(C) keys and measures
(D) only surrogate keys

Answer : (D)

Explanation:

A factless fact table is a fact table that does not have any measures. It is essentially an intersection of dimensions. On the surface, a factless fact table does not make sense, since a fact table is, after all, about facts. However, there are situations where having this kind of relationship makes sense in data warehousing.
For example, think about a record of student attendance in classes. In this case, the fact table would consist of 3 dimensions: the student dimension, the time dimension, and the class dimension. This factless fact table would look like the following:



The only measure that you can possibly attach to each combination is "1" to show the presence of that particular combination. However, adding a fact that always shows 1 is redundant because we can simply use the COUNT function in SQL to answer the same questions.

Factless fact tables offer the most flexibility in data warehouse design. For example, one can easily answer the following questions with this factless fact table:
How many students attended a particular class on a particular day?
How many classes on average does a student attend on a given day?

Without using a factless fact table, we will need two separate fact tables to answer the above two questions. With the above factless fact table, it becomes the only fact table that's needed.

Hence correct option is (D) Fact-less fact table in a data warehouse contains only surrogate keys.

Q : 48 Which e-business model allows consumers to name their own price for products and
services ?
(A) B2 B
(B) B2 G
(C) C2 C
(D) C2 B

Answer: (D)

Explanation:

B2B: B2B means that you are selling a product or service to other businesses.

A few examples of B2B product based companies would be:
Ex1: Selling CRM Software “Customer relationship management” to organizations so they can keep track of their sales leads, manage their sales cycles and determine a cold-calling schedule.
Ex2: Selling office equipment to companies who wish to upgrade their existing furniture.
Ex3: Selling security and access control hardware and systems to building management companies, universities and municipalities.

B2G: On the Internet, B2G is business-to-government (a variation of the term B2B or business-to-business), the concept that businesses and government agencies can use central Web sites to exchange information and do business with each other more efficiently than they usually can off the Web.
For example, a Web site offering B2G services could provide businesses with a single place to locate applications and tax forms for one or more levels of government (city, state or province, country, and so forth); provide the ability to send in filled-out forms and payments; update corporate information; request answers to specific questions; and so forth. 
B2G may also include-procurement services, in which businesses learn about the purchasing needs of agencies and agencies request proposal responses.
B2G may also support the idea of a virtual workplace in which a business and an agency could coordinate the work on a contracted project by sharing a common site to coordinate online meetings, review plans, and manage progress.
B2G may also include the rental of online applications and databases designed especially for use by government agencies.

C2C:

Customer to Customer (C2C) markets are innovative ways to allow customers to interact with each other. While traditional markets require business to customer relationships, in which a customer goes to the business in order to purchase a product or service. In customer to customer markets the business facilitates an environment where customers can sell these goods or services to each other.

Consumer to Consumer (or citizen-to-citizen) electronic commerce involves the electronically facilitated transactions between consumers through some third party. A common example is the online auction, in which a consumer posts an item for sale and other consumers bid to purchase it; the third party generally charges a flat fee or commission. The sites are only intermediaries, just there to match consumers. They do not have to check quality of the products being offered.

Consumer to Consumer (C2C) marketing is the creation of a product or service with the specific promotional strategy being for consumers to share that product or service with others as brand advocates based on the value of the product. The investment into concepting and developing a top of the line product or service that consumers are actively looking for is equitable to a retail pre-launch product awareness marketing.

C2B:

Consumer-to-business (C2B) is a business model in which consumers (individuals) create value and businesses consume that value. For example, when a consumer writes reviews or when a consumer gives a useful idea for new product development then that consumer is creating value for the business if the business adopts the input. Excepted concepts are crowd sourcing and co-creation.
C2B model, also called a reverse auction or demand collection model, enables buyers to name or demand their own price, which is often binding, for a specific good or service. The website collects the demand bids then offers the bids to participating sellers.

Hence correct option is (D).

Q : 49 __________ model is designed to bring prices down by increasing the number of
customers who buy a particular product at once.
(A) Economic Order Quantity
(B) Inventory
(C) Data Mining
(D) Demand-Sensitive Pricing

Answer: (D)

Explanation:

'Demand-Sensitive Pricing' or 'Price Elasticity Of Demand'

A measure of the relationship between a change in the quantity demanded of a particular good and a change in its price. Price elasticity of demand is a term in economics often used when discussing price sensitivity. The formula for calculating price elasticity of demand is:

Price Elasticity of Demand = % Change in Quantity Demanded / % Change in Price
If a small change in price is accompanied by a large change in quantity demanded, the product is said to be elastic (or responsive to price changes). Conversely, a product is inelastic if a large change in price is accompanied by a small amount of change in quantity demanded.

Hence correct option is (D).



Q : 50 Match the following :
List – I List – II
a. Call control protocol                               i. Interface between Base Transceiver Station
                                                                         (BTS) and Base Station Controller (BSC)

b. A-bis                                                         ii. Spread spectrum

c. BSMAP                                                    iii. Connection management

d. CDMA                                                     iv. Works between Mobile Switching Centre
                                                                         (MSC) and Base Station Subsystem (BSS)
Codes :
       a    b    c    d
(A) iii   iv   i     ii
(B) iii   i     iv   ii
(C) i     ii    iii   iv
(D) iv   iii   ii    i

Answer: (B)

Friday, January 21, 2022

Copy Constructor in C++

When we want to initialize an object with use of some other object then copy constructor may be used.

It require reference to the object who's values will be copied to create new object. However it can also work without reference variable.

 #include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()

{

a=0;

b=0;

}

abc(int x,int y)

{

a=x;

b=y;

}

abc(abc &k)//copy constructor

{

a=k.a;

b=k.b;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

int l,m;

cout<<"Enter two no." <<endl;

cin>>l>>m;

abc ob1,ob2(l,m),ob3(ob2);

ob1.show();

ob2.show();

ob3.show();

getch();

}

In which case Copy Constructor is executed

1. When we pass object to a constructor then copy constructor provided by the programmer is executed.

2. When object is passed to a function

3. When object is assigned to another object using = operator 


Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

Dynamic Constructor in C++

Whenever value passed to a parameterized constructor is provided at runtime it is known as dynamic constructor

#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()

{

a=0;

b=0;

}

abc(int x,int y)

{

a=x;

b=y;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

int l,m;

cout<<"Enter two no." <<endl;

cin>>l>>m;

abc ob1,ob2(l,m);//dynamic constructor

ob1.show();

ob2.show();

getch();

}

In main function l & m will be initialized at runtime.


Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

Parameterized Constructor in C++

 Whenever we want to initialize data members with some values we use parameterized constructors.


#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()//default

{

a=0;

b=0;

}

abc(int x,int y)//parameterized

{

a=x;

b=y;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

abc ob1,ob2(10,20);

ob1.show();//it will print 0 0

ob2.show();//it will print 10 20

getch();

a & b of ob1 will be initialized to 0

a & b of ob2 will be initialized to 10  &  20 respectively.

Note: As we are creating a parameterized constructor we always need to provide default constructor.



Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

Types of Constructors in C++


Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

//Default Constructor By Programmer

#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()

{

a=10;

b=20;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

abc ob;

ob.show();

getch();

}

The above example shows that a & b will always be initialized to 10 & 20. It is default constructor by the programmer.

If we do not provide any constructor then default constructor by the compiler will initialize a & b with garbage value.


Constructors & Destructors in C++

 Constructors are special member functions which are executed automatically when object of a class is created. These are special because they have same name as name of class. These are also special because they do not have any return type. 

Syntax:

class-name(parameter list)

{

...

}

Eg:

#include<iostream.h>

#include<conio.h>

class abc

{

int a,b;

public:

abc()

{

a=0;

b=0;

}

void show()

{

cout<<"a= "<<a<<endl<<"b= "<<b<<endl;

}

};

void main()

{

clrscr();

abc ob;

ob.show();

getch();

}

Source Code

Types of Constructors in C++:


Default Constructor

Parameterized Constructor

Copy Constructor

Dynamic Constructor

Thursday, January 20, 2022

ActionEvent class in JAVA

The ActionEvent Class

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_ PERFORMED, which can be used to identify action events.

ActionEvent has these three constructors: 

ActionEvent(Object src, int type, String cmd) 

ActionEvent(Object src, int type, String cmd, int modifiers) 

ActionEvent(Object src, int type, String cmd, long when, int modifiers) 

Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when parameter specifies when the event occurred. You can obtain the command name for the invoking ActionEvent object by using the getActionCommand( ) method, shown here: 

String getActionCommand( ) 

For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button. The getModifiers( ) method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. 

Its form is shown here: 

int getModifiers( ) 

The method getWhen( ) returns the time at which the event took place. This is called the event’s timestamp. 

The getWhen( ) method is shown here: 

long getWhen( )

Program to ADD two numbers in JAVA using GUI


#JAVA #awt #swing #events #frames #jframe #java 



Add Two Numbers in JAVA using GUI (awt, swing, event handling)


 import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class MyFrameSample  extends JFrame implements ActionListener

{


JButton btn;

JTextField[] txt;

MyFrameSample()

{

txt=new JTextField[3];//initializing array of text fields

btn=new JButton("Click Me");//initializing button

txt[0]=new JTextField("Enter a");//it will be used to take number as input

txt[1]=new JTextField("Enter b");

txt[2]=new JTextField("a+b = ");//result will be set here

btn.addActionListener(this);//it register action listener with button and this(out frame) will

// handle action event

add(txt[0]);

add(txt[1]);

add(txt[2]);

add(btn);

}

public void actionPerformed(ActionEvent e)//on button click this will be called

{

int a=Integer.parseInt(txt[0].getText());//converting string into integer

int b=Integer.parseInt(txt[1].getText());

int c=a+b;

txt[2].setText(""+c);

}

}

class FrameDemoSample

{

public static void main(String args[])

{

MyFrameSample x=new MyFrameSample();

x.setLayout(new FlowLayout());//setting layout

x.setSize(300,400);//setting size

x.setTitle("My Frame Sample");//title

x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//cross button working

x.setVisible(true);//frame will be visible now

}

}

#JAVA #awt #swing #events #frames #jframe #java 

UGC-NET Computer Science Unix Questions with Explanation

passwd Command in Unix:

The command that we use in a Unix system to change password is passwd (Note spelling correctly).
passwd:

$ passwd
Old   Password :   **********[enter]
New  Password :  *********[enter]
Renter Password : *********[enter]

$ _
(Prompt is returned-command completes)

Event Handling in JAVA

 Event handling is fundamental to Java programming because it is integral to the creation of  GUI-based programs. Furthermore, any program that uses a graphical user interface, such as a Java application written for Windows, is event driven. Thus, you cannot write these types of programs without a solid command of event handling. Events are supported by a number of packages, including java.util, java.awt, and java.awt.event. Most events to which your program will respond are generated when the user interacts with a GUI-based program. They are passed to your program in a variety of ways, with the specific method dependent upon the actual event. There are several types of events, including those generated by the mouse, the keyboard, and various GUI controls, such as a push button, scroll bar, or check box.

The Delegation Event Model

The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an event is received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to “delegate” the processing of an event to a separate piece of code. In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it was handled by a component. This required components to receive events that they did not process, and it wasted valuable time. The delegation event model eliminates this overhead.

Note: Event here is actual object of particular Event.


Events

In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. You are free to define events that are appropriate for your application. 

Event Sources

A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. 

Here is the general form: public void addTypeListener(TypeListener el) 

Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.

A source must also provide a method that allows a listener to unregister an interest in a specific type of event. 

The general form of such a method is this: public void removeTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners.

Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

Event Classes

The classes that represent events are at the core of Java’s event handling mechanism. Thus, a discussion of event handling must begin with the event classes. It is important to understand, however, that Java defines several types of events and that not all event classes can be discussed in this chapter. The most widely used events are those defined by the AWT and those defined by Swing. 

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events.

 Its one constructor is shown here: EventObject(Object src)

Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the event.

Its general form is shown here: Object getSource( ) 

As expected, toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its getID( ) method can be used to determine the type of the event.

The signature of this method is shown here: int getID( ) 

The package java.awt.event defines many types of events that are generated by various user interface elements.


Monday, June 21, 2021

Inter Thread Communication in java

multithreading replaces event loop programming by dividing your

tasks into discrete, logical units. Threads also provide a secondary benefit: they do away

with polling. Polling is usually implemented by a loop that is used to check some condition

repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time.

For example, consider the classic queuing problem, where one thread is producing some

data and another is consuming it. To make the problem more interesting, suppose that the

producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to

produce. Once the producer was finished, it would start polling, wasting more CPU cycles

waiting for the consumer to finish, and so on. Clearly, this situation is undesirable.

To avoid polling, Java includes an elegant interprocess communication mechanism via

the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final

methods in Object, so all classes have them. All three methods can be called only from

within a synchronized context. Although conceptually advanced from a computer science

perspective, the rules for using these methods are actually quite simple:

• wait( ) tells the calling thread to give up the monitor and go to sleep until some

other thread enters the same monitor and calls notify( ).

• notify( ) wakes up a thread that called wait( ) on the same object.

• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of

the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException

final void notify( )

final void notifyAll( )

Additional forms of wait( ) exist that allow you to specify a period of time to wait.

Before working through an example that illustrates interthread communication, an

important point needs to be made. Although wait( ) normally waits until notify( ) or

notifyAll( ) is called, there is a possibility that in very rare cases the waiting thread could be

awakened due to a spurious wakeup. In this case, a waiting thread resumes without notify( )

or notifyAll( ) having been called. (In essence, the thread resumes for no apparent reason.)

Because of this remote possibility, Sun recommends that calls to wait( ) should take place

within a loop that checks the condition on which the thread is waiting. The following

example shows this technique.

 //Inter Thread Communication in java

class Shared

{

int n;

boolean available=false;

Shared(int x)

{

n=x;

}

synchronized void produce(int x)

{

while(available)

{

try

{

wait();

}

catch(InterruptedException e){}

}

n=x;

available=true;

notify();

}

synchronized int consume()

{

while(!available)

{

try

{

wait();

}

catch(InterruptedException e){}

}

available=false;

notify();

return n;

}

}

class Producer implements Runnable

{

Shared s;

Producer(Shared s1)

{

s=s1;

}

public void run()

{

for(int i=1;i<=10;i++)

{

s.produce(i);

System.out.println("Produced "+i);

}

}

}

class Consumer implements Runnable

{

Shared s;

Consumer(Shared s1)

{

s=s1;

}

public void run()

{

for(int i=1;i<=10;i++)

{

System.out.println("Consumed "+s.consume());

}

}

}

class InterThreadComDemo

{

public static void main(String args[])

{

Shared ob=new Shared(-1);

Producer p=new Producer(ob);

Consumer c=new Consumer(ob);

Thread t1=new Thread(p);

Thread t2=new Thread(c);

t1.start();

t2.start();

}

}

Deadlocks in JAVA

A special type of error that you need to avoid that relates specifically to multitasking is

deadlock, which occurs when two threads have a circular dependency on a pair of synchronized

objects. For example, suppose one thread enters the monitor on object X and another thread

enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y,

it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized

method on X, the thread waits forever, because to access X, it would have to release its own

lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for

two reasons:

• In general, it occurs only rarely, when the two threads time-slice in just the right way.

• It may involve more than two threads and two synchronized objects

//Deadlocks in java

 class DeadLockDemo

{

public static void main(String args[])

{

String r1="Resource 1";

String r2="Resource 2";

Thread t1=new Thread()

{

public void run()

{

synchronized(r1)

{

System.out.println("Locked R1");

try

{

Thread.sleep(300);

}

catch(Exception e){}

synchronized(r2)

{

System.out.println("Locked R2");

}

}

}

};

Thread t2=new Thread()

{

public void run()

{

synchronized(r2)

{

System.out.println("Locked R2");

try

{

Thread.sleep(300);

}

catch(Exception e){}

synchronized(r1)

{

System.out.println("Locked R1");

}

}

}

};

t1.start();

t2.start();

}

}

Rethrowing Exception in JAVA

 A Java exception is an object that describes an exceptional (that is, error) condition that has

occurred in a piece of code. When an exceptional condition arises, an object representing

that exception is created and thrown in the method that caused the error. That method may

choose to handle the exception itself, or pass it on. Either way, at some point, the exception

is caught and processed. Exceptions can be generated by the Java run-time system, or they

can be manually generated by your code. Exceptions thrown by Java relate to fundamental

errors that violate the rules of the Java language or the constraints of the Java execution

environment. Manually generated exceptions are typically used to report some error condition

to the caller of a method.

Java exception handling is managed via five keywords: try, catch, throw, throws, and

finally. Briefly, here is how they work. Program statements that you want to monitor for

exceptions are contained within a try block. If an exception occurs within the try block, it is

thrown. Your code can catch this exception (using catch) and handle it in some rational manner.

System-generated exceptions are automatically thrown by the Java run-time system. To

manually throw an exception, use the keyword throw. Any exception that is thrown out of

a method must be specified as such by a throws clause. Any code that absolutely must be

executed after a try block completes is put in a finally block.

//Rethrowing Exception in JAVA

class ExceptionDemo

{

static void divide(int a,int b)

{

try

{

System.out.println("a/b = "+a/b);

}

catch(ArithmeticException e)

{

System.out.println("ArithmeticException caught in divide");

System.out.println("Rethrowing e");

throw e;

}

}

public static void main(String args[])

{

try

{

divide(10,2);

divide(20,0);

}

catch(ArithmeticException e)

{

System.out.println("ArithmeticException Caught in main");

}

}

}

User Defined Exception in JAVA

Although Java’s built-in exceptions handle most common errors, you will probably want

to create your own exception types to handle situations specific to your applications. This

is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of

Throwable). Your subclasses don’t need to actually implement anything—it is their existence

in the type system that allows you to use them as exceptions.

The Exception class does not define any methods of its own. It does, of course, inherit

those methods provided by Throwable. Thus, all exceptions, including those that you create,

have the methods defined by Throwable available to them.Exception defines four constructors. Two were added by JDK 1.4 to support chained

exceptions, described in the next section. The other two are shown here:

Exception( )

Exception(String msg)

The first form creates an exception that has no description. The second form lets you specify

a description of the exception.

Although specifying a description when an exception is created is often useful, sometimes

it is better to override toString( ). Here’s why: The version of toString( ) defined by Throwable

(and inherited by Exception) first displays the name of the exception followed by a colon, which

is then followed by your description. By overriding toString( ), you can prevent the exception

name and colon from being displayed. This makes for a cleaner output, which is desirable in

some cases.


 //User defined exception when radius of circle is negative

class MyException extends Exception

{

MyException()

{

//Empty Constructor must be there

}

MyException(String str)

{

super(str);

}

}

class DemoException

{

static double area(double r) throws MyException

{

if(r<0)

throw new MyException("Radius cannot be negative");

return 3.14*r*r;

}

public static void main(String args[])

{

try

{

System.out.println("Area is "+area(-10.0));

}

catch(MyException e)

{

//e.printStackTrace();

                        System.out.println(e.getMessage());//It will print Radius cannot be negative 

}

finally

{

System.out.println("Inside Finally");

}

System.out.println("Program Ends");

}

}

Coding Acceleration Program

🚀 CODING ACCELERATION PROGRAM (90 DAYS) Build Strong Foundations Learn to Think Like a Programmer Get Placement Ready 💡 Learn C Progra...