Remote Method Invocation (RMI) Interview Questions in Java

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

Remote Method Invocation (RMI) Interview Questions in Java

Question 1.
What are RMI and the steps involved in developing an RMI object?
Answer:
Remote Method Invocation (RMI) allows java objects that execute on one machine and invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are:

  • Define the interfaces.
  • Implementing these interfaces
  • Compile the interfaces and their implementations with the java compiler
  • Compile the server implementation with the RMI compiler
  • Run the RMI registry
  • Run the application

Question 2.
What is RMI architecture?
Answer:
RMI architecture consists of four layers and each layer performs specific functions:

a) Application layer                ——-     contains the actual object definition
b) Proxy layer                         ——-     consists of stub and skeleton
c) Remote Reference layer     ——-     gets the stream of bytes from the transport layer and sends it to the proxy layer
d) Transportation layer          ——-     responsible for handling the actual machine-to-machine communication

Question 3.
What is UnicastRemoteObject?
Answer:
All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.

Question 4.
Explain the methods, rebind( ) and lookup( ) in Naming class?
Answer:
rebind( ) of the Naming class(found in java.rmi) is used to update the RMI registry on the server machine.
Naming. rebind(“AddSever”, AddServerlmpl);
lookup( ) of the Naming class accepts one argument, the rmi URL, and returns a reference to an object of type AddServerlmpl.

 

Java Networking Interview Questions in Java

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

Java Networking Interview Questions in Java

Question 1.
What are Datagrams and Sockets?
Answer:
A socket represents a connection point into a TCP/IP network between two computers; one of which is the server and the other is the client. Sockets are used to access the Web server. These sockets are available in the Java Socket class. Sockets act as virtual passageways for communication through which the data travels from one host to another. Sockets are of two types, connection-oriented or connectionless. The connection-oriented socket operates similarly to a telephone where the connection is established prior to the transmission of data. The second type of socket is the connectionless socket. This type of socket is called a Datagram. This socket operates similarly to the mail. A characteristic of the Datagram is that it allows only one message to be sent at a time. The delivery of data is not guaranteed because Datagrams use the UDP protocol.

Question 2.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances of InetAddress.

Question 3.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 4.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 5.
What are the seven layers of the OSI model?
Answer:
Application
Presentation
Session
Transport
Network
DataLink
Physical Layer.

Question 6.
What Transport Layer does?
Answer:
It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent.

Question 7.
What is DHCP?
Answer:
Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.

Question 8.
What is SMTP?
Answer:
Simple Mail Transmission Protocol, the TCP/IP Standard for Internet mails. SMTP exchanges mail between servers; contrast this with POP, which transmits mail between a server and a client.

Question 9.
In OSI N/W architecture, the dialogue control and token management are responsibilities of which layer?
Answer:
b) Session Layer.

Question 10.
In OSI N/W Architecture, the routing is performed by which layer?
Answer:
Network Layer.

Question 11.
What is the difference between URL instances and URLConnection instances?
Answer:
A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

Question 12.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke openConnection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.

Question 13.
What Is a Socket?
Answer:
A socket is one end-point of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes-Socket and ServerSocket–which implement the client-side of the connection and the server-side of the connection, respectively.

Question 14.
What information is needed to create a TCP Socket?
Answer:
The Local System’s IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

Question 15.
what are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in Socket class.

Question 16.
When MalformedURLException and UnknownHostException throws?
Answer:
When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unable to resolve the hostname they throw an UnknownHostException.

Question 17.
Define Network Programming?
Answer:
It refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Question 18.
What is a Socket?
Answer:
Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

Question 19.
Advantages of Java Sockets?
Answer: Sockets are flexible and sufficient. Efficient socket-based programming can be easily implemented for general communications. It causes low network traffic.

Question 20.
Disadvantages of Java Sockets?
Answer:
Socket-based communications allow only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.

Question 21.
Which class is used by server applications to obtain a port and listen for client requests?
Answer:
java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests.

Question 22.
Which class represents the socket that both the client and server use to communicate with each other?
Answer:
java.net.Socket class represents the socket that both the client and server use to communicate with each other.

Question 23.
How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
Answer:
By InetAddress.getByName(“192.18.97.39”).getHostName( ) where 192.18.97.39 is the IP address.

Question 24.
How do I get the IP address of a machine from its hostname?
Answer:
The InetAddress class is able to resolve IP addresses for you. Obtain an instance of InetAddress for the machine, and call the get host address( ) method, which returns a string in the xxx.xxx.xxx.xxx address form.

InetAddress inet = InetAddress.getByNameC“www.davidreilly.com”); 
System.out.println (“IP: “ + inet.getHostAddress( )) ;

Question 25.
How do I perform a hostname lookup for an IP address?
Answer:
The InetAddress class contains a method that can return the domain name of an IP address. You need to obtain an InetAddress class and then call its get hostname( ) method. This will return the hostname for that IP address. Depending on the platform, a partial or a fully qualified hostname may be returned.

InetAddress inet = InetAddress.getByName(“209.204.220.121”); 
system. out.println (“Host: “ + inet.get hostname( ));

Question 26.
How can I find out who is accessing my server?
If you’re using a DatagramSocket, every packet that you receive will contain the address and port from which it was sent.

DatagramPacket packet = null;
// Receive next packet 
myDatagramsocket.receive (packet);
// Print address + port
system.out.println (“Packet From: “ + packet.getAddress( ). 
getHostAddress( ) + ' : ’ + packet. getPort( ));

If you’re using a ServerSocket, then every socket connection you accept will contain similar information. The Socket class has a getlnetAddress( ) and getPort( ) method which will allow you to find the same information.

socket mysock = myServersocket.accept( );
// Print address + port
System.out.println (“connection From: “ + mySock.getlnetAddress( ). 
getHostAddress( ) + ‘:’ + mysock. getPort( ));

27. How can I find out the current IP address for my machine?
Answer:
The InetAddress has a static method called get localhost( ) which will return the current address of the local machine. You can then use the getHostAddressO method to get the IP address.

InetAddress local = InetAddress.getLocalHost( );
// print address
System.out.println (“Local IP: “ + local .getHostAddress( ));

Question 28.
Why can’t my applet connect via sockets, or bind to a local port?
Applets are subject to heavy security constraints when executing under the control of a browser. Applets are unable to access the local file system, bind to local ports, or connect to a computer via sockets other than the computer from which the applet is loaded. While it may seem to be an annoyance for developers, there are many good reasons why such tight constraints are placed on applets. Applets could bind to well-known ports, and service network clients without authorization or consent. Applets executing within firewalls could obtain privileged information, and then send it across the network.

Applets could even be infected by viruses, such as the Java StrangeBrew strain. Applets might become infected without an applet author’s knowledge and then send information back that might leave hosts vulnerable to attack.

Signed applets may be allowed greater freedom by browsers than unsigned applets, which could be an option. In cases where an applet must be capable of network communication, HTTP can be used as a communication mechanism. An applet could communicate via java.net.URLConnection with a CGI script or a Java servlet. This has an added advantage – applets that use the URLConnection will be able to communicate through a firewall.

Question 29.
What are socket options, and why should I use them?
Socket options give developers greater control over how sockets behave. Most socket behavior is controlled by the operating system, not Java itself, but as of JDKl.l, you can control several socket options, including SOJTIMEOUT, SO_LINGER, TCP_ NODELAY, SO.RCVBUF and SO_SNDBUF.
These are advanced options, and many programmers may want to ignore them. That’s OK, but be aware of their existence for the future. You might like to specify a timeout for reading operations, to control the amount of time a connection will linger for before a reset is sent, whether Nagle’s algorithm is enabled/disabled, or the send and receive buffers for datagram sockets.

Question 30.
How do I display more than one page from an applet?
The show document method of the AppletContext interface is overloaded – meaning that it can accept more than one parameter. It can accept a second parameter, which represents the name of the browser window that should display a page.
For example,
myAppletContext.show document (myurl, “frame 1”) will display the document in frame 1. If there exists no window named frame 1, then a brand new window will be created.

Question 31.
How do I use a proxy server for HTTP requests?
When a Java applet under the control of a browser (such as Netscape or Internet Explorer) fetches content via an URLConnection, it will automatically and transparently use the proxy settings of the browser.
If you’re writing an application, however, you’ll have to manually specify the proxy server settings. You can do this when running a Java application or you can write code that will specify proxy settings automatically for the user (providing you allow the users to customize the settings to suit their proxy servers).
To specify proxy settings when running an application, use the -D parameter:

jre -DproxySet=true -DproxyHost=myhost -DproxyPort=myport MyApp

Alternately, your application can maintain a configuration file, and specify proxy settings before using an URLConnection:

// Modify system properties
Properties sysProperties = System.getProperties( );
 // Specify proxy settings
sysProperties.put(“proxyHost”, “myhost”);
 sysProperties.put(“proxyPort”, “myport”); 
sysProperties.put(“proxySet”, “true”);

Question 32.
What is a malformed URL, and why is it exceptional?
When you create an instance of the java.net.URL class, its constructor can throw a MalformedURLException. This occurs when the URL is invalid. When it is thrown, it isn’t because the host machine is down, or the URL path points to a missing file; a malformed URL exception is thrown when the URL cannot be correctly parsed. Common mistakes include:-

  • leaving out a protocol (eg “www.microsoft.com” instead of “http://www.microsoft. com/”)
  • specifying an invalid protocol (eg “www://netscape.com”)
  • leaving out the character (eg http//www.micrsoft.com/)

MalformedURLException will not be thrown if:-

  • the hostname is invalid (eg “www.microsoft-rules-the-world.com”)
  • the path is invalid (eg “http://www.microsoft.com/company_secrets.htm”)

Question 33.
Why is a security exception thrown when using java.net.URL or java.net. URLConnection from an applet?
Answer:
Web browsers impose security restrictions on applets, which prevent applets from establishing network connections to servers other than that from which they were loaded. Like socket connections, HTTP connections will cause security exceptions to be thrown. If you absolutely, positively, have to access other hosts (and replacing your applet with a Java servlet is impractical), consider using a digitally signed applet.

Question 34.
How do I prevent caching of HTTP requests?
Answer:
By default, caching will be enabled. You must use a URLConnection, rather than the URL.openStreamO method, and explicitly specify that you do not want to cache the requests. This is achieved by calling the URLConnection.setup caches (boolean) method with a value of false.

Question 35.
What’s the Factory Method?
Answer:
Factory methods are merely a convention whereby static methods in a class return an instance of that class. The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the available factory methods. In InetAddress the three methods getLocalHost, getByName, getByAllName can be . used to create instances of InetAddress.

Question 36.
What’s the difference between TCP and UDP?
Answer:
These two protocols differ in the way they carry out the action of communicating. A TCP protocol establishes a two-way connection between a pair of computers, while the UDP protocol is a one-way message sender. The common analogy is that TCP is like making a phone call and carrying on two-way communication, while UDP is like mailing a letter.

Question 37.
What is the Proxy Server?
Answer:
A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular website, a proxy server can get the contents of the web server’s popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients. Also, we can get multiple connections for a single server.

Question 38.
How do I make a connection to the URL?
Answer:
You obtain a URL instance and then invoke open Connection on it. URLConnection is an abstract class, which means you can’t directly create instances of it using a constructor. We have to invoke the openConnection method on a URL instance, to get the right kind of connection for your URL.
E.g.

URL url;
URLConnection connection; 
try{ url = new URL(“...”); 
conection = url.openConnection( );
} catch (MaiFormedURLException e) {  }

Question 39.
When MalformedURLException and UnknownHostException throw?
Answer:
When the specified URL is not connected then the URL throw Malforme- dURLExceptiop and If InetAddress’ methods
getByName( ) and getLocalHost( ) are unable to resolve the host name they throw an UnknownHostException.

Question 40.
What are the two important TCP Socket classes?
Answer:
Socket and ServerSocket.
ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets.
getlnputStream( ) and getOutputStream( ) are the two methods available in the Socket class.

Java Applet Interview Questions in Java

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

Java Applet Interview Questions in Java

Question 1.
What is the difference between applications and applets?
Answer:

a) Application must be run on a local machine whereas the applet needs no explicit installation on the local machine.
b) Application must be run explicitly within a Java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser.
d) Application starts execution with its main method whereas applet starts execution with its init method.
e) Application can run with or without the graphical user interface whereas applet must run within a graphical user interface.

Question 2.
How does the applet recognize the height and width?
Answer:
Using getParameters( ) method.

Question 3.
When do you use codebase in the applet?
Answer:
When the applet class file is not in the same directory, the codebase is used.

Question 4.
What is the lifecycle of an applet?
Answer:
init( ) method – Can be called when an applet is first loaded
start( ) method – Can be called each time an applet is started
paint( ) method – Can be called when the applet is minimized or maximized
stop( ) method – Can be used when the browser moves off the applet’s page
destroy( ) method – Can be called when the browser is finished with the applet

Question 5.
How do you set security in applets?
Answer:
using setSecurityManager( ) method

Question 6.
How will you initialize an Applet?
Answer:
By including the initialization code in the init( ) method.

Question 7.
What is the order of method invocation in an Applet?
Answer:
init( ), start( ), paint( ), stop( ), destroy( ),

Question 8.
When is the update method called?
Answer:
Whenever we minimize, maximize, restart the applet, and explicitly calling the repaint( ) method in the code. Repaint( ) method will implicitly call the update!) method.

