Sunday, 23 January 2022

Java Database Connectivity Example



import java.sql.*;
class JavaCon 
    public static void main(String a[]) 
    { 
        String url = "jdbc:oracle:thin:@localhost:1521:xe"; //connecting to port
        String user = "system"; //user name for dbms
        String pass = "12345";//password
        String sql2 = "select * from STUDENT";
//simple select query Student table already exist in database
        Connection con; //Making connection reference
        try
        { 
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());//registering driver 
  
            
            con = DriverManager.getConnection(url,user,pass); //initializing connection object
  
            Statement stm = con.createStatement(); //creating statement object
    System.out.println("Connected");//if all goes well
      ResultSet rs = stm.executeQuery(sql2);
//executing the query which will return whole table as result set
while(rs.next())//row pointer pointing one by one to next row 
{
         //getting attribute values using attribute names
         int roll  = rs.getInt("ROLLNO"); 
         String name = rs.getString("NAME");
         String cl = rs.getString("CLASS");
         System.out.println("NAME: " +name+" Roll Number: "+roll+" CLASS: "+cl);
         
    }
            //closing objects
            rs.close();
            con.close();
            stm.close();
        } 
        catch(Exception e) 
        { 
            System.out.println(e); 
        } 
    } 




Java JDBC Tutorial

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers:
JDBC-ODBC Bridge Driver,
Native Driver,
Network Protocol Driver, and
Thin Driver
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface

A list of popular classes of JDBC API are given below:
DriverManager class
Blob class
Clob class
Types class
Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following activities:
Connect to the database
Execute queries and update statements to the database
Retrieve the result received from the database.Do You Know

How to connect Java application with Oracle and Mysql database using JDBC?
What is the difference between Statement and PreparedStatement interface?
How to print total numbers of tables and views of a database using JDBC?
How to store and retrieve images from Oracle database using JDBC?
How to store and retrieve files from Oracle database using JDBC?

What is API

API (Application programming interface) is a document that contains a description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc.

Topics in Java JDBC Tutorial2) JDBC Drivers

In this JDBC tutorial, we will learn four types of JDBC drivers, their advantages and disadvantages.3) 5 Steps to connect to the Database

In this JDBC tutorial, we will see the five steps to connect to the database in Java using JDBC.4) Connectivity with Oracle using JDBC

In this JDBC tutorial, we will connect a simple Java program with the Oracle database.5) Connectivity with MySQL using JDBC

In this JDBC tutorial, we will connect a simple Java program with the MySQL database.6) Connectivity with Access without DSN

Let's connect java application with access database with and without DSN.7) DriverManager class

In this JDBC tutorial, we will learn what does the DriverManager class and what are its methods.8) Connection interface

In this JDBC tutorial, we will learn what is Connection interface and what are its methods.9) Statement interface

In this JDBC tutorial, we will learn what is Statement interface and what are its methods.10) ResultSet interface

In this JDBC tutorial, we will learn what is ResultSet interface and what are its methods. Moreover, we will learn how we can make the ResultSet scrollable.11) PreparedStatement Interface

In this JDBC tutorial, we will learn what is benefit of PreparedStatement over Statement interface. We will see examples to insert, update or delete records using the PreparedStatement interface.12) ResultSetMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a table.13) DatabaseMetaData interface

In this JDBC tutorial, we will learn how we can get the metadata of a database.14) Storing image in Oracle

Let's learn how to store image in the Oracle database using JDBC.15) Retrieving image from Oracle

Let's see the simple example to retrieve image from the Oracle database using JDBC.16) Storing file in Oracle

Let's see the simple example to store file in the Oracle database using JDBC.17) Retrieving file from Oracle

Let's see the simple example to retrieve file from the Oracle database using JDBC.18) CallableStatement

Let's see the code to call stored procedures and functions using CallableStatement.19) Transaction Management using JDBC

Let's see the simple example to use transaction management using JDBC.20) Batch Statement using JDBC

Let's see the code to execute batch of queries.21) JDBC RowSet

Let's see the working of new JDBC RowSet interface.

NET December 2021 Computer Science Solved Paper 2 Question 1

 Q: 1 Let us assume a person climbing the stairs can take one stair or two stairs at a time. How many ways can this person climb a flight of eight stairs?

(a) 21

(b) 24

(c) 31

(d) 34

Answer : d


Solution:

First Method :


In this case answer would be 9th Fibonacci number as number of stairs are 8 so answer is fib(9) = 34.
If number of stairs = n then total ways will be fib(n+1).
Second Method :

Here, we have to use the concept of combination to find the number of ways in which a person can walk up a stairway which has 8 steps. So, we have to make
pairs of the combination of 1 and 2 steps and then by using the concept of the combination we will get the number of ways a person can walk up a stairway of 8 steps.



It is given that there are 8 steps of the stairway and he can take only 1 or 2 steps up the
stairs at a time.


   No. of Step 1               No. of Step 2               Total Ways
   8                                        0                                    1               
   6                                        1                                  (7!)/(6!)(1!) = 7
   4                                        2                                  (6!)/(4!)(2!) = 15
   2                                        3                                  (5!)/(2!)(3!) = 10
   0                                        4                                     1

Adding all we get 1+7+15+10+1= 34
So, 34 is right answer which is also 9th Fibonacci Number.


#NTA #NET #NETDECEMBER2021 Discrete Mathematics Combination


Friday, 21 January 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)

Thursday, 20 January 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