Question 9.
How will you communicate between two Applets?
Answer:
By creating URL object, URLConnection object and getting InputStream , OutputStream Using getlnputStream( ), getOutputStream( )

Question 10.
What is an applet?
Answer: Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

Question 11.
How does the applet recognize the height and width?
Answer.
’Using getParameters( ) method.

Question 12.
When do you use codebase in the applet?
Answer:
When the applet class file is not in the same directory, the codebase is used.

Question 13.
How do you set security in applets?
Answer:
using setSecurityManager( ) method

Question 14.
The definition of an applet named MyApplet would begin with the line

class MyApplet extends Applet {

What is going on here? What is “Applet”? What is the word “extends” doing there?
Answer:
The applet is the name of a class that is a standard part of Java. Here, MyApplet is a new class that is being defined as a subclass of Applet. The word “extends” is used to create subclasses in this way. The class MyApplet inherits everything that is in the class Applet. The rest of the definition of MyApplet will consist of additions and modifications to the stuff that is inherited from Applet.
(Note: The Applet class is actually defined in the package java. applet, so the above line has to be preceded by “import java.applet.*” or “import java.applet.Applet;” to make the applet class available.)

Question 15.
An applet can define a method
public boolean keyDown(Event evt, int key)
What is the purpose of such a method? What is the key parameter for? Why is this method “public”?
Answer:
This keyDown method will be called by the “system” when the user presses a key on the keyboard (assuming that the applet has the input focus at that time). You would write such a method to react to the user’s keystrokes. The key parameter tells which key the user pressed. This method has to be public since it is called by the system, from outside the class that contains the method.

Question 16.
Is it possible to access the network resources through an Applet on the browser?
Answer:
There is no way that an applet can access network resources. You have to implement a Java Query Server that will be running on the same machine from where you are receiving your applet (that is Internet Server). Your applet will communicate with that server which will fulfill all the requirements of the applet. You can communicate between applet and Java query server using sockets RMI (preferred, as this will return the whole object).

Question 17.
Java applets can be downloaded from anywhere and run on a client’s system. What are the restrictions imposed on Java applets that prevent them from causing system damage or security breaches?
Answer:
The restrictions that are there for Java applets are: –

  • Applets cannot read or write to the local file system where it is being executed.
  • Applets can only communicate back to the server from where it was downloaded by the browser.
  • Applets cannot execute any local program on the client’s system.

Question 18.
What is the sequence of interpretation, compilation of a java applet?
Answer:
A java program is first compiled to bytecode which is stored in a ‘.class file’. This file is downloaded as an applet to a browser which then interprets it by converting it into machine code appropriate to the hardware platform on which it is running. •

Question 19.
Is it possible to access the network resources through an Applet on the browser?
Answer:
There is no way that an applet can access network resources. You have to implement a Java Query Server that will be running on the same machine from where you are receiving your applet (that is Internet Server). Your applet will communicate with that server which will fulfill all the requirements of the applet. You can communicate between applet and Java query server using sockets RMI (preferred, as this will return the whole object).

Question 20.
When we give the resize function within an applet then it does not reflect the changes when we see the applet in the IE. Why does this happen?
Answer:
Applets are resized only in applet viewer, not in browsers. Change the applet height/width attributes in the HTML file and refresh IE.

Question 21.
What is the relationship between clipping and repainting?
Answer:
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

Question 22.
How do I load a serialized applet?
Answer:
Instead of specifying the CODE attribute of a <APPLET> tag, you use the OBJECT attribute, as in:

<APPLET 
OBJ ECT=TheApp1et.ser
WIDTH=300 
HEIGHT=300 
>
</APPLET>

This allows you to pre-initialize your applet to some saved state, instead of having to reinitialize your applet each time it is loaded.

Question 23.
“Why does it take so much time to access an Applet having Swing Components the first time?
Answer:
Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.

Question 24.
Which method is called by the Applet class to load an image?
Answer:
getImage(URL object, filename) is used for this purpose.

 

Java Swing Interview Questions in Java

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

Java Swing Interview Questions in Java

Question 1.
Why swing is not thread-safe?
Answer:
The Swing API was designed to be powerful, flexible, and easy to use. In particular, we wanted to make it easy for programmers to build new Swing components, whether from scratch or by extending the components that we provide. For this reason, we do not require Swing components to support access from multiple threads. Instead, we make it easy to send requests to a component so that the requests run on a single thread.

Question 2.
Which package has lightweight components?
Answer:
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame, and JWindow are lightweight components.

Question 3.
What are peerless components?
Answer:
The peerless components are called lightweight components.

Question 4.
What is the difference between the Font and FontMetrics classes?
Answer:
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

Question 5.
What is the difference between Swing and AWT components?
Answer:
AWT components are heavy-weight, whereas Swing components are lightweight. Hence Swing works faster than AWT. Heavyweight components depend on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component. Pluggable look and feel possible using java Swing. Also, we can switch from one look and feel to another at runtime in swing which is not possible in AWT.

Question 6.
Name the containers which use Border Layout as their default layout?
Answer:
window, Frame, and Dialog classes.

Question 7.
Name Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 8.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 9.
What is the difference between the paint() and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 10.
Which package has lightweight components?
Answer:
javax.The swing package contains lightweight components. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.

Question 11.
What are peerless components?
Answer:
The peerless components are called lightweight components.

Question 12.
What is a Container in a GUI?
Answer:
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

Question 13.
How are the elements of a GridBagLayout organized?
Or
What is a layout manager and what are the different types of layout managers available in java Swing?
Or
How are the elements of different layouts organized?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using

the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements may be different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 14.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

Question 15.
What method is used to specify a container’s layout?
Answer:
The setLayout( ) method is used to specify a container’s layout. For example, setLayout(new FlowLayout( )); will be set the layout as FlowLayout.

Question 16.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 17.
Name Component subclasses that support painting.
Answer:
The Canvas, Frame, Panel, and Applet classes support painting.

Question 18.
What is the purpose of the enableEvents() method?
Answer:
The enableEvents( ) method is used to enable an event for a particular component. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

Question 19.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

Question 20.
What do heavy-weight components mean?
Answer:
Heavyweight components like Abstract Window Toolkit (AWT) depend on the local windowing toolkit. For example, java.awt .The button is a heavy-weight component.

Question 21.
What is the difference between a Scrollbar and a ScrollPane?
Answer:
A Scrollbar is just a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Question 22.
What is the preferred size of a component?
Answer:
The preferred size of a component is the minimum component size that will allow the component to display normally.

Question 23.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and Applet classes use the FlowLayout as their default layout.

Question 24.
What is Event-Driven-Thread (EDT) in Swing?
Answer:
Event-Driven-Thread or EDT is a special thread in Swing and AWT. Event-Driven Thread is used to draw graphics and listen for events in Swing. You will get a bonus point if you are able to highlight that time-consuming operation like connecting to the database, opening a file, or connecting to the network should not be done on the EDT thread because it could lead to freezing GUI because of blocking and time-consuming nature of these operations instead of the,’ should be done on a separate thread and EDT can just be used to spawn those thread on a button click or mouse click.

Question 25.
Does Swing is thread-safe? What do you mean by swing is not thread-safe?
Answer:
Since Swing components are not thread-safe it means you cannot update these components in any thread other than Event-Driven-Thread. If you do so you will get unexpected behavior. Some time interviewer will also ask what are thread-safe methods in swing which can be safely called from any thread only a few like repaint( ) and revalidate( )

Question 26.
What are the differences between Swing and AWT?
Answer:
There is a couple of differences between swing and AWT:

  1. AWT components are considered to be heavyweight while Swing components are lightweights
  2. Swing has a pluggable look and feel.
  3. AWT is platform depended same GUI will look different on the different platforms while Swing is developed in Java and is platform-dependent.

Question 27.
Why Swing components are called lightweight components?
Answer:
AWT components are associated with native screen resources and called heavyweight components while Swing components use the screen resource of an ancestor instead of having their own and that’s why called lightweight or lighter components.

Question 28.
What is the difference between invokeAndWait and invokeLater?
Answer:
Sometimes the question is how do you update the swing component from a thread other than EDT, for such kind of scenario we use SwingUtilities. invokeAndWait(Runnable r) and SwingUtilities.invoke setter(Runnable r) though there are quite a few differences between these two, the major one is invokeAndWait is a blocking call and wait until GUI updates while invokeLater is a nonblocking asynchronous call. In my opinion, these question has its own value and every swing developer should be familiar with these questions or concept not just for interview point of view but on application perspective, you can read more on my post How InvokeAndWait and InvokeLater works in Swing

Question 29.
Write code for JTable with custom cell editor and custom cell Tenderer?
Answer:
JTable is one of the favorite topics of all Swing interviews and the most popular questions on swing interviews are from JTable why? Because here interviewer will directly ask you to write code another reason is JTable heavily used in all Electronic TRADINGS GUI. GUI used for online stock TRADINGS uses JTable to show data in tabular format so an in-depth knowledge of JTable is required to work on ONLINE TRADING GUI developed in Swing. While this question is just an example questions around JTable are mostly centered around updating the table, how do you handle a large volume of data in the table, using customize cell Tenderer and editor, sorting table data based on any column, etc. so just make sure you have done quite a few handsome exercises on JTable before appearing for any java swing interview in IB.

Question 30.
Write code to print following layout (mainly focused on GridBag layout)?
Answer:
GridBagLayout in the swing is the most powerful but at the same time, most complex layout and a clear-cut experience and expertise around GridBagLayout is desired for developing Swing GUI for trading systems. No matter whether you are developing GUI for equities trading, futures, or OPTIONS TRADING or forex trading you always required GridBagLayout. Swing interview question on GridBagLayout will be mostly on writing code for a particular layout just like an example shown here. In which six buttons A, B, C, D, E, and F are organized in a certain fashion.

Question 31.
How do you handle the opening of a database, file, or network connection with a click of a button?
Answer:
You should not do this operation in the EDT thread instead spawn a new thread from the actionListener or button and disable the button until the operation gets completed to avoid resubmitting the request. The only condition is that your GUI should always be responsive no matter what happens on a network connection or database connection because these operations usually take time.

Event Handling Interview Questions in Java

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

Event Handling Interview Questions in Java

Question 1.
What are the advantages of the model over the event-inheritance model?
Answer:
The event-delegation model has two advantages over the event-inheritance model. They are:

a) It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.

b) It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events as is the case of the event inheritance.

Question 2.
What are source and listener?
Answer:
Source: A source is an object that generates an event. This occurs when the internal state of that object changes in some way.
Listener: 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.

Question 3.
What is adapter class?
Answer:
An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( )and mouseMoved( ).

The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged( ).

Question 4.
What is an event and what are the models available for event handling?
Answer:
An event is an event object that describes a state of change in a source. In other words, an event occurs when an action is generated, like pressing a button, clicking the mouse, selecting a fist, etc.
There are two types of models for handling events and they are:

a) event-inheritance model and
b) event-delegation model

Question 5.
What are the advantages of the model over the event-inheritance model?
Answer:
The event-delegation model has two advantages over the event-inheritance model. They are:

a) It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.

b) It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events as is the case of the event inheritance.

Question 6.
what is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?
Answer:
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

Question 7.
What is the highest-level event class of the event-delegation model?
Answer:
The java. util.EventObject class is the highest-level class in the event- delegation class hierarchy.

Question 8.
What event results from the clicking of a button?
Answer:
The ActionEvent event is generated as the result of the clicking of a button.

Question 9.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 10.
What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?
Answer:
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on until the highest-level container has been tried. In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.

Question 11.
What is the purpose of the enableEvents( ) method?
Answer:
The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

Question 12.
What interface is extended by AW^T event listeners?
Answer:
All AWT event listeners extend the java. util.EventListener interface.

Question 13.
How can a GUI component handle its own events?
Answer:
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

Question 14.
What is the purpose of the enableEvents( ) method?
Answer:
The enableEvents( ) method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents( ) method is used by objects that handle events by overriding their event-dispatch methods.

SQL Server Interview Questions and Answers for .Net Developers

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

SQL Server Interview Questions and Answers PDF Free Download for .Net Developers

Question 1.
What is Microsoft SQL Server?
Answer:
The Microsoft relational database management system is a software product that primarily stores and retrieves data requested by other applications. These applications may run on the same or a different computer. SQL is a special-purpose programming language designed to handle data in a relational database management system. A database server is a computer program that provides database services to other programs or computers, as defined by the client-server model. Therefore, a SQL Server is a database server that implements the Structured Query Language (SQL). SQL Server is a central part of the Microsoft data platform. SQL Server is an industry leader in operational database management systems (ODBMS).

Question 2.
What is Database?
Answer:
A database is a collection of information that is organized so that it can be easily accessed, managed and updated. Computer databases, typically contain aggregations of data records or files, containing information about sales transactions or interactions with specific customers.

Question 3.
Write Advantage of DBMS?
Answer:
The following advantage of DBMS in SQL Server.

  • The amount of data redundancy in-store data can be reduced.
  • Store data can be shared by single or multiple users.
  • Data abstraction and independence & Data Security
  • The ability to swiftly recover from crashes and errors, including restorability and recoverability
  • Simple access using a standard application programming interface (API)
  • Uniform administration procedures for data

Question 4.
What is Normalization Explain?
Answer:
Normalization is a process that helps analysts or database designers to design table structures for an application. The focus of normalization is to attempt to reduce redundant table data to the very minimum. Through the normalization process, the collection of data in a single table is replaced, by the same data being distributed over multiple tables with a specific relationship being set up between the tables.

First Normal Form (INF) :
A relation is in INF if it contains an atomic value.
Ex: Sample Employee table, it displays employees are working with multiple departments.

Employee Age Department
Melvin 30 Marketing
Melvin 30 Sales
Edward 40 Quality Assurance
Melvin 30 Marketing, Sales
Edward 40 Quality Assurance
Jay 35 Human Resource
Jay 35 Human Resource

Second Norma! Form (2nd NF):
A relation will be in 2NF if it is in INF and all non-key attributes are fully functional dependent on the primary key
Ex: The entity should be considered already in INF, and all attributes within the entity should depend solely on the unique identifier of the entity.

Sample Products table:

Product ID Product Brand
1 Monitor Apple
2 Monitor Acer
3 Scanner HP
4 Head Phone Nokia

product table following 2NF:
products Category table:

Brand table:

Product ID Product
1 Monitor
2 Scanner
3 Head Phone
BrandID Brand
1 Apple
2 Acer
3 HP
4 Nokia

Product Brand table:

Pb ID Product ID Brand ID
1 1 1
2 1 2
3 2 3
4 3 4

SQL Server Interview Questions and Answers for .Net Developers chapter 3 img 1

Third Normal Form(NF3): A relation will be in 3NF if it is in 2NF and no transition dependency exists. The entity should be considered already in 2NF, and no column entry should be dependent on any other entry (value) other than the key for the table. If such an entity exists, move it outside into a new table. 3NF is achieved considered as the database is normalized. The BCNF, 3NF, and all tables in the database should be only one primary key.

Fourth Normal form(NF4): Tables cannot have multi-valued dependencies on a Primary Key.

Fifth Normal Form(NF5): A relation is in 5NF if it is in 4NF and not contains any join dependency and joining should be lossless.

Question 5.
What is the difference between a duplicate table and a cloning/coping table in SQL Server?
Answer:
Cloning may be a situation when you just want to create an exact copy or clone of an existing table to test or perform something without affecting the original table. The data copy returns a database with the structure and datable. Ex:

Datatable dt_copy = new Datatable();
Dt.Table name = “Copy table”;
dt_copy = it.copy( );
The clone will copy the structure of a data whereas Copy will copy the complete structure as well as data.

You can duplicate an existing table in SQL Server 2017 by using SQL
Server Management Studio or Transact-SQL by creating a new table
and then copying column information from an existing table.

Question 6.
What is the difference between “•Between” Operator & “IN” Operator in SQL Server?
Answer:
The BETWEEN operator selects a range of data between two values can be number text (Range) etc. Ex: Select * from abx where marks between 50 and 80;
The IN operator allows you to specify multi values.

Ex. Select * from abd where marks EM (89,82);

Question 7.
What is the difference between Temp Table & Table variable in SQL Server?
Answer:

SL Temp Table Table Variable
1 The temp table is created in tempdb database Table variable (@table) is crated in the memory.
2 The temp table is shown in a table variable. Table variable can’t involve transaction logging or locking.
3 Temp table allows creating Index Table variable can’t allow Index.
4 Temp table can’t pass SP & function Table variable can pass SP & function.
5 Temporary tables are visible in the created routine and also in the child routines. Table variables are only visible in the created routine

Question 8.
How to bulk data upload in SQL Server types of process Explain?
Answer:
BCP Utility: A command-line utility (Bcp.exe) that bulk exports and bulk imports data and generates format files.
BULK INSERT Statement: A Transact-SQL statement that imports data directly from a data file into a database table or no partitioned view.
SQL Server Import & Expert Wizard: The wizard creates simple packages that import and export data between many popular data formats including databases, spreadsheets, and text files.

Question 9.
Difference between function & Store procedure in SQL Server.
Answer:

Store Procedure Function
SP can return Zero, single or multiple values. The function must return a single value

(were maybe a scalar or a table).

SP can use input & output parameters both Function can’t have input parameter.
SP can’t call function. The function can call SP.
SP is DML command (Insert, update & delete) Function is DML command only single value.
SP can’t use where and having statement. The function can use Where/Select & having statement.
We can use exception handling try & catch statement in SP Function can’t use try-catch statement.
We can use transactions in SP. Function can’t use transaction.

Question 10.
What is the SOLID Principle?
Answer:
SOLID are five basic principles that help to create good software architecture. SOLID is an acronym where: –

  • S stands for SRP (Single responsibility principle
  • O stands for OCP (Open closed principle)
  • L stands for LSP (Liskov substitution principle)
  • I stand for ISP (Interface segregation principle)
  • D stands for DIP (Dependency inversion principle)

Question 11.
What is Transaction in SQL Server?
Answer:
A Transaction is a unit of work that is perforated against a database. A transaction is the propagation of one or more changes to the database example if you are creating records, delete, changes, and update from the table you are performing transactions.
Transaction control:

  • Commit: to save the changes
  • Rollback: to roll back the changes.
  • Save Point: creates points within the group of transactions in which to roll back.
  • Set Transaction: Place a name on a transaction.

Question 12.
Write different between Cluster Index & Non-Cluster Index?
Answer:
Cluster index defines the order in which data is physically stored in a table data can be sorted in only one way, therefore, they can be only one cluster index per table. The primary key constraint automatically creates a clustered index on a particular column.
Non-Cluster Index doesn’t sort the physical data inside the table. Non cluster index is sorted at one place and table data is sorted in another place. Like your textbook content is located in one place and index is located in another place. This allows for more than one non-cluster index per table. The non-cluster index is slow the clustered index.

Ex: create nonclustered index ABC Name ON Student (name ASC)

It’s useful for improved query performance & searching data in SQL Server.

Question 13.
Different between Having & Where in SQL Server?
Answer:
The Where is coming before Group by where having is used to check condition after the aggression task. Where is used for filtering row and it applies enhanced every row while having used grouping filter.

Question 14.
What is common table expression(CTE)?
Answer:
A Temporary name result set knows as a common table expression(CTE). The simple query and defined within the execution scope of a single select, Insert, Update, Delete or Merge statement.

Ex: Syntax

With Expression Name (Column 1, Column2)
(
CTE query definition
)
Select column form expression name.

Advantage of CTE:

  • Can be used to create a recursive query.
  • Can be substituted for a view.
  • Can reference itself multiple Items.

Question 15.
The difference between Primary Key, Unique Key, Foreign Key?
Answer:

Primary Key Unique Key Foreign Key
Primary Key can’t have a null value Unique Key may have a null value. A foreign key is a field in the table that is the primary key in another table.
Each table has one primary key. Each table has more than one unique key. A foreign key can accept multiple null values.
By default primary key is the clustered index. By default, the Unique key is a nonclustered index. Foreign key doesn’t create cluster or non-cluster index.
The support Auto Incremental value. They don’t support We can have more than one foreign key in the table.

Question 16.
How to Query optimize in SQL Server?
Answer:
The following method of SQL Query Optimize is given below:
Do not use the * operator in your SELECT statements. Instead, use column names, because SQL Server scans for all column names and replaces the * with all the column names of the table)s) in the SQL SELECT statement.

• Do not use NOT IN when comparing with Nullable columns. Use NOT EXISTS instead.

Do not use table variables in joins. Use temporary tables, CTEs (Common Table Expressions), or derived tables in joins instead. Even though table variables are very fast and efficient in a lot of situations, the SQL Server engine sees it as a single row. Due to this, they perform horribly when used in joins. CTEs and derived tables perform better with joins compared to table variables.

Do not begin your stored procedure’s name with sp_. Because the stored procedure is named sp or SP, SQL Server always checks in the system/master database even if the Owner/Schema name is provided.

• Avoid using a wildcard (%) at the beginning of a predicate. The predicate LIKE ‘%abc’ causes a full table scan, For example: Select from table 1 where coll like ‘%likeabc’

• Use inner join, instead of outer join if possible. The outer join should only be used if it is necessary. Using outer join limits the database optimization options which typically results in slower SQL execution

• Avoid using GROUP BY, ORDER BY, and DISTINCT as much as possible. When using GROUP BY, ORDER BY, or DISTINCT, the SQL Server engine creates a work table and puts the data on the work table. After that, it organizes this data in the work table as requested by the query, and then it returns the final result.

Use SET NOCOUNT ON with DML operations. When performing DML operations (i.e. INSERT, DELETE, SELECT, and UPDATE), SQL Server always returns the number of rows affected. In complex queries with a lot of joins, this becomes a huge performance issue.

Question 17.
What is Identity? How many types of Identity are in SQL Server?
Answer:
An Identity column of a table is a column whose value increases automatically. The value in an identity column is created by the server. A user generally can’t insert a value into an identity column.

Syntax: Identity [(Seed, Increment)]

Seed – Starting value of column default value is 1.
Increment – It’s the Increment value that is added to the identity value of the previous row that was loaded. The default value is 1.

  • Identity Inserted ON – Allow a user to insert data into an identity column.
  • Identity Inserted OFF – redirect a user from inserting data into and Identify column.

Question 18.
What are Triggers in SQL? Explain the type of triggers.
Answer:
A Trigger is a special kind of store procedure that automatically executes when an event occurs in the database server. DML (Data Manipulation Language) Trigger execute when a user tries to modify data through (DML) event Insert, Update or delete.

DDL Triggers: SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system-defined stored procedures that perform DDL-like operations.

DML Triggers: SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored procedures that perform DML-like operations. DML Triggers are of two types. After Trigger (using FOR/AFTER CLAUSE) & Instead of Trigger (using INSTEAD OF CLAUSE)

CLR Triggers: CLR triggers are a special type of trigger based on the CLR (Common Language Runtime) in the .net framework. CLR integration of triggers has been introduced with SQL Server 2008 and allows for triggers to be coded in one of.NET language like C#, Visual Basic, and F#.

Login Triggers: Logon triggers are a special type of trigger that fires when the LOGON event of SQL Server is raised. This event is raised when a user session is being established with SQL Server that is made after the authentication phase finishes, but before the user session is actually established.

Example of Insert Trigger:

Create trigger abc on [dbo]. [mytable]
For INSERT As
Declare @ ID int,
Declare @Name varchare(50);
Declate @Audit_Action(50);
Select @ID = j.id from Inserted j;
Select @Name = j.name from Inserted j;
Select @Audit_Action = ‘Inserted Record after triggers’;
Insert into xyzBackupfile (Id,Name,Audit Action,Audit time)
values(@id,@name,@audit_action,GetDate());
Print ‘Trigger Inserted sucessfully’;

Question 19.
What is Scaler function in SQL Server?
Answer:
SQL Server scalar function takes one or more parameters and returns a single value. The scalar functions help you simplify your code. For example, you may have a complex calculation that appears in many queries. Instead of including the formula in every query, you can create a scalar function that encapsulates the formula and uses it in the queries.\

Ex:
CREATE FUNCTION [schema_name.]function_name (parameter_list)
RETURNS data type AS
BEGIN
statements
RETURN value
END

Question 20.
What is the difference between the # & @ table in SQL Server?
Answer:
# table refers to a local variable (visible to only users who created it) temporary table.
## table refers to a global temporary table (display all users).
@ variable name refer to a variable that can hold value depending on its size.

Question 21.
What is function Explain?
Answer:
A function is a database object in SQL Server. Basically, it is a set of SQL statements that accept only input parameters, perform actions and return the result. A function can return only a single value or a table. We can’t use a function to Insert, Update, Delete records in the database tables.
System Defined Function

 Scaler function: Scalar functions operates on a single value and return a single value.
Example: rand, round, upper, lower, trim, convert

Aggregation function: SQL Server aggregate functions perform a calculation on a set of values and return a single value. With the exception of the COUNT aggregate function, all other aggregate functions ignore NULL values.
Example :

  1. min( ),
  2. max( ),
  3. ave( ),
  4. Count( ).

User Define function: These functions are created by the user in the system database or in the user-defined database. There are 3 types of user define function scaler function, table-valued function & System

Question 22.
What is SQL Injection?
Answer:
SQL Injection is a code injection technique that might destroy your database. SQL Injection is one of the most common web hacking techniques. SQL injection is the placement of malicious code in SQL statements, via web page input.

Question 23.
What are Constraints in SQL Server explain?
Answer:
The Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted. Constraints can be column level or table level. Column level constraints apply to a column, and table-level constraints apply to the whole table.

Example:

  • NOT NULL – Ensures that a column cannot have a NULL value
  • UNIQUE – Ensures that all values in a column are different
  • PRIMARY KEY – A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
  • FOREIGN KEY – Uniquely identifies a row/record in another table
  • CHECK – Ensures that all values in a column satisfy a specific condition
  • DEFAULT – Sets a default value for a column when no value is specified
  • INDEX – Used to create and retrieve data from the database very quickly.

Question 24.
What is Rollback in SQL Server?
Answer:
We can undo a single or even multiple consecutive written and delete operations. the command used rollback in SQL server.
Ex:

SQL> DELETE FROM CUSTOMERS WHERE AGE = 25;
SQL> COMMIT;
SQL> Rollback;
SQL> select * from customer;

Question 25.
The difference between delete & truncate?
Answer:

SL Truncate Delete
1 TRUNCATE is a DDL command DELETE is a DML command
2 TRUNCATE is executed using a table lock and the whole table is locked to remove all records. DELETE is executed using a row lock, each row in the table is locked for deletion.
3 We cannot use the Where clause with TRUNCATE. We can use the where clause with DELETE to filter & delete specific records.
4 TRUNCATE removes all rows from a table. The DELETE command is used to remove rows from a table based on the WHERE conditions.
5 Minimal logging in the transaction log, so it is performance-wise faster. It maintains the log, so it is slower than truncates.
6 To use Truncate on a table you need at least ALTER permission on the table. To use Delete you need DELETE permission on the table.
7 Truncate uses less transaction space than Delete statement. Delete uses more transaction space than a Truncate statement.
8 Truncate cannot be used with an indexed view The delete can be used with indexed views

Question 26.
What is PIVOT & UNPIVOT Explain?
Answer:
The PIVOT and UNPIVOT relational operators change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. PIVOT runs aggregations, where they’re required on any remaining column values that are wanted in the final output UNPIVOT, carries out the opposite operation to PIVOT by rotating columns of a table-valued expression into column values in SQL Server.

Question 27.
What is Join Explain?
Answer:
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.
There is 4 type of joins

  1. Inner Join,
  2. Outer Joins,
  3. Cross Joins.

1) Inner Join: Returns records that have matching values in both tables.
Syntax:SELECT column name(s)¥RON[ ta/)/e/INNER JOIN table2 ON table 1 .column jiame = table2.column _name\

2) Outer Join:

• Left Outer Join: Returns all records from the left table, and the matched records from the right table
Syntax.SELECT column_name(s)F7?0M table 1 LEFT JOIN table2
ON table 1 .column_name = table2.column_name;

• Right Outer Join: Returns all records from the right table, and the matched records from the left table
Syntax.SELECT column_name(s)F/?6W table 1 RIGHT JOIN table2
ON table 1 .column jiame = table2.column jiame;

• Full outer Join: Returns all records when there is a match in either the left or the right table.
Syntax:SELECT column_name(s)Fi?OM table IFULL OUTER JOIN la. ble2
ON table l.columnname = table2. column jiame WHERE condition;

3) Cross Join (Cartesian Product): A result set which is the number of rows in the first table multiplied by the number of rows in the second table if nowhere clause is used along with cross join.

Syntax: Select * from table 1 corss join table2;

SQL Server Interview Questions and Answers for .Net Developers chapter 3 img 2

Question 28.
How can SQL Injection be stopped?
Answer:
The following process of SQL Injection prevention is given below:

  • Validate the SQL commands that are being passed by the front end.
  • Validate the length and data type per parameter.
  • Convert dynamic SQL to stored procedures with parameters.
  • Prevent any commands from executing with the combination of or all of the following commands: semi-colon, EXEC, CAST, SET, two dashes, apostrophe, etc.
  • Based on your front end programming language determine what special characters should be removed before any commands are passed to SQL Server
  • Depending on the language this could be a semi-colon, dashes, apostrophes, etc.
  • Prevent traffic from particular IP addresses or domains & See if email-based alerts can be sent if traffic comes from these sources
  • Review the firewall settings to determine if SQL Injection attacks can be prevented

Question 29.
What do Database Encryption and Decryption mean?
Answer:
Database encryption is the process of converting data, within a database, in plain text format into a meaningless cipher text by means of a suitable algorithm.
Database decryption is converting the meaningless ciphertext into the original information using keys generated by the encryption algorithms.

Question 30.
What is a Symmetric-key in the Data encryption process?
Answer:
In the Symmetric cryptography system, the sender and the receiver of a message share a single, common key that is used to encrypt and decrypt the message. This is relatively easy to implement, and both the sender and the receiver can encrypt or decrypt the messages.

Question 31.
What key provides the strongest encryption in SQL Server DBA?
Answer:
Used AES (256 bit)

  • If we choose a longer key, then encryption will be better, so choose longer keys for more encryption. However, there is a larger performance penalty for longer keys. DES is a relatively old and weaker algorithm than AES.
  • AES: Advanced Encryption Standard
  • DES: Data Encryption Standard

Question 32.
How to find the 2nd Highest salary in the table?
Answer:
Select distinct salary from emp el where 2 = select count(distinct salary) from emp e2 where el.salary=e2.salary;
Or
(DEN SE_RANK Method)
Select a.name, s.salary from (select name, salary, DENSE RANK()
over (ORDER BY Salary) As RK from personal) as a where rk = 3;

Question 33.
How to delete all duplicate records in SQL Server?
Answer:
Delete from emp where id in (select id emp GroupBy e id having count (*) >1); ‘

Question 34.
How to update Male = Female & Female = Male in SQL Server;
Answer:
update emp set gender = case gender were ‘male’ then ‘female’ when ‘female’ than ‘male’ else gender END;

Question 35.
How do find the last records from the table?
Answer:
Select * from emp where id = select max (id) from emp;

Question 36.
How do find 1st five records from the table?
Answer:
Select * from emp where ROWNUM <= 5;

Question 37.
How do find the last 5 records from the table?
Answer:
Select * from e where ROWNUM <=5 union select * from (select * from emp e Order by Desc.) where ROWNUM <=5;

Question 38.
How do find the 3 highest salaries from the table?
Answer:
Select distinct salary from emp el where 3>= select counts (distinct salary) from emp2 where el. salary <= e2. salary order by el. salary disc;

Question 39.
How to create a clone table in SQL Server?
Answer:
create table ABC as select * from emp where 1=2;

Question 40.
How to delete all duplicate records from the table?
Answer:
Delete from emp where id in select id emp Group by E id having count (*)> 1;

Question 41.
How do find out the maximum salary of each department?
Answer:
Select Deptid Max(Salary) from emp Group By Deptid;

Question 42.
How do I fetch only common records between 2 tables?
Answer:
Select from emp Intersect select from empl;

Question 43.
Find out monthly salary from the table?
Answer:
Select emp name salary/12 as ‘monthly’ from EMP;

Question 44.
Write benefits of Store Procedure with Example?
Answer:
The following benefit as given below:

  • Reduced amount of information sent to the database server.
  • Compilation step is required only once when the store procedure used means one-time compilation required.
  • Re-Usability of code means multiple clients can have used the same code.
  • Helpful for enhancing the system security since we can grant permission to the users for executing the store procedure.
  • Helpful for your business logic.
  • Save time for coding.

Example:
/* This store procedure is used to insert a value into the table “Mapa” */

Create Procedure record
(
@ Name varchar (20),
@Age int,
@Sex char (1)
) 
As
Begin
Insert into Mapa(Name,Age,Sex) Values(@Name,@Age,@Sex)
END

Question 45.
Write Example of Index with Syntax?
Answer:
Syntax of Index:
CREATE INDEX Index name ON Table Name (Column1,Column2….);
Example My Table name is Emp:
CREATE INDEX Salarylndex ON Emp (Salary, Age);

Question 46.
Write Cluster Index Example?
Answer:
Example Table Name is EmpRecords:

CREATE TABLE [EmpRecord]
(
[EmpKey] [int] NOT NULL PRIMARY KEY,
[Name] [varchar](50) NOT NULL ,
[Email] [nvarchar](50) NULL,
[Profession] [nvarchar]( 100) NULL,
[Yearly Income] [money] NULL
)

Details you can check by using: EXECUTE SP_HELP EmpRecord

Question 47.
Write a Syntax of Constraint in SQL Server with Example?
Answer:
Constraint “Constraint Name” “Constraint definition” Example:

  • Unique Constraint: “column name” datatype<size> unique
  • Not null Constraint: “column name” datatype<size> not null
  • Check Constraint: “column name” datatype<size> checkdogical expression>
  • Default Constraint: “column name” datatype<size> Default <value> constraint definition.

Question 48.
Date function in SQL Server, write a Query to Add after the 4-month date of March 2019?
Answer:
Select ADD_Month(SYSDATE,4) “Next Month” from XYZ;
Output: Next Month: 01-Aug-19

Question 49.
Calculate last day in month SQL Server?
Answer:
Select SYSDATE, LAST DAY(SYSDATE) “NewDay” from XYZ;
Output: SYSDATE:01-Jul-19 & NewDay:31-Jul-19.

Question 50.
Calculate the Month between (Ol-May-19 to 30-Oct-19) in SQL server?
Answer:
Select Months Between (’01-MAY-19′ , ’30-OCT-19′)”Total Month ” from ABC.

Question 51.
in SQL Server?
Answer:
Select Months Between(’01-MAY-19’,’30-OCT-19’) “Total Month” from ABC;
Output: Total Month: 6

Question 52.
How to calculate Next day in SQL Server in Date function?
Answer:
Select NEXT_DAY (’14-Oct-19’,’ Monday’) “Next Week” from Apple;
Output: Next Week: 21-Oct-19

Question 53.
Write a Syntax of time Zone? Answer:New_Time(date, Zonal,zone2)
Example:
SELECT EID, EMPJoiningDate,
EMPJoiningDate AT TIME ZONE ‘Pacific Standard Time’ AS
EMPJoiningDate TimeZonePST
FROM EMP.EMPEnterHeader;

Question 54.
What are used Rollup Operators?
Answer:
The Rollup operator is used to calculate aggregates and super aggregates expression in the group by statement. The Rollup option allows you to include extra rows that represent the subtotals, which are commonly referred to as super-aggregate rows, along with the grand total row. ROLLUP (Ml, M2, M3) creates only four grouping sets, assuming the hierarchy Ml > M2 > M3, as follows

Syntax: Select Ml,M2,M3 aggregate function(p4) from tablename GROUP BY ROLLUP (Ml,M2,M3);

Question 55.
What is Sub Query Explain with Example?
Answer:
The Subquery is a query set inside of another SQL Statement. It’s a nested query inside select, insert, update and delete statements. A subquery can be used anywhere an expression is allowed. We can also use where & having condition. The DISTINCT keyword & COMPUTE and INTO clauses cannot be used with subqueries that include GROUP BY.

Example:
Select * from SalDetail
where sal_add IN(select dept_add from dept where dept name – finance’)

Question 56.
Write Query of Not Exists in SQL Server?
Answer:
SELECT StudentID, ProductName FROM Student p WHERE NOT EXISTS (SELECT * FROM [Student Details] od WHERE p.Studentld = od.Studentld)

Question 57.
Write a triggered update & delete in SQL Server?
Answer:
Update after Trigger Example as given below:

Create Trigger abc as on [dbo].[mytable]
For UPDATE As
Begin
Declare @id int;
Declare @name varchar (20);
Declare @Audit_Time (60);

Select @id = j.Id from Inserted j;
Select @Name = j.Name from Inserted j;
Select @Audit_Time = Updated Record – After Updated Trigger;

Update into MPGbackup (id,Name.Audit Time) values(@id,@Name, @Audit_time ,GetDate());
Print ‘Trigger Updated Successfully’
–Acb is table name, MPGbackup is backup file name

Example of Delete after Trigger as given below:

Delete Trigger abc as on [dbo].[mytable]

For UPDATE As
Begin
Declare @id int;
Declare @name varchar (20);
Declare @Audit_Time (60);

Select @id = j.Id from deleted j;
Select @Name = j.Name from deleted j;
Select @Audit_Time = Record Deleted – After Updated Trigger;

Insert into MPGbackup (id,Name.Audit_Time) values(@id,@Name,@Audit_time,GetDate());
Print ‘Trigger Deleted Successfully’

– -Acb is table name, MPGbackup is backup file name

Question 58.
Write Case Statement in SQL Server with Example?
Answer:Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition3 THEN result3
WHEN condition4 THEN result4
WHEN condition THEN resultN
ELSE result
END;

Example:

SELECT EmpID, EmpAge,
CASE WHEN EmpAge > 40 THEN “The employee is greater than 30”
WHEN EmpAge = 30 THEN “The Age is 30”
ELSE “The Age is under 30”
END AS EmpText FROM EmployeeDetails; ‘

26) Give me Example of a Function in SQL Server?
Answer:
Example 1: User Define a function

CREATE FUNCTION dbo. Stock1(@ItemID int)
RETURNS int AS
— Returns the Store Inventory level for the product.
BEGIN
DECLARE @ret int;
SELECT @ret = SUM(r.Quantity)
FROM Production.Productlnventory r WHERE r. ItemID = @ItemID AND r.Location® = ‘6’;
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;

Example 2: The Example of Scaler Function

SELECT student id, SUM(sales.udfNetSale(quantity, list_price, dis count))
net amount FROM sales.orderitems
GROUP BY order_id
ORDER BY net_amount DESC;

Question 59.
Find 3rd Highest salary using Rank Method?
Answer:
Select * from (Select Dense Rank() over ( order by salaryl desc)
as Rnk,E.* from Employee E) where Rnk=3;

Question 60.
How to get a Distinct Record without using distinct keywords?
Answer:
Select * from Student a where rowid = (select max(rowid) from
Student b where a.Student_ID =b. Student_ID);

Question 61.
How to remove duplicate rows from the table?
Answer:
Select EID FROM Employee WHERE ROWID <>
(Select max (rowid) from Employee b where EID=b.EID);

Delete duplicate rows:

Delete FROM Employee WHERE ROWID
(Select max (rowid) from Employee b where EID =b. EID);

Question 62.
How to fetch duplicate records from the table?
Answer:
SELECT Empld, Name, Salary, COUNT(*)
FROM EmpSalary
GROUP BY Empld, Name, Salary
HAVING COUNT(*)> 1;

Question 63.
Write a SQL query to fetch top n records?
Answer:
Select Top N * from Manager Order By Salary DESC;

Question 64.
What is Cursor, Explain?
Answer:
The SQL Server Query basically works on a complete set like Select Statement & as per Where condition. Sometimes you may want to process a data set on a row by row basis. This is where cursors come into play. Here we can use cursors.
Type of cursor in SQL Server:

  • Forward Only
  • Static
  • Keyset
  • Dynamic

Syntax:

DECLARE cursor name CURSOR [ LOCAL | GLOBAL ] [ FORWARD ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | LAST LORWARD]
[ READ-ONLY | SCROLL_LOCKS | OPTIMISTIC]
[ TYPEWARNING ] FOR select statement
FOR UPDATE [coll,col2,…coln]
—define columns that need to be updated

Question 65.
What is Collection in SQL Server?
Answer:
According to Microsoft Definition “A collection is a list of objects that have been constructed from the same object class and that share the same parent object. The collection object always contains the name of the object type with the Collection suffix. Lor example, to access the columns in a specified table, use the ColumnCollection object type.”

Question 66.
Explain the locks in SQL Server and type of locks?
Answer:
The Lock is used for security purposes and to prevent data from being corrupted by the database. The locks are used to implement concurrency control when multiple users access the Database to manipulate its data at the same time.
Lock Mode as given below:

• Shared(S) – The Shared Mode is used for reading operations that do not change or update data, such as a SELECT statement.
• Exclusive(X) – The Exclusive Mode used for data- modification operations, such as INSERT, UPDATE, or DELETE. Ensures that multiple updates cannot be made to the same resource at the same time.
• Intent – The Intent used to establish a lock hierarchy. The types of intent locks are: intent shared (IS), intent exclusive (IX), and shared with intent exclusive (SEX).
• Bulk Update – We can have updated bulk data lock mode Tab Lock.

Question 67.
Write a Query of Bulk(BCP) data uploaded in SQL Server?
Answer:
create table Customer (id int,
name varchar(60),
Age int,
email varchar(60))

Now we will load the data using the BULK INSERT statement & We have CVS file with bulk data:

BULK
INSERT Customer
FROM 'c:\sql\mycustomers.CSV
WITH
(
FIELDTERMINATOR = ROWTERMINATOR = '\n'
)

Question 68.
Query Data Received from server Syntax with getting Method Example?
Answer:

<!DOCTYPE html>
<html>
<head>
<script
       src="https ://aj ax. googleapis. com/aj ax/libs/j query/3.4.1/j query. mi 
       n.j s'"></script><script>
$(document).ready(function() {
$("button").click(function() {
  $.get("demo_test2.asp", fimction(data, status){
    alert("Data: " + data+ "YnStatus: " + status);
}); '
});
});

</script>
</head>
<body>

<button>Send an HTTP GET Method</button>
</body>
</html>

Question

Question 69.
JQuery Method Post Method data in SQL Server Example?
Answer:

<!DOCTYPE html>
<html>
<head>
<script
         src= "https ://aj ax.googleapis. com/aj ax/libs/j query/3.4.1/j query .mi n.js"></script>
<script> .
$(document).ready(function() {
$('"button"). click(function() {
  $ .post(" demotest 1 _post.asp",
  {

   name: "Tom", 
   city: "Rome"
   },
   function(data,status){
   alert("Data: " + data + "\nStatus: " + status);
   });
   });
   });
</script>
</head>
<body>
<button>Send an HTTP POST Method</button>
</body>
</html>

Question 70.
Write a JQuery Load Data Method?
Answer:
Just add the code in JQuery as per your txt file name.

<script>
$(document).ready(function() {
$("button").click(function() {
$( "#di v 1"). load(" demo_test.txt");
});
});
</script>

Question 71.
Write a Simple code for Ajax Data Request from Serve, Example?
Answer:
The Code as given below for changes in Script File.

<script>
$(document).ready(function() {
$("button").click(function() {
$("#divl ").load("demo_testl .txt");
});
});
</script>

Question 72.
Write List Method in LINQ in MVC?
Answer:

public static void Main( )
{ 
// string collection
IList<string> stringList = new List<string>() { "Dot NET",
"MVC",
"SQL",
"AJAX",
"JQuery"
// LESTQ Query Syntax
var result = from s in stringList
where s.Contains("Interview2") select s;
foreach (var str in result)
{
Console. WriteLine(str);
}
}

Question 73.
Write Group by Query in LINQ Example?
Answer:
string[ ] groupingQuery = {“Banana”, “Apple”, “Grape”, “beans”, “Mango” }; ‘
IEnumerable<IGrouping<char, string» queryFoodGroups = from item in groupingQuery
group item by item[0];

Question 74.
Write an Inner Join Example in LINQ MVC?
Answer:

public static void Main( )
{
// Color collection in table IList<string> strListl = new List<string>() { "Red",
"Yellow",
"Green",
"Blue"
};
IList<string> strList2 = new List<string>() { "Red",
"Yellow",
"Orange",
"Black"
};

var innerJoinResult = strListl Join(// outer sequence

strList2, // inner sequence
str1 => strl, // outerKeySelector
str2 => str2, // innerKeySelector


(strl, str2) => strl);


foreach (var str in innerJoinResult)


{

Console.WriteLine("{0} ", str);
}
}
}

Output: Red, Yellow

Question 75.
Write a Query to skip method in LINQ with the top 4 highest value skip?
Answer:
The LINQ Example is given below:

int[ ] grades = { 58, 80, 68, 40, 100, 200, 150,250 };


IEnumerable<int> lowerGrades =
grades.OrderByDescending(g => g).Skip(4);


Console.WriteLine("All grades except the top three are:");
foreach (int grade in lowerGrades)
{
Console.WriteLine(grade);
}
/*

Output:
All grades except the top three are:
80
68
58
40
*/ ‘

Question 76.
The difference between FirstOrDefault and First in LINQ?
Answer:
The first return First element value from the collection of elements or a sequence. It also returns the first element of sequence when you specified the condition. The First ( ) simply gives you the first one.

The default not showing the first value it’s showing the default value set in LINQ Operation. The default return is null when there is no result, it will not throw an exception.

Question 77.
Write an Anonymous Function Example? Answer: The following example of anonymous:

delegate int func(int r, int s);
static void Main(string[ ] args)
{
func f1= delegate(int r, int s)
{
return r + s;
};
Console.WriteLine(fl(l, 2));
}

Question 78.
How can we achieve Ajax method call using MVC?
Answer:
The Example as given below:
$.ajax({type: ‘POST’,url: ’@Url.Action(“TestLogic”, “MySearch”)’
,data: {listQuize },success: function (response)
{window.location.href = urldata;if (response != null)
{alert(“Search Working”);}
else {alert(“Search Not Working);}},
error: function (response) {}});

Question 79.
Give me Example of Lambda Expression in MVC?
Answer:

delegate int func(int m, int n);
static void Main(string[] args)
{
func fl = (m, n) => m + n;
Console.WriteLine(fl(l, 2));
}

Question 80.
How to find out duplicate Array in the list?
Answer:
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CodingAlgorithms
{
//Given an array of integers, find if the array contains any duplicates.
//This function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
public static class ArrayDuplicates1
{
//Dictionary solution
public static bool ContainsDuplicates(params int[ ] z)
{
Dictionary<int, int> d = new Dictionary<int, int>( );
foreach (int i in z) 
{
if (d.ContainsKey(i))
return true;
else
d.Add(i, 1);

}
return false;
}
}
}

Question 81.
Write a Program to Rotate array to the right given a pivot?
Answer:
Example:

using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;


namespace CodingAlgorithm
{
public static class RotateArrayRight
{ 
//Rotate array to the right of a given pivot
public static int[] Rotate(int[] y, int pivot)
{ 
if (pivot &lt; 0 || y == null)
throw new Exception ("Invalid argument");
pivot = pivot % y.Length;


//Rotate first half
y = RotateSub(y, 0, pivot - 1);


//Rotate second half
y = RotateSub(y, pivot, x.Length - 1);


//Rotate all
y = RotateSub(y, 0, y.Length - 1);

return y;


}
private static int[ ] RotateSub(int[ ] y, int start, int end)
{
while (start &lt; end)
{
int temp = y[start];
y[start] = y[end];
y[end] = temp;
start++;
end - ;
}
return x;
}
} 
}

Question 82.
How to remove duplicates from the sorted linked lists?
Answer:
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace LinkedListAlgorithm
{
partial class LinkedList1
{ 
 //Remove duplicates from a sorted linked list (Assumes nodes contain integers as data)
//Source: https://leetcode.com/problems/remove- duplicates-from-sorted-list/
public void RemoveDuplicates( )
{
Node lag = head;
Node lead = head.Next; ?
while (lead != null)
{
if ((int)lag.Data == (int)lead.Data)
{
lag.Next = lead.Next;
lead = lag .Next;
}
else
{
lag = lag.Next;
lead = lead.Next;
}
}
}
}
}

Question 83.
What is next Number 5,10,19,32,49,70….?
Answer:
The Solution is given below in Bold:
10-5 = 5
19-10 = 9
32-19=13
49-32= 17
70-49=21
?- 70= 25

Question 84.
A trader buys tea for $1200 and sells it for $1500, per sack of tea he makes a profit of $50. How many sacks of tea did he have?
Answer:
Solution:
He might have 6 sacks of sugar,
$1500-$1200 = 300
300/50 = 6

Question 85.
Now we have a committee of 10 men, where the age of all 10 men is the same as it was 4 years ago because an old man is replaced by a young man? Find out how much younger is the new men?
Answer:
Let say the sum of nine men = p and age of old man = R
So its average 4 years before = (p+r)/10
After 4 years let R be replaced by Y
So now avg=(p+4x 10+y)/10
Now, (p+r)/10 = (p+40+y)/10
So in the end you will get z=y+40

So young committee member is 40 years younger than old member

Question 86.
Find the next Series F21, S23, T25, T27, S29, M31,____?
Answer:
Solution: W02

F21: Friday the 21 st.
S23: Sunday the 23rd.
T25: Tuesday the 25th.
T27: Thursday the 27th.
S29: Saturday the 29th.
M31: Monday the 31 st.
Avoiding every other day, the next term must be ‘Wednesday the 2nd’ i.e. ‘W02’

Question 87.
You are given a 6 by 6 grid and asked to start on the top left corner. Now your aim is to get to the bottom right corner. You are only allowed to move either right or down. You must never move diagonally or backward.
Answer:
Solution: 252 Way

Think how symmetric the problem is. Pick up any random cell. Suppose that you took ‘n’ steps in reaching the particular cell above it and ‘m’ steps to reach the particular cell placed left to it. In such circumstances, the number of ways to reach the random cell is equal to the sum of two steps ‘n+m’. Thus, keep that logic in mind and fill out the six by six grid. In that manner, there are 252 ways to get to the destination that is the bottom right step.

Question 88.
You have 100 coins lying flat on a table, each with a head side and a tail side. 10 of them are heads up, 90 are tails up. You can’t feel, see or in any other way find out which side is up. Split the coins into two piles such that there is the same number of heads in each pile.
Answer:
Place 50 coins into two piles on their edges so that both have the same amount of heads in each pile, neither facing up or down.

Question 89.
There are three boxes, one contains only apples, one contains only oranges, and one contains both apples and oranges. The boxes have been incorrectly labeled such that no label identifies the actual contents of the box it labels. Opening just one box, and without looking in the box, you take out one piece of fruit. By looking at the fruit, how can you immediately label all of the boxes correctly?
Answer:

Let’s assume:
box 1 is labeled Oranges (O)
box 2 is labeled Apples (A)
box 3 is labeled Apples and Oranges (A+O)
and that ALL THREE BOXES ARE LABELLED
INCORRECTLY”

If you are picking fruit from box 1

if you pick an Orange:

  • box l’s real label can only be O or A+O
  • box 1 ‘s current label is O
  • since ALL LABELS ARE INCORRECT then box l’s real label can not be O
  • box l’s new label should then be A+O by elimination
  • since ALL LABELS ARE INCORRECT
  • box 2’s label is changed to O
  • box 3’s label is changed to A

Question 90.
If you’re given a Mug/Gallon with a mix of fair and unfair coins, and you pull one out and flip it 3 times, and get the specific sequence heads tails, what are the chances that you pulled out a fair or an unfair coin?
Answer:
If you don’t know how unfair the coins are then you have to compare fair vs. not fair. A fair coin Pf = 1/2 probability of heads or tails and therefore has a 1/(2A3) = 1/8 probability of going HHT. An unfair coin has a probability P*P*(1-P) = 2*(PA2) – (PA3) of going HHT. Integrating across P from 0 to 1, you also get 1/8. Therefore, whether the coin was biased or not, you had an even chance when you got HHT that the coin was fair or not fair (50%). However, if you were to know the distribution of the coins in the jar between fair and not fair, you would be able to estimate the probability the coin was fair based on that distribution.

Question 91.
If you have 2 eggs, and you want to figure out what’s the highest floor from which you can drop the egg without breaking it, how would you do it? What’s the optimal solution?
Answer:
you can say the answer more like, you can drop the egg even from the topmost floor without breaking it. The egg only breaks when it hits the floor.

Question 92.
The probability of a car passing a certain intersection in 20-minute windows is 0.9. What is the probability of a car passing the intersection in a 5-minute window? (Assuming a constant probability throughout)
Answer:
This is one of the basic probability questions asked in a software interview. Let’s start by creating an equation. Let x be the probability of a car passing the intersection in a 5-minute window.

Probability of a car passing in a 20 minute window = 1 – (probability of no car passing in a 20 minute window)
Probability of a car passing in a 20 minute window = 1 – (1 – probability of a car passing in a 5 minute window)A4
0.9= 1-(1-x)∧4
(1 -x)∧4 = 0.1
1 – x= 10∧(-0.25)
x = 1 – 10∧(-0.25) = 0.4377

Question 93.
There are 3 light bulbs in a hidden room and 3 switches outside the room that corresponds to those light bulbs. You do not know which switch affects which bulb and you cannot see inside of the room. You are allowed to go inside of the room only one time. How do you find out which switch corresponds to which bulb?
Answer:
Turn on two switches and wait for a while. Then turn off one switch and go inside the room. The bulb that is still on corresponds to the switch that is still on. Touch the remaining bulbs. The hotter bulb is the switch that you turned off, and the remaining bulb is the switch that you never turned on.

Question 94.
How would you cut a rectangular cake into two equal pieces when a rectangular piece has already been cut out of it? The cut piece can be of any size and orientation. You are only allowed to make one straight cut.
Answer:
Simple question right? There are two possible solutions to this problem. People often overlook the easier solution to this problem. Let’s start with the easiest solution. If you make one straight horizontal cut along with the height of the cake, the resulting slices are of equal sizes. But this solution may not work so well on a cake with icing. So let’s rethink.

Question 95.
John and Matt decide to play a game using a deck of cards. The game involves flipping two cards at a time. If both cards are black, they go into John’s pile and if both cards are red, they go into Matt’s pile. If one card is red and one card is black, they go into a discard pile. The game is played until all 52 cards have been flipped. The person with the most cards in their pile wins. If there is a tie, John wins. If Matt has more cards than John, then John pays Matt a dollar. What is the chance of Matt getting a dollar?
Answer:
Per deck is arranged in a way such that there are 13 black pairs. In this situation, John gets 13 black pairs. And since there are no other black cards left, Matt gets 13 red pairs too. So there’s a tie and John wins.

Suppose there are 12 black pairs in the deck. In this case, there would be 2 black cards left in the deck that would pair up with 2 other red cards in the deck. These 2 black cards would never be together since we have already claimed that there are only 12 black pairs in the deck. As a result, 2 pairs of cards end up in the discard pile. The remaining cards would all be red and Matt would get 12 red pairs too. So once again, there’s a tie and John wins.

We could continue this process through induction. Assuming there are 11 black pairs, there would be 4 other black cards that pair up with 4 other red cards and go into the discard pile. Once again, both John and Matt end up with 11 pairs of cards each and John wins.

Question 96.
What is the output of given data in JavaScript?

  • alert (‘7’+ 7 + 7)
  • alert (7 + 7)
  • alert (7+ 7‘7’)
  • alert (7 + ‘7’ + 7)

Answer:
In this JavaScript series ‘7’ representation of string format. Hence, result will be , String + number = string Number + Number = Number Therefore,

  • alert (‘7’ + 1 + 1) = 111
  • alert (7 + 7 ) = 14
  • alert (7+ 7‘7’) = 147
  • alert (7 + ‘7’ + 7) = 111

Question 97.
Uses of find() method .closestO method in Jquery?
Answer:
The method used for searches for descendant elements that match the specified selector. Syntax: $(selector) . find{filter)
The. the closest method used for matching element in DOM Tree or new jQuery object from the matching elements. Syntax: $(selector) . closest(filter)

Question 98.
How to Authenticated data coming from the right way by API?
Answer:
We can authenticate 3 basic approaches for our data coming from right way or wrong.
• HTTP Based Authentication: Simple authentication checking user-id & password by authorized users. we can also use OTP-based authentication.

API Key Based Authenticate: we can also use the API key and after matching the API key we can verify authorized users or not. Most APIs require you to sign up for an API key in order to use the API. The API key is a long string that you usually include either in the request URL or request header

HAMC based Authentication: We can crate HAMC for authentication.

Question 99.
Write a LINQ Count Query in MVC?
Answer:
IEnumerable <string> Items = new List
<string>{“3aywj”Soniya”,”Lita”,”Arohi”);
Int count = Item.Count();
// count: 3
Or
//Count between tables Example < then items.
IEnumerable <string> Items = new List <string>
{“10″,”15″,”18″,”20″,”30”}; ‘
Int Count = Items.Count (x=> x<15), // Count:3 Int Count = Items.Where (x=> x<15)Count.();
//Count:3

Question 100.
Write Select Statement Example in LINQ?
Answer:
string [ ] daysArrayDotNet =
{“Sunday”,”Monday”j”T uesday”};
Var days = from day in daysArrayDotNet select day;

//Example of Where Condition in Select Statement

Var days = from day in daysArrayDotNet where day == “Sunday”;

Question 101.
Order By Example in LINQ Select Statement?
Answer:
OrderByDecending (x =>’ x.Deliveryl.SubmissionMe);

Question 102.
Average Count Example in LINQ Statements?
Answer:
Var list = new List <int> {I,3,5,7,9};
Double result = list. Average (); //result: 5

Question 103.
Difference between Ref & Out Parameter?
Answer:
The Ref parameter means that the parameter has a value on it before going into the function. And out parameter means that the parameter has no official value before going into the function.

The ref keyword reference parameter when a passing argument in the method. While Out parameter we can pass argument in the method by out keyword.

The reference parameter or argument must be initialized first before it is passed to ref. while Out parameter is not compulsory to initialize a parameter or argument before it is passed to an out.

Example :
Out Parameter
Int m ;
Foo (out m);

Ref parameter

Int n;
Foo (ref n);

C++ Interview Questions in Java

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

C++ Interview Questions in Java

Question 1.
What is C++?
Answer:
Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language while simplifying memory management and adding several features – including a new data type known as a class (you will learn more about these later) – to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.

Question 2.
What Is Object-Oriented Programming?
Answer:
Object-Oriented Programming (OOP) is a programming paradigm where the complete software operates as a bunch of objects talking to each other. An object is a collection of data and methods that operate on its data.

Question 3.
Why OOP?
Answer:
The main advantage of OOP is better manageable code that covers the following.

  1. The overall understanding of the software is increased as the distance between the language spoken by developers and that spoken by users.
  2. Object orientation eases maintenance by the use of encapsulation. One can easily change the underlying representation by keeping the methods the same. OOP paradigm is mainly useful for relatively big software. See this for a complete example that shows the advantages of OOP over procedural programming.

Question 4.
What are the main features of OOP?
Answer:

  • Encapsulation
  • Polymorphism
  • Inheritance

Question 5.
What is encapsulation?
Answer:
Encapsulation is referred to one of the following two notions.

  1. Data hiding: A language feature to restrict access to members of an object. For example, private and protected members in C++.
  2. Bundling of data and methods together: Data and methods that operate on that data are bundled together.

Question 6.
What is Polymorphism? How is it supported by C++?
Answer:
Polymorphism means that some code or operations or objects behave differently in different contexts. In C++, the following features support polymorphism.
• Compile Time Polymorphism: Compile time polymorphism means the compiler knows which function should be called when a polymorphic call is made. C++ supports compiler time polymorphism by supporting features like templates, function overloading, and default arguments.

• Run Time Polymorphism: Run time polymorphism is supported by virtual functions. The idea is virtual functions are called according to the type of the object pointed or referred to, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime.

Question 7.
What is Abstraction?
Answer:
The first thing with which one is confronted when writing programs is the problem. Typically we are confronted with “real-life” problems and we want to make life easier by providing a program for the problem. However, real-life problems are nebulous and the first thing we have to do is to try to understand the problem to separate necessary from unnecessary details: We try to obtain our own abstract view, or model, of the problem. This process of modeling is called abstraction

Question 8.
What is the difference between realloc( ) and free()?
Answer:
The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.

Question 9.
What is function overloading and operator overloading?
Answer:
Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types, and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.

Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn’t add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).

Question 10.
What is the difference between declaration and definition?
Answer:
The declaration tells the compiler that at some later point we plan to present the definition of this declaration.

E.g.: void stars ( ) //function declaration 
The definition contains the actual implementation.
E.g.: void stars ( ) // declaratory
{
for(int j=10; j > =0; j - - ) //function body 
cout << *; 
cout << end1; }

Question 11.
What are the differences between references and pointers?
Answer:
Bothreferencesandpointerscanbeusedtochangelocalvariablesofonefunction inside another function. Bothofthemcanalsobeusedtosavecopyingofbig objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite the above similarities, there are the following differences between references and pointers.
References are less powerful than pointers

  1. Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  2. References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
  3. A reference must be initialized when declared. There is no such restriction with pointers

Due to the above limitations, references in C++ cannot be used for implementing data structures like Linked List, Tree, etc. In Java, references don’t have the above restrictions and can be used to implement all data structures. References being more powerful in Java are the main reason Java doesn’t need pointers. References are safer and easier to use:

  1. Safer: Since references must be initialized, wild references like wild pointers are unlikely to exist. It is still possible to have references that don’t refer to a valid location.
  2. Easier to use: References don’t need dereferencing operator to access the value. They can be used like normal variables. the operator is needed only at the time of declaration. Also, members of an object reference can be accessed with a dot operator, unlike pointers where an arrow operator (->) is needed to access members.

Question 12.
Explain Copy Constructor.
Answer:
It is a constructor which initializes its object member variable with another object of the same class. If you don’t implement a copy constructor in your class, the compiler automatically does it.

Question 13.
When do you call copy constructors?
Answer:
Copy constructors are called in these situations:

  • when the compiler generates a temporary object
  • when a function returns an object of that class by value
  • when the object of that class is passed by value as an argument to a function
  • when you construct an object based on another object of the same class

Question 14.
Differentiate between late binding and early binding. What are the advantages of early binding?
Answer:

  • Late binding refers to function calls that are not resolved until run time while early binding refers to the events that occur at compile time.
  • Late binding occurs through virtual functions while early binding takes place when all the information needed to call a function is known at the time of compiling. Early binding increases the efficiency. Some of the examples of early binding are normal function calls, overloaded function calls, and overloaded operators, etc.

Question 15.
What are the advantages of inheritance?
Answer:
It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 16.
What do you mean by inline function?
Answer:
The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application’s performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.

Question 17.
What is public, protected, private?
Answer:
Public, protected, and private are three access specifiers in C++. Public data members and member functions are accessible outside the class. Protected data members and member functions are only available to derived classes. Private data members and member functions can’t be accessed outside the class. However, there is an exception that can be using friend classes.
Write a function that swaps the values of two integers, using int* as the argument type.

void swap(int* a, int*b) { 
int t; 
t = *a;
*a = *b;
*b = t;
}

Question 18.
What are virtual constructors/destructors?
Answer:
Answer 1 Virtual destructors:
If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.

There is a simple solution to this problem that declares a virtual base-class destructor. This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called. Virtual constructor: Constructors cannot be virtual. Declaring a constructor as a virtual function is a syntax error.
Answer 2
Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor.

This makes all derived-class destructors virtual even though they don’t have the same name as the base-class destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Question 19.
Explain storage qualifiers in C++.
Answer:

  1. Const – This variable means that if the memory is initialized once, it should not be altered by a program.
  2. Volatile – This variable means that the value in the memory location can be altered even though nothing in the program code modifies the contents.
  3. Mutable – This variable means that a particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.

Question 20.
What is the type of “this” pointer? When does it get created?
Answer:
It is a constant pointer type. It gets created when a non-static member function of a class is called.

Question 21.
How would you differentiate between pre and post-increment operators while overloading?
Answer:
Mentioning the keyword int as the second parameter in the post-increment form of the operator++0 helps distinguish between the two forms.

Question 22.
What are the advantages of inheritance?
Answer:

  • It permits code reusability.
  • Reusability saves time in program development.
  • It encourages the reuse of proven and debugged high-quality software, thus reducing problems after a system becomes functional.

Question 23.
What is a template?
Answer:
Templates allow the creation of generic functions that admit any data type as parameters and return value without having to overload the function with all the possible data types. Until a certain point, they fulfill the functionality of a macro. Its prototype is any of the two following ones:

template <class indetifier> function_declaration; 
template type name indetifier> function_declaration;

The only difference between both prototypes is the use of keyword class or type name, its use is indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Question 24.
Define a constructor – What it is and how it might be called (2 methods).
Answer:
Answer 1
Constructor is a member function of the class, with the name of the function being the same as the class name. It also specifies how the object should be initialized. Ways of calling constructor:

  1. Implicitly: automatically by complier when an object is created.
  2. Calling the constructors explicitly is possible, but it makes the code unverifiable.

Answer 2

class Point2D{ 
int x; int y;
public Point2DO : x(0) , y(0) {} //default (no argument) constructor
};
main( ){
Point2D MyPoint; // implicit Constructor call, in order to allocate 
memory on stack, the default constructor is implicitly called.
Point2D * pPoint = new Point2D(); // Explicit constructor call, 
In order to allocate memory on HEAP we call the default constructor.
we have two pairs: new( ) and delete( ) and another pair : alloc( ) and free( ).

Question 25.
Explain differences between eg. new() and malloc()
Answer:
Answer 1:

  1. “new and delete” are preprocessors while “malloc( ) and ffee( )” are functions, [we dont use brackets will calling new or delete],
  2. no need of allocate the memory while using “new” but in “malloc( )” we have to use “sizeof( )”.
  3. “new” will initlize. the new rnemoiy to 0 but “malloc( )” gives random value in the new alloted memory location [better to use calloc( )]

Answer 2:
new( ) allocates continous space for the object instace mallocO allocates distributed space.
new( ) is castless, meaning that allocates memory for this specific type, mallocO, callocO allocate space for void * that is cated to the specific class type pointer.

Question 26.
What is the difference between class and structure?
Answer:
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

Question 27.
WhatisRTTI?
Answer:
Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a pointer or a reference to the base type. RTTI is the official way in standard C++ to discover the type of an object and to convert the type of a pointer or reference (that is, dynamic typing). The need came from practical experience with C++. RTTI replaces many Interview Questions – Homegrown versions with a solid, consistent approach.

Question 28.
W/hat is encapsulation?
Answer:
Packaging an object’s variables within its methods is called encapsulation.

Question 29.
W/hat is an object?
Answer:
Object is a software bundle of variables and related methods. Objects have state and behavior.

Question 30.
W/hat do you mean by inheritance?
Answer:
Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Question 31.
Wffiat is namespace?
Answer:
Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say it somehow, they serve to split the global scope in sub-scopes known as namespaces.
The form to use namespaces is:

namespace identifier { namespace-body }

Where identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace. For example: namespace general {int a, b;} In this case, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator ::. For example, to access the previous variables we would have to put:

general::a general::b

The functionality of namespaces is especially useful in case that there is a possibility that a global object or function can have the same name than another one, causing a redefinition error.

Question 32.
What is virtual class and friend class?
Answer:
Friend classes are used when two or more classes are designed to work .together and need access to each other’s implementation in ways that the rest of the world shouldn’t be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than mainO has.

Question 33.
WTiat is the difference between an object and a class?
Answer:
Classes and objects are separate but related concepts. Every object belongs
to a class and every class contains one or more related objects.

  • A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don’t change.
  • The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
  • An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Question 34.
What is a class?
Answer:
Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.

Question 35.
WTiat is friend function?
Answer:
As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Question 36.
WTiich recursive sorting technique always makes recursive calls to sort subarrays that are about half size of the original array?
Answer:
Mergesort always makes recursive calls to sort subarrays that are about half size of the original array, resulting in 0(n log n) time.

Question 37.
What is abstraction?
Answer:
Abstraction is of the process of hiding unwanted details from the user.

Question 38.
What are virtual functions?
Answer:
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don’t know about the derived class.

Question 39.
What is a scope resolution operator?
Answer:
A scope resolution operator (::), can be used to define the member functions of a class outside the class.

Question 40.
What do you mean by pure virtual functions?
Answer:
Pure virtual function in object oriented programming is called as virtual method that acts as a function allowing its behavior to be overridden by the class that is inheriting the pure virtual function with the same signature. This is used in case of polymorphism. It is used when a base class is being driven by the derived class and an object of the derived class referred as base or derived class type. When a derived class overrides the base class method then the output or the behavior will be called as ambiguous. To use the virtual function a virtual keyword is used. This allows the function to be defined in every derived class and use the functionality of it.

Question 40.
What is polymorphism? Explain with an example?
Answer:
“Poly” means“many” and“morph” means“form”. Polymorphismisthe ability of anobject(orreference)toassume(bereplacedby)orbecomemanydifferentformsofobject. Example: function overloading, function overriding, virtual functions. Another example can be a plus “+’ sign, used for adding two integers or for using it to concatenate two strings.

Question 41.
What is a conversion constructor?
Answer:
A constructor that accepts one argument of a different type.

Question 42.
What is the difference between a copy constructor and an overloaded assignment operator?
Answer:
A copy constructor constructs a new object by using the content of the argument object. An overloaded assignment operator assigns the contents of an existing object to another existing object of the same class.

Question 43.
Explain the ISA and HASA class relationships. How would you implement each in a class design?
Answer:
A specialized class “is” a specialization of another class and, therefore, has the ISA relationship with the other class. An Employee ISA Person. This relationship is best implemented with inheritance. Employee is derived from Person. A class may have an instance of another class. For example, an employee “has” a salary, therefore the Employee class has the HASA relationship with the Salary class. This relationship is best implemented by embedding an object of the Salary class in the Employee class.

Question 44.
What is the Standard Template Library (STL)?
Answer:
A library of container templates approved by the ANSI committee for inclusion in the standard C++ specification.
A programmer who then launches into a discussion of the generic programming model, iterators, allocators, algorithms, and such, has a higher than average understanding of the new technology that STL brings to C++ programming.

Question 45.
In C++, what is the difference between method overloading and method overriding?
Answer:
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.

Question 46.
What is a modifier?
Answer:
A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’.

Question 47.
What is an accessor?
Answer:
An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

Question 48.
Differentiate between a template class and class template.
Answer:
Template class: A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates. Class template: A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

Question 49.
Explain Stack & Heap Objects
Answer:
The memory a program uses is divided into four areas:

  • The code area – this is where the compiled program sits in memory.
  • The global area – the place where global variables are stored.
  • The heap – the place where dynamically allocated variables are allocated from.
  • The stack -the place where parameters and local variables are allocated from.

Question 50.
Explain deep copy and a shallow copy
Answer:

  • Deep copy – It involves using the contents of one object to create another instance of the same class. Here, the two objects may contain the same information but the target object will have its own buffers and resources. The destruction of either object will not affect the remaining object.
  • Shallow copy -It involves copying the contents of one object into another instance of the same class. This creates a mirror image. The two objects share the same externally contained contents of the other object to be unpredictable. This happens because of the straight copying of references and pointers.

Question 51.
Explain virtual class and friend class
Answer:
a. Virtual Base Class:
It is used in context of multiple inheritances in C++.
If you want to derive two classes from a class, and further derive one class from the two classes in the second level, you need to declare the uppermost base class as ‘virtual’ in the inherited classes. This prevents multiple copies of the uppermost base class data members when an object of the class at the third level of hierarchy is created.

b. Friend class:
When a class declares another class as its friend, it is giving complete access to all its data and methods including private and protected data and methods to the friend class member methods.
Friendship is not necessarily bi-directional. If A declares B as its friend it does not imply that A can access private data of B. It only means that B can access all data of A.
Explain the of scope resolution operator A scope resolution operator (::) is used to define the member functions of a class outside the class.
Mostly, a scope resolution operator is required when a data member is redefined by a derived class or an overridden method of the derived class wants to call the base class version of the same method.

Question 52.
What are virtual functions?
Answer:
Virtual functions are used with inheritance, they are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. Virtual keyword is used to make a function virtual. Following things are necessary to write a C++ program with runtime polymorphism use of virtual functions)

  1. A base class and a derived class.
  2. A function with same name in base class and derived class.
  3. A pointer or reference of base class type pointing or referring to an object of derived class.

Question 53.
What are the features that are provided to make a program modular?
Answer:
To create a program requires self sufficient resources, the way to make a piece of code modular so that it can be handled properly. This shows the relationship between different objects or in between the same objects. Different functions have to be used to keep the code different from the data provided. Object oriented programming allows creating a modular approach to make it more abstract and create the interactions between them. The features that are being provided in object oriented programming are:

• Encapsulation: it deals with the grouping of data and functions together at one place or it can be said in an object that defines the interface of their interaction and the relationship between them.
• Inheritance: it deals with the relationship that exists between the parent and child classes. A child can inherit the properties of the parent and it remains helpful in creating a hierarchy in the system to keep things more modular.
• Polymorphism: is a feature that deals with different values that can be used by only one function. It doesn’t have to re-create the same function again and again for different values but, it uses the same function to call different data types.

What are different data type in C

What are different data type in C

data type in C programming language declares the type of data that a variable can store and how much memory is required to store this data. C Data types can be classified into four categories:

  • Basic Data types : There are four basic data types in C(int, char, float and double.)
  • Derived Data Type : Data types that are derived from fundamental data types are called derived data types(Array, Structures, Unions and Pointers).
  • Void Data Type : Void is an empty data type that has no associated value(void).
  • Enumerated Data Type : Enumeration data type consists of set of named constant values(enum).

What are Tokens in C? what are the different Types of Tokens in C.

Tokens are the fundamental building blocks of a C Program. Punctuations, characters, words, sequence of words(strings) everything are tokens. Here are the different types of tokens in C with example.

  • Constants : 3.14, 100
  • Keyword : for, switch, float
  • Identifier : getSum, totalAmount
  • String : “ABCD”, “Jack”
  • Operators : +, -, /, *
  • Special Symbols : [], , ;

Can variable names in C have special symbols.

No, a variable’s name can be composed of alphabets, digits, and underscore only.

Can variable names in C start with underscore.

Yes, the first character of a variable name must be either an alphabet or underscore.

What is the difference between compiler, interpreter and assembler

What is the difference between compiler, interpreter and assembler.

  • Compiler : It’s a computer program(s) that transforms source code written in a programming language into machine language that is the target language which usually has a binary form known as object code.
  • Interpreter : It translates high level instructions into an intermediate form, it translates the code into the intermediate form line by line an caries out specific actions.
  • Assemblers : Assembler is software or a tool that translates Assembly language to machine code. So, an assembler is a type of a compiler and the source code is written in Assembly language.

Is C programming language is case sensitive.

Yes, C is a case sensitive language. C identifiers are case sensitive, which means ‘value’ and ‘Value’ will be treated as two different identifiers.

What are the key features and characteristics of C programming language.

Below are the some important features of C programming language.

  • Low Level Language Support
  • Structured programming language
  • Produces portable programs
  • Produces efficient programs
  • Easy to learn
  • Powerful programming language
  • Efficient Use of Pointers

What are the advantages of C programming language

Interview Questions

  • What are the benefits or advantages of C Programming Language.

What are the benefits or advantages of C programming language

  • Easy to learn: C is a very easy to learn middle level language for expressing ideas in programming in a way that most people are comfortable with.
  • Low-level Language Support: C is reasonably close to assembly machine. It support features like pointers, bytes and bit level manipulation. C allows the programmer to write directly to memory. C structures, pointers and arrays are designed to structure and manipulate memory in an efficient, machine-independent fashion. It is generally used to create hardware devices, OS, drivers, kernels etc.
  • Structured programming language: A structured programming language breaks and abstract a program into small logical components which are responsible for performing a specific task. C’s main structural components are functions or subroutines. It makes the program easier to understand and modify.
  • Produces efficient programs: C is a compiled programming language, which creates fast and efficient executable files. It also provides a set of library functions for common utilities. C provides a lot of inbuilt functions that makes the development fast.
  • Produces portable programs: C language produces portable programs, they can be run on any compiler with little or no modifications. One of the main strengths of C is that it combines universality and portability across various computer architectures.
  • Powerful programming language: C language provides a wide variety of inbuilt data types and ability to create custom data types using structures. It also provides a large set of commonly used Input/Output, Mathematical, String etc, related functions as C standard library. C has a rich set of control statements, arithmetic operators, loops etc which provides a powerful tool for programmer to implement his logic as a C program.
  • Memory Management: C is a very easy to learn middle level language for expressing ideas in programming in a way that most people are comfortable with.
  • Easy to learn: C provide support for dynamic memory allocation. In C, we can allocate and free the allocated memory at any time by calling library functions like malloc, calloc and free.